180814287SRaphael Isemann //===-- ScriptInterpreterPython.cpp ---------------------------------------===//
22c1f46dcSZachary Turner //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
62c1f46dcSZachary Turner //
72c1f46dcSZachary Turner //===----------------------------------------------------------------------===//
82c1f46dcSZachary Turner 
959998b7bSJonas Devlieghere #include "lldb/Host/Config.h"
10d055e3a0SPedro Tammela #include "lldb/lldb-enumerations.h"
11d68983e3SPavel Labath 
124e26cf2cSJonas Devlieghere #if LLDB_ENABLE_PYTHON
13d68983e3SPavel Labath 
1441de9a97SKate Stone // LLDB Python header must be included first
152c1f46dcSZachary Turner #include "lldb-python.h"
1641de9a97SKate Stone 
172c1f46dcSZachary Turner #include "PythonDataObjects.h"
189357b5d0Sserge-sans-paille #include "PythonReadline.h"
191f6a57c1SMed Ismail Bennani #include "SWIGPythonBridge.h"
2063dd5d25SJonas Devlieghere #include "ScriptInterpreterPythonImpl.h"
211f6a57c1SMed Ismail Bennani #include "ScriptedProcessPythonInterface.h"
221f6a57c1SMed Ismail Bennani 
231f6a57c1SMed Ismail Bennani #include "lldb/API/SBError.h"
2441ae8e74SKuba Mracek #include "lldb/API/SBFrame.h"
2563dd5d25SJonas Devlieghere #include "lldb/API/SBValue.h"
262c1f46dcSZachary Turner #include "lldb/Breakpoint/StoppointCallbackContext.h"
272c1f46dcSZachary Turner #include "lldb/Breakpoint/WatchpointOptions.h"
282c1f46dcSZachary Turner #include "lldb/Core/Communication.h"
292c1f46dcSZachary Turner #include "lldb/Core/Debugger.h"
302c1f46dcSZachary Turner #include "lldb/Core/PluginManager.h"
312c1f46dcSZachary Turner #include "lldb/Core/ValueObject.h"
322c1f46dcSZachary Turner #include "lldb/DataFormatters/TypeSummary.h"
334eff2d31SZachary Turner #include "lldb/Host/FileSystem.h"
342c1f46dcSZachary Turner #include "lldb/Host/HostInfo.h"
352c1f46dcSZachary Turner #include "lldb/Host/Pipe.h"
362c1f46dcSZachary Turner #include "lldb/Interpreter/CommandInterpreter.h"
372c1f46dcSZachary Turner #include "lldb/Interpreter/CommandReturnObject.h"
382c1f46dcSZachary Turner #include "lldb/Target/Thread.h"
392c1f46dcSZachary Turner #include "lldb/Target/ThreadPlan.h"
405861234eSJonas Devlieghere #include "lldb/Utility/ReproducerInstrumentation.h"
4138d0632eSPavel Labath #include "lldb/Utility/Timer.h"
4222c8efcdSZachary Turner #include "llvm/ADT/STLExtras.h"
43b9c1b51eSKate Stone #include "llvm/ADT/StringRef.h"
44d79273c9SJonas Devlieghere #include "llvm/Support/Error.h"
457d86ee5aSZachary Turner #include "llvm/Support/FileSystem.h"
462fce1137SLawrence D'Anna #include "llvm/Support/FormatAdapters.h"
472c1f46dcSZachary Turner 
4876e47d48SRaphael Isemann #include <cstdio>
4976e47d48SRaphael Isemann #include <cstdlib>
509a6c7572SJonas Devlieghere #include <memory>
519a6c7572SJonas Devlieghere #include <mutex>
529a6c7572SJonas Devlieghere #include <string>
539a6c7572SJonas Devlieghere 
542c1f46dcSZachary Turner using namespace lldb;
552c1f46dcSZachary Turner using namespace lldb_private;
56722b6189SLawrence D'Anna using namespace lldb_private::python;
5704edd189SLawrence D'Anna using llvm::Expected;
582c1f46dcSZachary Turner 
59bba9ba8dSJonas Devlieghere LLDB_PLUGIN_DEFINE(ScriptInterpreterPython)
60fbb4d1e4SJonas Devlieghere 
61b01b1087SJonas Devlieghere // Defined in the SWIG source file
62b01b1087SJonas Devlieghere #if PY_MAJOR_VERSION >= 3
63b01b1087SJonas Devlieghere extern "C" PyObject *PyInit__lldb(void);
64b01b1087SJonas Devlieghere 
65b01b1087SJonas Devlieghere #define LLDBSwigPyInit PyInit__lldb
66b01b1087SJonas Devlieghere 
67b01b1087SJonas Devlieghere #else
68b01b1087SJonas Devlieghere extern "C" void init_lldb(void);
69b01b1087SJonas Devlieghere 
70b01b1087SJonas Devlieghere #define LLDBSwigPyInit init_lldb
71b01b1087SJonas Devlieghere #endif
72b01b1087SJonas Devlieghere 
73*049ae930SJonas Devlieghere #if defined(_WIN32)
74*049ae930SJonas Devlieghere // Don't mess with the signal handlers on Windows.
75*049ae930SJonas Devlieghere #define LLDB_USE_PYTHON_SET_INTERRUPT 0
76*049ae930SJonas Devlieghere #else
77*049ae930SJonas Devlieghere // PyErr_SetInterrupt was introduced in 3.2.
78*049ae930SJonas Devlieghere #define LLDB_USE_PYTHON_SET_INTERRUPT                                          \
79*049ae930SJonas Devlieghere   (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
80*049ae930SJonas Devlieghere #endif
81b01b1087SJonas Devlieghere 
82d055e3a0SPedro Tammela static ScriptInterpreterPythonImpl *GetPythonInterpreter(Debugger &debugger) {
83d055e3a0SPedro Tammela   ScriptInterpreter *script_interpreter =
84d055e3a0SPedro Tammela       debugger.GetScriptInterpreter(true, lldb::eScriptLanguagePython);
85d055e3a0SPedro Tammela   return static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
86d055e3a0SPedro Tammela }
87d055e3a0SPedro Tammela 
882c1f46dcSZachary Turner static bool g_initialized = false;
892c1f46dcSZachary Turner 
90b9c1b51eSKate Stone namespace {
9122c8efcdSZachary Turner 
9205097246SAdrian Prantl // Initializing Python is not a straightforward process.  We cannot control
9305097246SAdrian Prantl // what external code may have done before getting to this point in LLDB,
9405097246SAdrian Prantl // including potentially having already initialized Python, so we need to do a
9505097246SAdrian Prantl // lot of work to ensure that the existing state of the system is maintained
9605097246SAdrian Prantl // across our initialization.  We do this by using an RAII pattern where we
9705097246SAdrian Prantl // save off initial state at the beginning, and restore it at the end
98b9c1b51eSKate Stone struct InitializePythonRAII {
99079fe48aSZachary Turner public:
1009494c510SJonas Devlieghere   InitializePythonRAII() {
101079fe48aSZachary Turner     InitializePythonHome();
102079fe48aSZachary Turner 
1039357b5d0Sserge-sans-paille #ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
1049357b5d0Sserge-sans-paille     // Python's readline is incompatible with libedit being linked into lldb.
1059357b5d0Sserge-sans-paille     // Provide a patched version local to the embedded interpreter.
1069357b5d0Sserge-sans-paille     bool ReadlinePatched = false;
1079357b5d0Sserge-sans-paille     for (auto *p = PyImport_Inittab; p->name != NULL; p++) {
1089357b5d0Sserge-sans-paille       if (strcmp(p->name, "readline") == 0) {
1099357b5d0Sserge-sans-paille         p->initfunc = initlldb_readline;
1109357b5d0Sserge-sans-paille         break;
1119357b5d0Sserge-sans-paille       }
1129357b5d0Sserge-sans-paille     }
1139357b5d0Sserge-sans-paille     if (!ReadlinePatched) {
1149357b5d0Sserge-sans-paille       PyImport_AppendInittab("readline", initlldb_readline);
1159357b5d0Sserge-sans-paille       ReadlinePatched = true;
1169357b5d0Sserge-sans-paille     }
1179357b5d0Sserge-sans-paille #endif
1189357b5d0Sserge-sans-paille 
11974587a0eSVadim Chugunov     // Register _lldb as a built-in module.
12005495c5dSJonas Devlieghere     PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
12174587a0eSVadim Chugunov 
122079fe48aSZachary Turner // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
123079fe48aSZachary Turner // calling `Py_Initialize` and `PyEval_InitThreads`.  < 3.2 requires that you
124079fe48aSZachary Turner // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
125079fe48aSZachary Turner #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
126079fe48aSZachary Turner     Py_InitializeEx(0);
127079fe48aSZachary Turner     InitializeThreadsPrivate();
128079fe48aSZachary Turner #else
129079fe48aSZachary Turner     InitializeThreadsPrivate();
130079fe48aSZachary Turner     Py_InitializeEx(0);
131079fe48aSZachary Turner #endif
132079fe48aSZachary Turner   }
133079fe48aSZachary Turner 
134b9c1b51eSKate Stone   ~InitializePythonRAII() {
135b9c1b51eSKate Stone     if (m_was_already_initialized) {
1363b7e1981SPavel Labath       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
1373b7e1981SPavel Labath       LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
1381b6700efSTatyana Krasnukha                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
139079fe48aSZachary Turner       PyGILState_Release(m_gil_state);
140b9c1b51eSKate Stone     } else {
141079fe48aSZachary Turner       // We initialized the threads in this function, just unlock the GIL.
142079fe48aSZachary Turner       PyEval_SaveThread();
143079fe48aSZachary Turner     }
144079fe48aSZachary Turner   }
145079fe48aSZachary Turner 
146079fe48aSZachary Turner private:
147b9c1b51eSKate Stone   void InitializePythonHome() {
1483ec3f62fSHaibo Huang #if LLDB_EMBED_PYTHON_HOME
1493ec3f62fSHaibo Huang #if PY_MAJOR_VERSION >= 3
1503ec3f62fSHaibo Huang     typedef wchar_t* str_type;
1513ec3f62fSHaibo Huang #else
1523ec3f62fSHaibo Huang     typedef char* str_type;
1533ec3f62fSHaibo Huang #endif
1543ec3f62fSHaibo Huang     static str_type g_python_home = []() -> str_type {
1553ec3f62fSHaibo Huang       const char *lldb_python_home = LLDB_PYTHON_HOME;
1563ec3f62fSHaibo Huang       const char *absolute_python_home = nullptr;
1573ec3f62fSHaibo Huang       llvm::SmallString<64> path;
1583ec3f62fSHaibo Huang       if (llvm::sys::path::is_absolute(lldb_python_home)) {
1593ec3f62fSHaibo Huang         absolute_python_home = lldb_python_home;
1603ec3f62fSHaibo Huang       } else {
1613ec3f62fSHaibo Huang         FileSpec spec = HostInfo::GetShlibDir();
1623ec3f62fSHaibo Huang         if (!spec)
1633ec3f62fSHaibo Huang           return nullptr;
1643ec3f62fSHaibo Huang         spec.GetPath(path);
1653ec3f62fSHaibo Huang         llvm::sys::path::append(path, lldb_python_home);
1663ec3f62fSHaibo Huang         absolute_python_home = path.c_str();
1673ec3f62fSHaibo Huang       }
16822c8efcdSZachary Turner #if PY_MAJOR_VERSION >= 3
16922c8efcdSZachary Turner       size_t size = 0;
1703ec3f62fSHaibo Huang       return Py_DecodeLocale(absolute_python_home, &size);
17122c8efcdSZachary Turner #else
1723ec3f62fSHaibo Huang       return strdup(absolute_python_home);
17322c8efcdSZachary Turner #endif
1743ec3f62fSHaibo Huang     }();
1753ec3f62fSHaibo Huang     if (g_python_home != nullptr) {
176079fe48aSZachary Turner       Py_SetPythonHome(g_python_home);
1773ec3f62fSHaibo Huang     }
178386f00dbSDavide Italiano #else
179386f00dbSDavide Italiano #if defined(__APPLE__) && PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION == 7
18063dd5d25SJonas Devlieghere     // For Darwin, the only Python version supported is the one shipped in the
18163dd5d25SJonas Devlieghere     // OS OS and linked with lldb. Other installation of Python may have higher
1824f9cb260SDavide Italiano     // priorities in the path, overriding PYTHONHOME and causing
1834f9cb260SDavide Italiano     // problems/incompatibilities. In order to avoid confusion, always hardcode
1844f9cb260SDavide Italiano     // the PythonHome to be right, as it's not going to change.
18563dd5d25SJonas Devlieghere     static char path[] =
18663dd5d25SJonas Devlieghere         "/System/Library/Frameworks/Python.framework/Versions/2.7";
1874f9cb260SDavide Italiano     Py_SetPythonHome(path);
188386f00dbSDavide Italiano #endif
189386f00dbSDavide Italiano #endif
19022c8efcdSZachary Turner   }
19122c8efcdSZachary Turner 
192b9c1b51eSKate Stone   void InitializeThreadsPrivate() {
1931b6700efSTatyana Krasnukha // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself,
1941b6700efSTatyana Krasnukha // so there is no way to determine whether the embedded interpreter
1951b6700efSTatyana Krasnukha // was already initialized by some external code. `PyEval_ThreadsInitialized`
1961b6700efSTatyana Krasnukha // would always return `true` and `PyGILState_Ensure/Release` flow would be
1971b6700efSTatyana Krasnukha // executed instead of unlocking GIL with `PyEval_SaveThread`. When
1981b6700efSTatyana Krasnukha // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock.
1991b6700efSTatyana Krasnukha #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3)
2001b6700efSTatyana Krasnukha     // The only case we should go further and acquire the GIL: it is unlocked.
2011b6700efSTatyana Krasnukha     if (PyGILState_Check())
2021b6700efSTatyana Krasnukha       return;
2031b6700efSTatyana Krasnukha #endif
2041b6700efSTatyana Krasnukha 
205b9c1b51eSKate Stone     if (PyEval_ThreadsInitialized()) {
2063b7e1981SPavel Labath       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
207079fe48aSZachary Turner 
208079fe48aSZachary Turner       m_was_already_initialized = true;
209079fe48aSZachary Turner       m_gil_state = PyGILState_Ensure();
2103b7e1981SPavel Labath       LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n",
211079fe48aSZachary Turner                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
212079fe48aSZachary Turner       return;
213079fe48aSZachary Turner     }
214079fe48aSZachary Turner 
215079fe48aSZachary Turner     // InitThreads acquires the GIL if it hasn't been called before.
216079fe48aSZachary Turner     PyEval_InitThreads();
217079fe48aSZachary Turner   }
218079fe48aSZachary Turner 
2199494c510SJonas Devlieghere   PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
2209494c510SJonas Devlieghere   bool m_was_already_initialized = false;
221079fe48aSZachary Turner };
22263dd5d25SJonas Devlieghere } // namespace
2232c1f46dcSZachary Turner 
2242df331b0SPavel Labath void ScriptInterpreterPython::ComputePythonDirForApple(
2252df331b0SPavel Labath     llvm::SmallVectorImpl<char> &path) {
2262df331b0SPavel Labath   auto style = llvm::sys::path::Style::posix;
2272df331b0SPavel Labath 
2282df331b0SPavel Labath   llvm::StringRef path_ref(path.begin(), path.size());
2292df331b0SPavel Labath   auto rbegin = llvm::sys::path::rbegin(path_ref, style);
2302df331b0SPavel Labath   auto rend = llvm::sys::path::rend(path_ref);
2312df331b0SPavel Labath   auto framework = std::find(rbegin, rend, "LLDB.framework");
2322df331b0SPavel Labath   if (framework == rend) {
23361f471a7SHaibo Huang     ComputePythonDir(path);
2342df331b0SPavel Labath     return;
2352df331b0SPavel Labath   }
2362df331b0SPavel Labath   path.resize(framework - rend);
2372df331b0SPavel Labath   llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
2382df331b0SPavel Labath }
2392df331b0SPavel Labath 
24061f471a7SHaibo Huang void ScriptInterpreterPython::ComputePythonDir(
2412df331b0SPavel Labath     llvm::SmallVectorImpl<char> &path) {
2422df331b0SPavel Labath   // Build the path by backing out of the lib dir, then building with whatever
2432df331b0SPavel Labath   // the real python interpreter uses.  (e.g. lib for most, lib64 on RHEL
24461f471a7SHaibo Huang   // x86_64, or bin on Windows).
24561f471a7SHaibo Huang   llvm::sys::path::remove_filename(path);
24661f471a7SHaibo Huang   llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
2470016b450SHaibo Huang 
2480016b450SHaibo Huang #if defined(_WIN32)
2490016b450SHaibo Huang   // This will be injected directly through FileSpec.GetDirectory().SetString(),
2500016b450SHaibo Huang   // so we need to normalize manually.
2510016b450SHaibo Huang   std::replace(path.begin(), path.end(), '\\', '/');
2520016b450SHaibo Huang #endif
2532df331b0SPavel Labath }
2542df331b0SPavel Labath 
2552df331b0SPavel Labath FileSpec ScriptInterpreterPython::GetPythonDir() {
2562df331b0SPavel Labath   static FileSpec g_spec = []() {
2572df331b0SPavel Labath     FileSpec spec = HostInfo::GetShlibDir();
2582df331b0SPavel Labath     if (!spec)
2592df331b0SPavel Labath       return FileSpec();
2602df331b0SPavel Labath     llvm::SmallString<64> path;
2612df331b0SPavel Labath     spec.GetPath(path);
2622df331b0SPavel Labath 
2632df331b0SPavel Labath #if defined(__APPLE__)
2642df331b0SPavel Labath     ComputePythonDirForApple(path);
2652df331b0SPavel Labath #else
26661f471a7SHaibo Huang     ComputePythonDir(path);
2672df331b0SPavel Labath #endif
2682df331b0SPavel Labath     spec.GetDirectory().SetString(path);
2692df331b0SPavel Labath     return spec;
2702df331b0SPavel Labath   }();
2712df331b0SPavel Labath   return g_spec;
2722df331b0SPavel Labath }
2732df331b0SPavel Labath 
2744c2cf3a3SLawrence D'Anna static const char GetInterpreterInfoScript[] = R"(
2754c2cf3a3SLawrence D'Anna import os
2764c2cf3a3SLawrence D'Anna import sys
2774c2cf3a3SLawrence D'Anna 
2784c2cf3a3SLawrence D'Anna def main(lldb_python_dir, python_exe_relative_path):
2794c2cf3a3SLawrence D'Anna   info = {
2804c2cf3a3SLawrence D'Anna     "lldb-pythonpath": lldb_python_dir,
2814c2cf3a3SLawrence D'Anna     "language": "python",
2824c2cf3a3SLawrence D'Anna     "prefix": sys.prefix,
2834c2cf3a3SLawrence D'Anna     "executable": os.path.join(sys.prefix, python_exe_relative_path)
2844c2cf3a3SLawrence D'Anna   }
2854c2cf3a3SLawrence D'Anna   return info
2864c2cf3a3SLawrence D'Anna )";
2874c2cf3a3SLawrence D'Anna 
2884c2cf3a3SLawrence D'Anna static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH;
2894c2cf3a3SLawrence D'Anna 
290bbef51ebSLawrence D'Anna StructuredData::DictionarySP ScriptInterpreterPython::GetInterpreterInfo() {
291bbef51ebSLawrence D'Anna   GIL gil;
292bbef51ebSLawrence D'Anna   FileSpec python_dir_spec = GetPythonDir();
293bbef51ebSLawrence D'Anna   if (!python_dir_spec)
294bbef51ebSLawrence D'Anna     return nullptr;
2954c2cf3a3SLawrence D'Anna   PythonScript get_info(GetInterpreterInfoScript);
2964c2cf3a3SLawrence D'Anna   auto info_json = unwrapIgnoringErrors(
2974c2cf3a3SLawrence D'Anna       As<PythonDictionary>(get_info(PythonString(python_dir_spec.GetPath()),
2984c2cf3a3SLawrence D'Anna                                     PythonString(python_exe_relative_path))));
299bbef51ebSLawrence D'Anna   if (!info_json)
300bbef51ebSLawrence D'Anna     return nullptr;
301bbef51ebSLawrence D'Anna   return info_json.CreateStructuredDictionary();
302bbef51ebSLawrence D'Anna }
303bbef51ebSLawrence D'Anna 
304004a264fSPavel Labath void ScriptInterpreterPython::SharedLibraryDirectoryHelper(
305004a264fSPavel Labath     FileSpec &this_file) {
306004a264fSPavel Labath   // When we're loaded from python, this_file will point to the file inside the
307004a264fSPavel Labath   // python package directory. Replace it with the one in the lib directory.
308004a264fSPavel Labath #ifdef _WIN32
309004a264fSPavel Labath   // On windows, we need to manually back out of the python tree, and go into
310004a264fSPavel Labath   // the bin directory. This is pretty much the inverse of what ComputePythonDir
311004a264fSPavel Labath   // does.
312004a264fSPavel Labath   if (this_file.GetFileNameExtension() == ConstString(".pyd")) {
313004a264fSPavel Labath     this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd
314004a264fSPavel Labath     this_file.RemoveLastPathComponent(); // lldb
3152e826088SPavel Labath     llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
3162e826088SPavel Labath     for (auto it = llvm::sys::path::begin(libdir),
3172e826088SPavel Labath               end = llvm::sys::path::end(libdir);
318004a264fSPavel Labath          it != end; ++it)
319004a264fSPavel Labath       this_file.RemoveLastPathComponent();
320004a264fSPavel Labath     this_file.AppendPathComponent("bin");
321004a264fSPavel Labath     this_file.AppendPathComponent("liblldb.dll");
322004a264fSPavel Labath   }
323004a264fSPavel Labath #else
324004a264fSPavel Labath   // The python file is a symlink, so we can find the real library by resolving
325004a264fSPavel Labath   // it. We can do this unconditionally.
326004a264fSPavel Labath   FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
327004a264fSPavel Labath #endif
328004a264fSPavel Labath }
329004a264fSPavel Labath 
3305f4980f0SPavel Labath llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() {
33163dd5d25SJonas Devlieghere   return "Embedded Python interpreter";
33263dd5d25SJonas Devlieghere }
33363dd5d25SJonas Devlieghere 
33463dd5d25SJonas Devlieghere void ScriptInterpreterPython::Initialize() {
33563dd5d25SJonas Devlieghere   static llvm::once_flag g_once_flag;
33663dd5d25SJonas Devlieghere 
33763dd5d25SJonas Devlieghere   llvm::call_once(g_once_flag, []() {
33863dd5d25SJonas Devlieghere     PluginManager::RegisterPlugin(GetPluginNameStatic(),
33963dd5d25SJonas Devlieghere                                   GetPluginDescriptionStatic(),
34063dd5d25SJonas Devlieghere                                   lldb::eScriptLanguagePython,
34163dd5d25SJonas Devlieghere                                   ScriptInterpreterPythonImpl::CreateInstance);
34263dd5d25SJonas Devlieghere   });
34363dd5d25SJonas Devlieghere }
34463dd5d25SJonas Devlieghere 
34563dd5d25SJonas Devlieghere void ScriptInterpreterPython::Terminate() {}
34663dd5d25SJonas Devlieghere 
34763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::Locker(
34863dd5d25SJonas Devlieghere     ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
349b07823f3SLawrence D'Anna     uint16_t on_leave, FileSP in, FileSP out, FileSP err)
35063dd5d25SJonas Devlieghere     : ScriptInterpreterLocker(),
35163dd5d25SJonas Devlieghere       m_teardown_session((on_leave & TearDownSession) == TearDownSession),
35263dd5d25SJonas Devlieghere       m_python_interpreter(py_interpreter) {
35363dd5d25SJonas Devlieghere   DoAcquireLock();
35463dd5d25SJonas Devlieghere   if ((on_entry & InitSession) == InitSession) {
35563dd5d25SJonas Devlieghere     if (!DoInitSession(on_entry, in, out, err)) {
35663dd5d25SJonas Devlieghere       // Don't teardown the session if we didn't init it.
35763dd5d25SJonas Devlieghere       m_teardown_session = false;
35863dd5d25SJonas Devlieghere     }
35963dd5d25SJonas Devlieghere   }
36063dd5d25SJonas Devlieghere }
36163dd5d25SJonas Devlieghere 
36263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
36363dd5d25SJonas Devlieghere   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
36463dd5d25SJonas Devlieghere   m_GILState = PyGILState_Ensure();
36563dd5d25SJonas Devlieghere   LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked",
36663dd5d25SJonas Devlieghere             m_GILState == PyGILState_UNLOCKED ? "un" : "");
36763dd5d25SJonas Devlieghere 
36863dd5d25SJonas Devlieghere   // we need to save the thread state when we first start the command because
36963dd5d25SJonas Devlieghere   // we might decide to interrupt it while some action is taking place outside
37063dd5d25SJonas Devlieghere   // of Python (e.g. printing to screen, waiting for the network, ...) in that
37163dd5d25SJonas Devlieghere   // case, _PyThreadState_Current will be NULL - and we would be unable to set
37263dd5d25SJonas Devlieghere   // the asynchronous exception - not a desirable situation
37363dd5d25SJonas Devlieghere   m_python_interpreter->SetThreadState(PyThreadState_Get());
37463dd5d25SJonas Devlieghere   m_python_interpreter->IncrementLockCount();
37563dd5d25SJonas Devlieghere   return true;
37663dd5d25SJonas Devlieghere }
37763dd5d25SJonas Devlieghere 
37863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
379b07823f3SLawrence D'Anna                                                         FileSP in, FileSP out,
380b07823f3SLawrence D'Anna                                                         FileSP err) {
38163dd5d25SJonas Devlieghere   if (!m_python_interpreter)
38263dd5d25SJonas Devlieghere     return false;
38363dd5d25SJonas Devlieghere   return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
38463dd5d25SJonas Devlieghere }
38563dd5d25SJonas Devlieghere 
38663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
38763dd5d25SJonas Devlieghere   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
38863dd5d25SJonas Devlieghere   LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
38963dd5d25SJonas Devlieghere             m_GILState == PyGILState_UNLOCKED ? "un" : "");
39063dd5d25SJonas Devlieghere   PyGILState_Release(m_GILState);
39163dd5d25SJonas Devlieghere   m_python_interpreter->DecrementLockCount();
39263dd5d25SJonas Devlieghere   return true;
39363dd5d25SJonas Devlieghere }
39463dd5d25SJonas Devlieghere 
39563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
39663dd5d25SJonas Devlieghere   if (!m_python_interpreter)
39763dd5d25SJonas Devlieghere     return false;
39863dd5d25SJonas Devlieghere   m_python_interpreter->LeaveSession();
39963dd5d25SJonas Devlieghere   return true;
40063dd5d25SJonas Devlieghere }
40163dd5d25SJonas Devlieghere 
40263dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::~Locker() {
40363dd5d25SJonas Devlieghere   if (m_teardown_session)
40463dd5d25SJonas Devlieghere     DoTearDownSession();
40563dd5d25SJonas Devlieghere   DoFreeLock();
40663dd5d25SJonas Devlieghere }
40763dd5d25SJonas Devlieghere 
4088d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger)
4098d1fb843SJonas Devlieghere     : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
41063dd5d25SJonas Devlieghere       m_saved_stderr(), m_main_module(),
41163dd5d25SJonas Devlieghere       m_session_dict(PyInitialValue::Invalid),
41263dd5d25SJonas Devlieghere       m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(),
41363dd5d25SJonas Devlieghere       m_run_one_line_str_global(),
4148d1fb843SJonas Devlieghere       m_dictionary_name(m_debugger.GetInstanceName().AsCString()),
415ea1752a7SJonas Devlieghere       m_active_io_handler(eIOHandlerNone), m_session_is_active(false),
41664ec505dSJonas Devlieghere       m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
417ea1752a7SJonas Devlieghere       m_command_thread_state(nullptr) {
41863dd5d25SJonas Devlieghere   InitializePrivate();
41963dd5d25SJonas Devlieghere 
4201f6a57c1SMed Ismail Bennani   m_scripted_process_interface_up =
4211f6a57c1SMed Ismail Bennani       std::make_unique<ScriptedProcessPythonInterface>(*this);
4221f6a57c1SMed Ismail Bennani 
42363dd5d25SJonas Devlieghere   m_dictionary_name.append("_dict");
42463dd5d25SJonas Devlieghere   StreamString run_string;
42563dd5d25SJonas Devlieghere   run_string.Printf("%s = dict()", m_dictionary_name.c_str());
42663dd5d25SJonas Devlieghere 
42763dd5d25SJonas Devlieghere   Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock);
42863dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
42963dd5d25SJonas Devlieghere 
43063dd5d25SJonas Devlieghere   run_string.Clear();
43163dd5d25SJonas Devlieghere   run_string.Printf(
43263dd5d25SJonas Devlieghere       "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
43363dd5d25SJonas Devlieghere       m_dictionary_name.c_str());
43463dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
43563dd5d25SJonas Devlieghere 
43663dd5d25SJonas Devlieghere   // Reloading modules requires a different syntax in Python 2 and Python 3.
43763dd5d25SJonas Devlieghere   // This provides a consistent syntax no matter what version of Python.
43863dd5d25SJonas Devlieghere   run_string.Clear();
43963dd5d25SJonas Devlieghere   run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')",
44063dd5d25SJonas Devlieghere                     m_dictionary_name.c_str());
44163dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
44263dd5d25SJonas Devlieghere 
44363dd5d25SJonas Devlieghere   // WARNING: temporary code that loads Cocoa formatters - this should be done
44463dd5d25SJonas Devlieghere   // on a per-platform basis rather than loading the whole set and letting the
44563dd5d25SJonas Devlieghere   // individual formatter classes exploit APIs to check whether they can/cannot
44663dd5d25SJonas Devlieghere   // do their task
44763dd5d25SJonas Devlieghere   run_string.Clear();
44863dd5d25SJonas Devlieghere   run_string.Printf(
44963dd5d25SJonas Devlieghere       "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')",
45063dd5d25SJonas Devlieghere       m_dictionary_name.c_str());
45163dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
45263dd5d25SJonas Devlieghere   run_string.Clear();
45363dd5d25SJonas Devlieghere 
45463dd5d25SJonas Devlieghere   run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
45563dd5d25SJonas Devlieghere                     "lldb.embedded_interpreter import run_python_interpreter; "
45663dd5d25SJonas Devlieghere                     "from lldb.embedded_interpreter import run_one_line')",
45763dd5d25SJonas Devlieghere                     m_dictionary_name.c_str());
45863dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
45963dd5d25SJonas Devlieghere   run_string.Clear();
46063dd5d25SJonas Devlieghere 
46163dd5d25SJonas Devlieghere   run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
46263dd5d25SJonas Devlieghere                     "; pydoc.pager = pydoc.plainpager')",
4638d1fb843SJonas Devlieghere                     m_dictionary_name.c_str(), m_debugger.GetID());
46463dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
46563dd5d25SJonas Devlieghere }
46663dd5d25SJonas Devlieghere 
46763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
46863dd5d25SJonas Devlieghere   // the session dictionary may hold objects with complex state which means
46963dd5d25SJonas Devlieghere   // that they may need to be torn down with some level of smarts and that, in
47063dd5d25SJonas Devlieghere   // turn, requires a valid thread state force Python to procure itself such a
47163dd5d25SJonas Devlieghere   // thread state, nuke the session dictionary and then release it for others
47263dd5d25SJonas Devlieghere   // to use and proceed with the rest of the shutdown
47363dd5d25SJonas Devlieghere   auto gil_state = PyGILState_Ensure();
47463dd5d25SJonas Devlieghere   m_session_dict.Reset();
47563dd5d25SJonas Devlieghere   PyGILState_Release(gil_state);
47663dd5d25SJonas Devlieghere }
47763dd5d25SJonas Devlieghere 
47863dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler,
47963dd5d25SJonas Devlieghere                                                      bool interactive) {
4802c1f46dcSZachary Turner   const char *instructions = nullptr;
4812c1f46dcSZachary Turner 
482b9c1b51eSKate Stone   switch (m_active_io_handler) {
4832c1f46dcSZachary Turner   case eIOHandlerNone:
4842c1f46dcSZachary Turner     break;
4852c1f46dcSZachary Turner   case eIOHandlerBreakpoint:
4862c1f46dcSZachary Turner     instructions = R"(Enter your Python command(s). Type 'DONE' to end.
4872c1f46dcSZachary Turner def function (frame, bp_loc, internal_dict):
4882c1f46dcSZachary Turner     """frame: the lldb.SBFrame for the location at which you stopped
4892c1f46dcSZachary Turner        bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
4902c1f46dcSZachary Turner        internal_dict: an LLDB support object not to be used"""
4912c1f46dcSZachary Turner )";
4922c1f46dcSZachary Turner     break;
4932c1f46dcSZachary Turner   case eIOHandlerWatchpoint:
4942c1f46dcSZachary Turner     instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
4952c1f46dcSZachary Turner     break;
4962c1f46dcSZachary Turner   }
4972c1f46dcSZachary Turner 
498b9c1b51eSKate Stone   if (instructions) {
4997ca15ba7SLawrence D'Anna     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
5000affb582SDave Lee     if (output_sp && interactive) {
5012c1f46dcSZachary Turner       output_sp->PutCString(instructions);
5022c1f46dcSZachary Turner       output_sp->Flush();
5032c1f46dcSZachary Turner     }
5042c1f46dcSZachary Turner   }
5052c1f46dcSZachary Turner }
5062c1f46dcSZachary Turner 
50763dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler,
508b9c1b51eSKate Stone                                                          std::string &data) {
5092c1f46dcSZachary Turner   io_handler.SetIsDone(true);
5108d1fb843SJonas Devlieghere   bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
5112c1f46dcSZachary Turner 
512b9c1b51eSKate Stone   switch (m_active_io_handler) {
5132c1f46dcSZachary Turner   case eIOHandlerNone:
5142c1f46dcSZachary Turner     break;
515b9c1b51eSKate Stone   case eIOHandlerBreakpoint: {
516cfb96d84SJim Ingham     std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
517cfb96d84SJim Ingham         (std::vector<std::reference_wrapper<BreakpointOptions>> *)
518cfb96d84SJim Ingham             io_handler.GetUserData();
519cfb96d84SJim Ingham     for (BreakpointOptions &bp_options : *bp_options_vec) {
5202c1f46dcSZachary Turner 
521a8f3ae7cSJonas Devlieghere       auto data_up = std::make_unique<CommandDataPython>();
522d5b44036SJonas Devlieghere       if (!data_up)
5234e4fbe82SZachary Turner         break;
524d5b44036SJonas Devlieghere       data_up->user_source.SplitIntoLines(data);
5252c1f46dcSZachary Turner 
526738af7a6SJim Ingham       StructuredData::ObjectSP empty_args_sp;
527d5b44036SJonas Devlieghere       if (GenerateBreakpointCommandCallbackData(data_up->user_source,
528738af7a6SJim Ingham                                                 data_up->script_source,
529738af7a6SJim Ingham                                                 false)
530b9c1b51eSKate Stone               .Success()) {
5314e4fbe82SZachary Turner         auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
532d5b44036SJonas Devlieghere             std::move(data_up));
533cfb96d84SJim Ingham         bp_options.SetCallback(
53463dd5d25SJonas Devlieghere             ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
535b9c1b51eSKate Stone       } else if (!batch_mode) {
5367ca15ba7SLawrence D'Anna         StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
537b9c1b51eSKate Stone         if (error_sp) {
5382c1f46dcSZachary Turner           error_sp->Printf("Warning: No command attached to breakpoint.\n");
5392c1f46dcSZachary Turner           error_sp->Flush();
5402c1f46dcSZachary Turner         }
5412c1f46dcSZachary Turner       }
5422c1f46dcSZachary Turner     }
5432c1f46dcSZachary Turner     m_active_io_handler = eIOHandlerNone;
544b9c1b51eSKate Stone   } break;
545b9c1b51eSKate Stone   case eIOHandlerWatchpoint: {
546b9c1b51eSKate Stone     WatchpointOptions *wp_options =
547b9c1b51eSKate Stone         (WatchpointOptions *)io_handler.GetUserData();
548a8f3ae7cSJonas Devlieghere     auto data_up = std::make_unique<WatchpointOptions::CommandData>();
549d5b44036SJonas Devlieghere     data_up->user_source.SplitIntoLines(data);
5502c1f46dcSZachary Turner 
551d5b44036SJonas Devlieghere     if (GenerateWatchpointCommandCallbackData(data_up->user_source,
552d5b44036SJonas Devlieghere                                               data_up->script_source)) {
5534e4fbe82SZachary Turner       auto baton_sp =
554d5b44036SJonas Devlieghere           std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
555b9c1b51eSKate Stone       wp_options->SetCallback(
55663dd5d25SJonas Devlieghere           ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
557b9c1b51eSKate Stone     } else if (!batch_mode) {
5587ca15ba7SLawrence D'Anna       StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
559b9c1b51eSKate Stone       if (error_sp) {
5602c1f46dcSZachary Turner         error_sp->Printf("Warning: No command attached to breakpoint.\n");
5612c1f46dcSZachary Turner         error_sp->Flush();
5622c1f46dcSZachary Turner       }
5632c1f46dcSZachary Turner     }
5642c1f46dcSZachary Turner     m_active_io_handler = eIOHandlerNone;
565b9c1b51eSKate Stone   } break;
5662c1f46dcSZachary Turner   }
5672c1f46dcSZachary Turner }
5682c1f46dcSZachary Turner 
56963dd5d25SJonas Devlieghere lldb::ScriptInterpreterSP
5708d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) {
5718d1fb843SJonas Devlieghere   return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
57263dd5d25SJonas Devlieghere }
5732c1f46dcSZachary Turner 
57463dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::LeaveSession() {
5752c1f46dcSZachary Turner   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
5762c1f46dcSZachary Turner   if (log)
57763dd5d25SJonas Devlieghere     log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
5782c1f46dcSZachary Turner 
57920b52c33SJonas Devlieghere   // Unset the LLDB global variables.
58020b52c33SJonas Devlieghere   PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
58120b52c33SJonas Devlieghere                      "= None; lldb.thread = None; lldb.frame = None");
58220b52c33SJonas Devlieghere 
58305097246SAdrian Prantl   // checking that we have a valid thread state - since we use our own
58405097246SAdrian Prantl   // threading and locking in some (rare) cases during cleanup Python may end
58505097246SAdrian Prantl   // up believing we have no thread state and PyImport_AddModule will crash if
58605097246SAdrian Prantl   // that is the case - since that seems to only happen when destroying the
58705097246SAdrian Prantl   // SBDebugger, we can make do without clearing up stdout and stderr
5882c1f46dcSZachary Turner 
5892c1f46dcSZachary Turner   // rdar://problem/11292882
590b9c1b51eSKate Stone   // When the current thread state is NULL, PyThreadState_Get() issues a fatal
591b9c1b51eSKate Stone   // error.
592b9c1b51eSKate Stone   if (PyThreadState_GetDict()) {
5932c1f46dcSZachary Turner     PythonDictionary &sys_module_dict = GetSysModuleDictionary();
594b9c1b51eSKate Stone     if (sys_module_dict.IsValid()) {
595b9c1b51eSKate Stone       if (m_saved_stdin.IsValid()) {
596f8b22f8fSZachary Turner         sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
5972c1f46dcSZachary Turner         m_saved_stdin.Reset();
5982c1f46dcSZachary Turner       }
599b9c1b51eSKate Stone       if (m_saved_stdout.IsValid()) {
600f8b22f8fSZachary Turner         sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
6012c1f46dcSZachary Turner         m_saved_stdout.Reset();
6022c1f46dcSZachary Turner       }
603b9c1b51eSKate Stone       if (m_saved_stderr.IsValid()) {
604f8b22f8fSZachary Turner         sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
6052c1f46dcSZachary Turner         m_saved_stderr.Reset();
6062c1f46dcSZachary Turner       }
6072c1f46dcSZachary Turner     }
6082c1f46dcSZachary Turner   }
6092c1f46dcSZachary Turner 
6102c1f46dcSZachary Turner   m_session_is_active = false;
6112c1f46dcSZachary Turner }
6122c1f46dcSZachary Turner 
613b07823f3SLawrence D'Anna bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp,
614b07823f3SLawrence D'Anna                                                const char *py_name,
615b07823f3SLawrence D'Anna                                                PythonObject &save_file,
616b9c1b51eSKate Stone                                                const char *mode) {
617b07823f3SLawrence D'Anna   if (!file_sp || !*file_sp) {
618b07823f3SLawrence D'Anna     save_file.Reset();
619b07823f3SLawrence D'Anna     return false;
620b07823f3SLawrence D'Anna   }
621b07823f3SLawrence D'Anna   File &file = *file_sp;
622b07823f3SLawrence D'Anna 
623a31baf08SGreg Clayton   // Flush the file before giving it to python to avoid interleaved output.
624a31baf08SGreg Clayton   file.Flush();
625a31baf08SGreg Clayton 
626a31baf08SGreg Clayton   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
627a31baf08SGreg Clayton 
6280f783599SLawrence D'Anna   auto new_file = PythonFile::FromFile(file, mode);
6290f783599SLawrence D'Anna   if (!new_file) {
6300f783599SLawrence D'Anna     llvm::consumeError(new_file.takeError());
6310f783599SLawrence D'Anna     return false;
6320f783599SLawrence D'Anna   }
6330f783599SLawrence D'Anna 
634b07823f3SLawrence D'Anna   save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
635a31baf08SGreg Clayton 
6360f783599SLawrence D'Anna   sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
637a31baf08SGreg Clayton   return true;
638a31baf08SGreg Clayton }
639a31baf08SGreg Clayton 
64063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
641b07823f3SLawrence D'Anna                                                FileSP in_sp, FileSP out_sp,
642b07823f3SLawrence D'Anna                                                FileSP err_sp) {
643b9c1b51eSKate Stone   // If we have already entered the session, without having officially 'left'
64405097246SAdrian Prantl   // it, then there is no need to 'enter' it again.
6452c1f46dcSZachary Turner   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
646b9c1b51eSKate Stone   if (m_session_is_active) {
64763e5fb76SJonas Devlieghere     LLDB_LOGF(
64863e5fb76SJonas Devlieghere         log,
64963dd5d25SJonas Devlieghere         "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
650b9c1b51eSKate Stone         ") session is already active, returning without doing anything",
651b9c1b51eSKate Stone         on_entry_flags);
6522c1f46dcSZachary Turner     return false;
6532c1f46dcSZachary Turner   }
6542c1f46dcSZachary Turner 
65563e5fb76SJonas Devlieghere   LLDB_LOGF(
65663e5fb76SJonas Devlieghere       log,
65763e5fb76SJonas Devlieghere       "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
658b9c1b51eSKate Stone       on_entry_flags);
6592c1f46dcSZachary Turner 
6602c1f46dcSZachary Turner   m_session_is_active = true;
6612c1f46dcSZachary Turner 
6622c1f46dcSZachary Turner   StreamString run_string;
6632c1f46dcSZachary Turner 
664b9c1b51eSKate Stone   if (on_entry_flags & Locker::InitGlobals) {
665b9c1b51eSKate Stone     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
6668d1fb843SJonas Devlieghere                       m_dictionary_name.c_str(), m_debugger.GetID());
667b9c1b51eSKate Stone     run_string.Printf(
668b9c1b51eSKate Stone         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
6698d1fb843SJonas Devlieghere         m_debugger.GetID());
6702c1f46dcSZachary Turner     run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
6712c1f46dcSZachary Turner     run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
6722c1f46dcSZachary Turner     run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
6732c1f46dcSZachary Turner     run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
6742c1f46dcSZachary Turner     run_string.PutCString("')");
675b9c1b51eSKate Stone   } else {
67605097246SAdrian Prantl     // If we aren't initing the globals, we should still always set the
67705097246SAdrian Prantl     // debugger (since that is always unique.)
678b9c1b51eSKate Stone     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
6798d1fb843SJonas Devlieghere                       m_dictionary_name.c_str(), m_debugger.GetID());
680b9c1b51eSKate Stone     run_string.Printf(
681b9c1b51eSKate Stone         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
6828d1fb843SJonas Devlieghere         m_debugger.GetID());
6832c1f46dcSZachary Turner     run_string.PutCString("')");
6842c1f46dcSZachary Turner   }
6852c1f46dcSZachary Turner 
6862c1f46dcSZachary Turner   PyRun_SimpleString(run_string.GetData());
6872c1f46dcSZachary Turner   run_string.Clear();
6882c1f46dcSZachary Turner 
6892c1f46dcSZachary Turner   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
690b9c1b51eSKate Stone   if (sys_module_dict.IsValid()) {
691b07823f3SLawrence D'Anna     lldb::FileSP top_in_sp;
692b07823f3SLawrence D'Anna     lldb::StreamFileSP top_out_sp, top_err_sp;
693b07823f3SLawrence D'Anna     if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
694b07823f3SLawrence D'Anna       m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
695b07823f3SLawrence D'Anna                                                  top_err_sp);
6962c1f46dcSZachary Turner 
697b9c1b51eSKate Stone     if (on_entry_flags & Locker::NoSTDIN) {
6982c1f46dcSZachary Turner       m_saved_stdin.Reset();
699b9c1b51eSKate Stone     } else {
700b07823f3SLawrence D'Anna       if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
701b07823f3SLawrence D'Anna         if (top_in_sp)
702b07823f3SLawrence D'Anna           SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
7032c1f46dcSZachary Turner       }
704a31baf08SGreg Clayton     }
705a31baf08SGreg Clayton 
706b07823f3SLawrence D'Anna     if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
707b07823f3SLawrence D'Anna       if (top_out_sp)
708b07823f3SLawrence D'Anna         SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w");
709a31baf08SGreg Clayton     }
710a31baf08SGreg Clayton 
711b07823f3SLawrence D'Anna     if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
712b07823f3SLawrence D'Anna       if (top_err_sp)
713b07823f3SLawrence D'Anna         SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w");
714a31baf08SGreg Clayton     }
7152c1f46dcSZachary Turner   }
7162c1f46dcSZachary Turner 
7172c1f46dcSZachary Turner   if (PyErr_Occurred())
7182c1f46dcSZachary Turner     PyErr_Clear();
7192c1f46dcSZachary Turner 
7202c1f46dcSZachary Turner   return true;
7212c1f46dcSZachary Turner }
7222c1f46dcSZachary Turner 
72304edd189SLawrence D'Anna PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
724f8b22f8fSZachary Turner   if (!m_main_module.IsValid())
72504edd189SLawrence D'Anna     m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__"));
7262c1f46dcSZachary Turner   return m_main_module;
7272c1f46dcSZachary Turner }
7282c1f46dcSZachary Turner 
72963dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
730f8b22f8fSZachary Turner   if (m_session_dict.IsValid())
731f8b22f8fSZachary Turner     return m_session_dict;
732f8b22f8fSZachary Turner 
7332c1f46dcSZachary Turner   PythonObject &main_module = GetMainModule();
734f8b22f8fSZachary Turner   if (!main_module.IsValid())
735f8b22f8fSZachary Turner     return m_session_dict;
736f8b22f8fSZachary Turner 
737b9c1b51eSKate Stone   PythonDictionary main_dict(PyRefType::Borrowed,
738b9c1b51eSKate Stone                              PyModule_GetDict(main_module.get()));
739f8b22f8fSZachary Turner   if (!main_dict.IsValid())
740f8b22f8fSZachary Turner     return m_session_dict;
741f8b22f8fSZachary Turner 
742722b6189SLawrence D'Anna   m_session_dict = unwrapIgnoringErrors(
743722b6189SLawrence D'Anna       As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
7442c1f46dcSZachary Turner   return m_session_dict;
7452c1f46dcSZachary Turner }
7462c1f46dcSZachary Turner 
74763dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
748f8b22f8fSZachary Turner   if (m_sys_module_dict.IsValid())
749f8b22f8fSZachary Turner     return m_sys_module_dict;
750722b6189SLawrence D'Anna   PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys"));
751722b6189SLawrence D'Anna   m_sys_module_dict = sys_module.GetDictionary();
7522c1f46dcSZachary Turner   return m_sys_module_dict;
7532c1f46dcSZachary Turner }
7542c1f46dcSZachary Turner 
755a69bbe02SLawrence D'Anna llvm::Expected<unsigned>
756a69bbe02SLawrence D'Anna ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
757a69bbe02SLawrence D'Anna     const llvm::StringRef &callable_name) {
758738af7a6SJim Ingham   if (callable_name.empty()) {
759738af7a6SJim Ingham     return llvm::createStringError(
760738af7a6SJim Ingham         llvm::inconvertibleErrorCode(),
761738af7a6SJim Ingham         "called with empty callable name.");
762738af7a6SJim Ingham   }
763738af7a6SJim Ingham   Locker py_lock(this, Locker::AcquireLock |
764738af7a6SJim Ingham                  Locker::InitSession |
765738af7a6SJim Ingham                  Locker::NoSTDIN);
766738af7a6SJim Ingham   auto dict = PythonModule::MainModule()
767738af7a6SJim Ingham       .ResolveName<PythonDictionary>(m_dictionary_name);
768a69bbe02SLawrence D'Anna   auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
769a69bbe02SLawrence D'Anna       callable_name, dict);
770738af7a6SJim Ingham   if (!pfunc.IsAllocated()) {
771738af7a6SJim Ingham     return llvm::createStringError(
772738af7a6SJim Ingham         llvm::inconvertibleErrorCode(),
773738af7a6SJim Ingham         "can't find callable: %s", callable_name.str().c_str());
774738af7a6SJim Ingham   }
775adbf64ccSLawrence D'Anna   llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
776adbf64ccSLawrence D'Anna   if (!arg_info)
777adbf64ccSLawrence D'Anna     return arg_info.takeError();
778adbf64ccSLawrence D'Anna   return arg_info.get().max_positional_args;
779738af7a6SJim Ingham }
780738af7a6SJim Ingham 
781b9c1b51eSKate Stone static std::string GenerateUniqueName(const char *base_name_wanted,
7822c1f46dcSZachary Turner                                       uint32_t &functions_counter,
783b9c1b51eSKate Stone                                       const void *name_token = nullptr) {
7842c1f46dcSZachary Turner   StreamString sstr;
7852c1f46dcSZachary Turner 
7862c1f46dcSZachary Turner   if (!base_name_wanted)
7872c1f46dcSZachary Turner     return std::string();
7882c1f46dcSZachary Turner 
7892c1f46dcSZachary Turner   if (!name_token)
7902c1f46dcSZachary Turner     sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
7912c1f46dcSZachary Turner   else
7922c1f46dcSZachary Turner     sstr.Printf("%s_%p", base_name_wanted, name_token);
7932c1f46dcSZachary Turner 
794adcd0268SBenjamin Kramer   return std::string(sstr.GetString());
7952c1f46dcSZachary Turner }
7962c1f46dcSZachary Turner 
79763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
798f8b22f8fSZachary Turner   if (m_run_one_line_function.IsValid())
799f8b22f8fSZachary Turner     return true;
800f8b22f8fSZachary Turner 
801b9c1b51eSKate Stone   PythonObject module(PyRefType::Borrowed,
802b9c1b51eSKate Stone                       PyImport_AddModule("lldb.embedded_interpreter"));
803f8b22f8fSZachary Turner   if (!module.IsValid())
804f8b22f8fSZachary Turner     return false;
805f8b22f8fSZachary Turner 
806b9c1b51eSKate Stone   PythonDictionary module_dict(PyRefType::Borrowed,
807b9c1b51eSKate Stone                                PyModule_GetDict(module.get()));
808f8b22f8fSZachary Turner   if (!module_dict.IsValid())
809f8b22f8fSZachary Turner     return false;
810f8b22f8fSZachary Turner 
811b9c1b51eSKate Stone   m_run_one_line_function =
812b9c1b51eSKate Stone       module_dict.GetItemForKey(PythonString("run_one_line"));
813b9c1b51eSKate Stone   m_run_one_line_str_global =
814b9c1b51eSKate Stone       module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
815f8b22f8fSZachary Turner   return m_run_one_line_function.IsValid();
8162c1f46dcSZachary Turner }
8172c1f46dcSZachary Turner 
81863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLine(
8194d51a902SRaphael Isemann     llvm::StringRef command, CommandReturnObject *result,
820b9c1b51eSKate Stone     const ExecuteScriptOptions &options) {
821d6c062bcSRaphael Isemann   std::string command_str = command.str();
822d6c062bcSRaphael Isemann 
8232c1f46dcSZachary Turner   if (!m_valid_session)
8242c1f46dcSZachary Turner     return false;
8252c1f46dcSZachary Turner 
8264d51a902SRaphael Isemann   if (!command.empty()) {
827b9c1b51eSKate Stone     // We want to call run_one_line, passing in the dictionary and the command
82805097246SAdrian Prantl     // string.  We cannot do this through PyRun_SimpleString here because the
82905097246SAdrian Prantl     // command string may contain escaped characters, and putting it inside
830b9c1b51eSKate Stone     // another string to pass to PyRun_SimpleString messes up the escaping.  So
83105097246SAdrian Prantl     // we use the following more complicated method to pass the command string
83205097246SAdrian Prantl     // directly down to Python.
833d79273c9SJonas Devlieghere     llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
83484228365SJonas Devlieghere         io_redirect_or_error = ScriptInterpreterIORedirect::Create(
83584228365SJonas Devlieghere             options.GetEnableIO(), m_debugger, result);
836d79273c9SJonas Devlieghere     if (!io_redirect_or_error) {
837d79273c9SJonas Devlieghere       if (result)
838d79273c9SJonas Devlieghere         result->AppendErrorWithFormatv(
839d79273c9SJonas Devlieghere             "failed to redirect I/O: {0}\n",
840d79273c9SJonas Devlieghere             llvm::fmt_consume(io_redirect_or_error.takeError()));
841d79273c9SJonas Devlieghere       else
842d79273c9SJonas Devlieghere         llvm::consumeError(io_redirect_or_error.takeError());
8432fce1137SLawrence D'Anna       return false;
8442fce1137SLawrence D'Anna     }
845d79273c9SJonas Devlieghere 
846d79273c9SJonas Devlieghere     ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
8472c1f46dcSZachary Turner 
84832064024SZachary Turner     bool success = false;
84932064024SZachary Turner     {
85005097246SAdrian Prantl       // WARNING!  It's imperative that this RAII scope be as tight as
85105097246SAdrian Prantl       // possible. In particular, the scope must end *before* we try to join
85205097246SAdrian Prantl       // the read thread.  The reason for this is that a pre-requisite for
85305097246SAdrian Prantl       // joining the read thread is that we close the write handle (to break
85405097246SAdrian Prantl       // the pipe and cause it to wake up and exit).  But acquiring the GIL as
85505097246SAdrian Prantl       // below will redirect Python's stdio to use this same handle.  If we
85605097246SAdrian Prantl       // close the handle while Python is still using it, bad things will
85705097246SAdrian Prantl       // happen.
858b9c1b51eSKate Stone       Locker locker(
859b9c1b51eSKate Stone           this,
86063dd5d25SJonas Devlieghere           Locker::AcquireLock | Locker::InitSession |
86163dd5d25SJonas Devlieghere               (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
8622c1f46dcSZachary Turner               ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
863d79273c9SJonas Devlieghere           Locker::FreeAcquiredLock | Locker::TearDownSession,
864d79273c9SJonas Devlieghere           io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
865d79273c9SJonas Devlieghere           io_redirect.GetErrorFile());
8662c1f46dcSZachary Turner 
8672c1f46dcSZachary Turner       // Find the correct script interpreter dictionary in the main module.
8682c1f46dcSZachary Turner       PythonDictionary &session_dict = GetSessionDictionary();
869b9c1b51eSKate Stone       if (session_dict.IsValid()) {
870b9c1b51eSKate Stone         if (GetEmbeddedInterpreterModuleObjects()) {
871b9c1b51eSKate Stone           if (PyCallable_Check(m_run_one_line_function.get())) {
872b9c1b51eSKate Stone             PythonObject pargs(
873b9c1b51eSKate Stone                 PyRefType::Owned,
874d6c062bcSRaphael Isemann                 Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
875b9c1b51eSKate Stone             if (pargs.IsValid()) {
876b9c1b51eSKate Stone               PythonObject return_value(
877b9c1b51eSKate Stone                   PyRefType::Owned,
878b9c1b51eSKate Stone                   PyObject_CallObject(m_run_one_line_function.get(),
879b9c1b51eSKate Stone                                       pargs.get()));
880f8b22f8fSZachary Turner               if (return_value.IsValid())
8812c1f46dcSZachary Turner                 success = true;
882b9c1b51eSKate Stone               else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
8832c1f46dcSZachary Turner                 PyErr_Print();
8842c1f46dcSZachary Turner                 PyErr_Clear();
8852c1f46dcSZachary Turner               }
8862c1f46dcSZachary Turner             }
8872c1f46dcSZachary Turner           }
8882c1f46dcSZachary Turner         }
8892c1f46dcSZachary Turner       }
8902c1f46dcSZachary Turner 
891d79273c9SJonas Devlieghere       io_redirect.Flush();
8922c1f46dcSZachary Turner     }
8932c1f46dcSZachary Turner 
8942c1f46dcSZachary Turner     if (success)
8952c1f46dcSZachary Turner       return true;
8962c1f46dcSZachary Turner 
8972c1f46dcSZachary Turner     // The one-liner failed.  Append the error message.
8984d51a902SRaphael Isemann     if (result) {
899b9c1b51eSKate Stone       result->AppendErrorWithFormat(
9004d51a902SRaphael Isemann           "python failed attempting to evaluate '%s'\n", command_str.c_str());
9014d51a902SRaphael Isemann     }
9022c1f46dcSZachary Turner     return false;
9032c1f46dcSZachary Turner   }
9042c1f46dcSZachary Turner 
9052c1f46dcSZachary Turner   if (result)
9062c1f46dcSZachary Turner     result->AppendError("empty command passed to python\n");
9072c1f46dcSZachary Turner   return false;
9082c1f46dcSZachary Turner }
9092c1f46dcSZachary Turner 
91063dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
9115c1c8443SJonas Devlieghere   LLDB_SCOPED_TIMER();
9122c1f46dcSZachary Turner 
9138d1fb843SJonas Devlieghere   Debugger &debugger = m_debugger;
9142c1f46dcSZachary Turner 
915b9c1b51eSKate Stone   // At the moment, the only time the debugger does not have an input file
91605097246SAdrian Prantl   // handle is when this is called directly from Python, in which case it is
91705097246SAdrian Prantl   // both dangerous and unnecessary (not to mention confusing) to try to embed
91805097246SAdrian Prantl   // a running interpreter loop inside the already running Python interpreter
91905097246SAdrian Prantl   // loop, so we won't do it.
9202c1f46dcSZachary Turner 
9217ca15ba7SLawrence D'Anna   if (!debugger.GetInputFile().IsValid())
9222c1f46dcSZachary Turner     return;
9232c1f46dcSZachary Turner 
9242c1f46dcSZachary Turner   IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
925b9c1b51eSKate Stone   if (io_handler_sp) {
9267ce2de2cSJonas Devlieghere     debugger.RunIOHandlerAsync(io_handler_sp);
9272c1f46dcSZachary Turner   }
9282c1f46dcSZachary Turner }
9292c1f46dcSZachary Turner 
93063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Interrupt() {
931*049ae930SJonas Devlieghere #if LLDB_USE_PYTHON_SET_INTERRUPT
932*049ae930SJonas Devlieghere   // If the interpreter isn't evaluating any Python at the moment then return
933*049ae930SJonas Devlieghere   // false to signal that this function didn't handle the interrupt and the
934*049ae930SJonas Devlieghere   // next component should try handling it.
935*049ae930SJonas Devlieghere   if (!IsExecutingPython())
936*049ae930SJonas Devlieghere     return false;
937*049ae930SJonas Devlieghere 
938*049ae930SJonas Devlieghere   // Tell Python that it should pretend to have received a SIGINT.
939*049ae930SJonas Devlieghere   PyErr_SetInterrupt();
940*049ae930SJonas Devlieghere   // PyErr_SetInterrupt has no way to return an error so we can only pretend the
941*049ae930SJonas Devlieghere   // signal got successfully handled and return true.
942*049ae930SJonas Devlieghere   // Python 3.10 introduces PyErr_SetInterruptEx that could return an error, but
943*049ae930SJonas Devlieghere   // the error handling is limited to checking the arguments which would be
944*049ae930SJonas Devlieghere   // just our (hardcoded) input signal code SIGINT, so that's not useful at all.
945*049ae930SJonas Devlieghere   return true;
946*049ae930SJonas Devlieghere #else
9472c1f46dcSZachary Turner   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
9482c1f46dcSZachary Turner 
949b9c1b51eSKate Stone   if (IsExecutingPython()) {
950b1cf558dSEnrico Granata     PyThreadState *state = PyThreadState_GET();
9512c1f46dcSZachary Turner     if (!state)
9522c1f46dcSZachary Turner       state = GetThreadState();
953b9c1b51eSKate Stone     if (state) {
9542c1f46dcSZachary Turner       long tid = state->thread_id;
95522c8efcdSZachary Turner       PyThreadState_Swap(state);
9562c1f46dcSZachary Turner       int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
95763e5fb76SJonas Devlieghere       LLDB_LOGF(log,
95863e5fb76SJonas Devlieghere                 "ScriptInterpreterPythonImpl::Interrupt() sending "
959b9c1b51eSKate Stone                 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
960b9c1b51eSKate Stone                 tid, num_threads);
9612c1f46dcSZachary Turner       return true;
9622c1f46dcSZachary Turner     }
9632c1f46dcSZachary Turner   }
96463e5fb76SJonas Devlieghere   LLDB_LOGF(log,
96563dd5d25SJonas Devlieghere             "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
966b9c1b51eSKate Stone             "can't interrupt");
9672c1f46dcSZachary Turner   return false;
968*049ae930SJonas Devlieghere #endif
9692c1f46dcSZachary Turner }
97004edd189SLawrence D'Anna 
97163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
9724d51a902SRaphael Isemann     llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
973b9c1b51eSKate Stone     void *ret_value, const ExecuteScriptOptions &options) {
9742c1f46dcSZachary Turner 
975f9517353SJonas Devlieghere   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
976f9517353SJonas Devlieghere       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
977f9517353SJonas Devlieghere           options.GetEnableIO(), m_debugger, /*result=*/nullptr);
978f9517353SJonas Devlieghere 
979f9517353SJonas Devlieghere   if (!io_redirect_or_error) {
980f9517353SJonas Devlieghere     llvm::consumeError(io_redirect_or_error.takeError());
981f9517353SJonas Devlieghere     return false;
982f9517353SJonas Devlieghere   }
983f9517353SJonas Devlieghere 
984f9517353SJonas Devlieghere   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
985f9517353SJonas Devlieghere 
98663dd5d25SJonas Devlieghere   Locker locker(this,
98763dd5d25SJonas Devlieghere                 Locker::AcquireLock | Locker::InitSession |
98863dd5d25SJonas Devlieghere                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
989b9c1b51eSKate Stone                     Locker::NoSTDIN,
990f9517353SJonas Devlieghere                 Locker::FreeAcquiredLock | Locker::TearDownSession,
991f9517353SJonas Devlieghere                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
992f9517353SJonas Devlieghere                 io_redirect.GetErrorFile());
9932c1f46dcSZachary Turner 
99404edd189SLawrence D'Anna   PythonModule &main_module = GetMainModule();
99504edd189SLawrence D'Anna   PythonDictionary globals = main_module.GetDictionary();
9962c1f46dcSZachary Turner 
9972c1f46dcSZachary Turner   PythonDictionary locals = GetSessionDictionary();
99804edd189SLawrence D'Anna   if (!locals.IsValid())
999722b6189SLawrence D'Anna     locals = unwrapIgnoringErrors(
1000722b6189SLawrence D'Anna         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1001f8b22f8fSZachary Turner   if (!locals.IsValid())
10022c1f46dcSZachary Turner     locals = globals;
10032c1f46dcSZachary Turner 
100404edd189SLawrence D'Anna   Expected<PythonObject> maybe_py_return =
100504edd189SLawrence D'Anna       runStringOneLine(in_string, globals, locals);
10062c1f46dcSZachary Turner 
100704edd189SLawrence D'Anna   if (!maybe_py_return) {
100804edd189SLawrence D'Anna     llvm::handleAllErrors(
100904edd189SLawrence D'Anna         maybe_py_return.takeError(),
101004edd189SLawrence D'Anna         [&](PythonException &E) {
101104edd189SLawrence D'Anna           E.Restore();
101204edd189SLawrence D'Anna           if (options.GetMaskoutErrors()) {
101304edd189SLawrence D'Anna             if (E.Matches(PyExc_SyntaxError)) {
101404edd189SLawrence D'Anna               PyErr_Print();
10152c1f46dcSZachary Turner             }
101604edd189SLawrence D'Anna             PyErr_Clear();
101704edd189SLawrence D'Anna           }
101804edd189SLawrence D'Anna         },
101904edd189SLawrence D'Anna         [](const llvm::ErrorInfoBase &E) {});
102004edd189SLawrence D'Anna     return false;
10212c1f46dcSZachary Turner   }
10222c1f46dcSZachary Turner 
102304edd189SLawrence D'Anna   PythonObject py_return = std::move(maybe_py_return.get());
102404edd189SLawrence D'Anna   assert(py_return.IsValid());
102504edd189SLawrence D'Anna 
1026b9c1b51eSKate Stone   switch (return_type) {
10272c1f46dcSZachary Turner   case eScriptReturnTypeCharPtr: // "char *"
10282c1f46dcSZachary Turner   {
10292c1f46dcSZachary Turner     const char format[3] = "s#";
103004edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
10312c1f46dcSZachary Turner   }
1032b9c1b51eSKate Stone   case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
1033b9c1b51eSKate Stone                                        // Py_None
10342c1f46dcSZachary Turner   {
10352c1f46dcSZachary Turner     const char format[3] = "z";
103604edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
10372c1f46dcSZachary Turner   }
1038b9c1b51eSKate Stone   case eScriptReturnTypeBool: {
10392c1f46dcSZachary Turner     const char format[2] = "b";
104004edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
10412c1f46dcSZachary Turner   }
1042b9c1b51eSKate Stone   case eScriptReturnTypeShortInt: {
10432c1f46dcSZachary Turner     const char format[2] = "h";
104404edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (short *)ret_value);
10452c1f46dcSZachary Turner   }
1046b9c1b51eSKate Stone   case eScriptReturnTypeShortIntUnsigned: {
10472c1f46dcSZachary Turner     const char format[2] = "H";
104804edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
10492c1f46dcSZachary Turner   }
1050b9c1b51eSKate Stone   case eScriptReturnTypeInt: {
10512c1f46dcSZachary Turner     const char format[2] = "i";
105204edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (int *)ret_value);
10532c1f46dcSZachary Turner   }
1054b9c1b51eSKate Stone   case eScriptReturnTypeIntUnsigned: {
10552c1f46dcSZachary Turner     const char format[2] = "I";
105604edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
10572c1f46dcSZachary Turner   }
1058b9c1b51eSKate Stone   case eScriptReturnTypeLongInt: {
10592c1f46dcSZachary Turner     const char format[2] = "l";
106004edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (long *)ret_value);
10612c1f46dcSZachary Turner   }
1062b9c1b51eSKate Stone   case eScriptReturnTypeLongIntUnsigned: {
10632c1f46dcSZachary Turner     const char format[2] = "k";
106404edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
10652c1f46dcSZachary Turner   }
1066b9c1b51eSKate Stone   case eScriptReturnTypeLongLong: {
10672c1f46dcSZachary Turner     const char format[2] = "L";
106804edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
10692c1f46dcSZachary Turner   }
1070b9c1b51eSKate Stone   case eScriptReturnTypeLongLongUnsigned: {
10712c1f46dcSZachary Turner     const char format[2] = "K";
107204edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format,
107304edd189SLawrence D'Anna                        (unsigned long long *)ret_value);
10742c1f46dcSZachary Turner   }
1075b9c1b51eSKate Stone   case eScriptReturnTypeFloat: {
10762c1f46dcSZachary Turner     const char format[2] = "f";
107704edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (float *)ret_value);
10782c1f46dcSZachary Turner   }
1079b9c1b51eSKate Stone   case eScriptReturnTypeDouble: {
10802c1f46dcSZachary Turner     const char format[2] = "d";
108104edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (double *)ret_value);
10822c1f46dcSZachary Turner   }
1083b9c1b51eSKate Stone   case eScriptReturnTypeChar: {
10842c1f46dcSZachary Turner     const char format[2] = "c";
108504edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (char *)ret_value);
10862c1f46dcSZachary Turner   }
1087b9c1b51eSKate Stone   case eScriptReturnTypeOpaqueObject: {
108804edd189SLawrence D'Anna     *((PyObject **)ret_value) = py_return.release();
108904edd189SLawrence D'Anna     return true;
10902c1f46dcSZachary Turner   }
10912c1f46dcSZachary Turner   }
10921dfb1a85SPavel Labath   llvm_unreachable("Fully covered switch!");
10932c1f46dcSZachary Turner }
10942c1f46dcSZachary Turner 
109563dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1096b9c1b51eSKate Stone     const char *in_string, const ExecuteScriptOptions &options) {
109704edd189SLawrence D'Anna 
109804edd189SLawrence D'Anna   if (in_string == nullptr)
109904edd189SLawrence D'Anna     return Status();
11002c1f46dcSZachary Turner 
1101f9517353SJonas Devlieghere   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1102f9517353SJonas Devlieghere       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1103f9517353SJonas Devlieghere           options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1104f9517353SJonas Devlieghere 
1105f9517353SJonas Devlieghere   if (!io_redirect_or_error)
1106f9517353SJonas Devlieghere     return Status(io_redirect_or_error.takeError());
1107f9517353SJonas Devlieghere 
1108f9517353SJonas Devlieghere   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1109f9517353SJonas Devlieghere 
111063dd5d25SJonas Devlieghere   Locker locker(this,
111163dd5d25SJonas Devlieghere                 Locker::AcquireLock | Locker::InitSession |
111263dd5d25SJonas Devlieghere                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1113b9c1b51eSKate Stone                     Locker::NoSTDIN,
1114f9517353SJonas Devlieghere                 Locker::FreeAcquiredLock | Locker::TearDownSession,
1115f9517353SJonas Devlieghere                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1116f9517353SJonas Devlieghere                 io_redirect.GetErrorFile());
11172c1f46dcSZachary Turner 
111804edd189SLawrence D'Anna   PythonModule &main_module = GetMainModule();
111904edd189SLawrence D'Anna   PythonDictionary globals = main_module.GetDictionary();
11202c1f46dcSZachary Turner 
11212c1f46dcSZachary Turner   PythonDictionary locals = GetSessionDictionary();
1122f8b22f8fSZachary Turner   if (!locals.IsValid())
1123722b6189SLawrence D'Anna     locals = unwrapIgnoringErrors(
1124722b6189SLawrence D'Anna         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1125f8b22f8fSZachary Turner   if (!locals.IsValid())
11262c1f46dcSZachary Turner     locals = globals;
11272c1f46dcSZachary Turner 
112804edd189SLawrence D'Anna   Expected<PythonObject> return_value =
112904edd189SLawrence D'Anna       runStringMultiLine(in_string, globals, locals);
11302c1f46dcSZachary Turner 
113104edd189SLawrence D'Anna   if (!return_value) {
113204edd189SLawrence D'Anna     llvm::Error error =
113304edd189SLawrence D'Anna         llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
113404edd189SLawrence D'Anna           llvm::Error error = llvm::createStringError(
113504edd189SLawrence D'Anna               llvm::inconvertibleErrorCode(), E.ReadBacktrace());
113604edd189SLawrence D'Anna           if (!options.GetMaskoutErrors())
113704edd189SLawrence D'Anna             E.Restore();
11382c1f46dcSZachary Turner           return error;
113904edd189SLawrence D'Anna         });
114004edd189SLawrence D'Anna     return Status(std::move(error));
114104edd189SLawrence D'Anna   }
114204edd189SLawrence D'Anna 
114304edd189SLawrence D'Anna   return Status();
11442c1f46dcSZachary Turner }
11452c1f46dcSZachary Turner 
114663dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1147cfb96d84SJim Ingham     std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1148b9c1b51eSKate Stone     CommandReturnObject &result) {
11492c1f46dcSZachary Turner   m_active_io_handler = eIOHandlerBreakpoint;
11508d1fb843SJonas Devlieghere   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1151a6faf851SJonas Devlieghere       "    ", *this, &bp_options_vec);
11522c1f46dcSZachary Turner }
11532c1f46dcSZachary Turner 
115463dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1155b9c1b51eSKate Stone     WatchpointOptions *wp_options, CommandReturnObject &result) {
11562c1f46dcSZachary Turner   m_active_io_handler = eIOHandlerWatchpoint;
11578d1fb843SJonas Devlieghere   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1158a6faf851SJonas Devlieghere       "    ", *this, wp_options);
11592c1f46dcSZachary Turner }
11602c1f46dcSZachary Turner 
1161738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1162cfb96d84SJim Ingham     BreakpointOptions &bp_options, const char *function_name,
1163738af7a6SJim Ingham     StructuredData::ObjectSP extra_args_sp) {
1164738af7a6SJim Ingham   Status error;
11652c1f46dcSZachary Turner   // For now just cons up a oneliner that calls the provided function.
11662c1f46dcSZachary Turner   std::string oneliner("return ");
11672c1f46dcSZachary Turner   oneliner += function_name;
1168738af7a6SJim Ingham 
1169a69bbe02SLawrence D'Anna   llvm::Expected<unsigned> maybe_args =
1170a69bbe02SLawrence D'Anna       GetMaxPositionalArgumentsForCallable(function_name);
1171738af7a6SJim Ingham   if (!maybe_args) {
1172a69bbe02SLawrence D'Anna     error.SetErrorStringWithFormat(
1173a69bbe02SLawrence D'Anna         "could not get num args: %s",
1174738af7a6SJim Ingham         llvm::toString(maybe_args.takeError()).c_str());
1175738af7a6SJim Ingham     return error;
1176738af7a6SJim Ingham   }
1177a69bbe02SLawrence D'Anna   size_t max_args = *maybe_args;
1178738af7a6SJim Ingham 
1179738af7a6SJim Ingham   bool uses_extra_args = false;
1180a69bbe02SLawrence D'Anna   if (max_args >= 4) {
1181738af7a6SJim Ingham     uses_extra_args = true;
1182738af7a6SJim Ingham     oneliner += "(frame, bp_loc, extra_args, internal_dict)";
1183a69bbe02SLawrence D'Anna   } else if (max_args >= 3) {
1184738af7a6SJim Ingham     if (extra_args_sp) {
1185738af7a6SJim Ingham       error.SetErrorString("cannot pass extra_args to a three argument callback"
1186738af7a6SJim Ingham                           );
1187738af7a6SJim Ingham       return error;
1188738af7a6SJim Ingham     }
1189738af7a6SJim Ingham     uses_extra_args = false;
11902c1f46dcSZachary Turner     oneliner += "(frame, bp_loc, internal_dict)";
1191738af7a6SJim Ingham   } else {
1192738af7a6SJim Ingham     error.SetErrorStringWithFormat("expected 3 or 4 argument "
1193a69bbe02SLawrence D'Anna                                    "function, %s can only take %zu",
1194a69bbe02SLawrence D'Anna                                    function_name, max_args);
1195738af7a6SJim Ingham     return error;
1196738af7a6SJim Ingham   }
1197738af7a6SJim Ingham 
1198738af7a6SJim Ingham   SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp,
1199738af7a6SJim Ingham                                uses_extra_args);
1200738af7a6SJim Ingham   return error;
12012c1f46dcSZachary Turner }
12022c1f46dcSZachary Turner 
120363dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1204cfb96d84SJim Ingham     BreakpointOptions &bp_options,
1205f7e07256SJim Ingham     std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
120697206d57SZachary Turner   Status error;
1207f7e07256SJim Ingham   error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1208738af7a6SJim Ingham                                                 cmd_data_up->script_source,
1209738af7a6SJim Ingham                                                 false);
1210f7e07256SJim Ingham   if (error.Fail()) {
1211f7e07256SJim Ingham     return error;
1212f7e07256SJim Ingham   }
1213f7e07256SJim Ingham   auto baton_sp =
1214f7e07256SJim Ingham       std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1215cfb96d84SJim Ingham   bp_options.SetCallback(
121663dd5d25SJonas Devlieghere       ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1217f7e07256SJim Ingham   return error;
1218f7e07256SJim Ingham }
1219f7e07256SJim Ingham 
122063dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1221cfb96d84SJim Ingham     BreakpointOptions &bp_options, const char *command_body_text) {
1222738af7a6SJim Ingham   return SetBreakpointCommandCallback(bp_options, command_body_text, {},false);
1223738af7a6SJim Ingham }
12242c1f46dcSZachary Turner 
1225738af7a6SJim Ingham // Set a Python one-liner as the callback for the breakpoint.
1226738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1227cfb96d84SJim Ingham     BreakpointOptions &bp_options, const char *command_body_text,
1228cfb96d84SJim Ingham     StructuredData::ObjectSP extra_args_sp, bool uses_extra_args) {
1229738af7a6SJim Ingham   auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1230b9c1b51eSKate Stone   // Split the command_body_text into lines, and pass that to
123105097246SAdrian Prantl   // GenerateBreakpointCommandCallbackData.  That will wrap the body in an
123205097246SAdrian Prantl   // auto-generated function, and return the function name in script_source.
123305097246SAdrian Prantl   // That is what the callback will actually invoke.
12342c1f46dcSZachary Turner 
1235d5b44036SJonas Devlieghere   data_up->user_source.SplitIntoLines(command_body_text);
1236d5b44036SJonas Devlieghere   Status error = GenerateBreakpointCommandCallbackData(data_up->user_source,
1237738af7a6SJim Ingham                                                        data_up->script_source,
1238738af7a6SJim Ingham                                                        uses_extra_args);
1239b9c1b51eSKate Stone   if (error.Success()) {
12404e4fbe82SZachary Turner     auto baton_sp =
1241d5b44036SJonas Devlieghere         std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1242cfb96d84SJim Ingham     bp_options.SetCallback(
124363dd5d25SJonas Devlieghere         ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
12442c1f46dcSZachary Turner     return error;
124593571c3cSJonas Devlieghere   }
12462c1f46dcSZachary Turner   return error;
12472c1f46dcSZachary Turner }
12482c1f46dcSZachary Turner 
12492c1f46dcSZachary Turner // Set a Python one-liner as the callback for the watchpoint.
125063dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1251b9c1b51eSKate Stone     WatchpointOptions *wp_options, const char *oneliner) {
1252a8f3ae7cSJonas Devlieghere   auto data_up = std::make_unique<WatchpointOptions::CommandData>();
12532c1f46dcSZachary Turner 
12542c1f46dcSZachary Turner   // It's necessary to set both user_source and script_source to the oneliner.
1255b9c1b51eSKate Stone   // The former is used to generate callback description (as in watchpoint
125605097246SAdrian Prantl   // command list) while the latter is used for Python to interpret during the
125705097246SAdrian Prantl   // actual callback.
12582c1f46dcSZachary Turner 
1259d5b44036SJonas Devlieghere   data_up->user_source.AppendString(oneliner);
1260d5b44036SJonas Devlieghere   data_up->script_source.assign(oneliner);
12612c1f46dcSZachary Turner 
1262d5b44036SJonas Devlieghere   if (GenerateWatchpointCommandCallbackData(data_up->user_source,
1263d5b44036SJonas Devlieghere                                             data_up->script_source)) {
12644e4fbe82SZachary Turner     auto baton_sp =
1265d5b44036SJonas Devlieghere         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
126663dd5d25SJonas Devlieghere     wp_options->SetCallback(
126763dd5d25SJonas Devlieghere         ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
12682c1f46dcSZachary Turner   }
12692c1f46dcSZachary Turner 
12702c1f46dcSZachary Turner   return;
12712c1f46dcSZachary Turner }
12722c1f46dcSZachary Turner 
127363dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1274b9c1b51eSKate Stone     StringList &function_def) {
12752c1f46dcSZachary Turner   // Convert StringList to one long, newline delimited, const char *.
12762c1f46dcSZachary Turner   std::string function_def_string(function_def.CopyList());
12772c1f46dcSZachary Turner 
127897206d57SZachary Turner   Status error = ExecuteMultipleLines(
1279b9c1b51eSKate Stone       function_def_string.c_str(),
1280fd2433e1SJonas Devlieghere       ExecuteScriptOptions().SetEnableIO(false));
12812c1f46dcSZachary Turner   return error;
12822c1f46dcSZachary Turner }
12832c1f46dcSZachary Turner 
128463dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature,
1285b9c1b51eSKate Stone                                                      const StringList &input) {
128697206d57SZachary Turner   Status error;
12872c1f46dcSZachary Turner   int num_lines = input.GetSize();
1288b9c1b51eSKate Stone   if (num_lines == 0) {
12892c1f46dcSZachary Turner     error.SetErrorString("No input data.");
12902c1f46dcSZachary Turner     return error;
12912c1f46dcSZachary Turner   }
12922c1f46dcSZachary Turner 
1293b9c1b51eSKate Stone   if (!signature || *signature == 0) {
12942c1f46dcSZachary Turner     error.SetErrorString("No output function name.");
12952c1f46dcSZachary Turner     return error;
12962c1f46dcSZachary Turner   }
12972c1f46dcSZachary Turner 
12982c1f46dcSZachary Turner   StreamString sstr;
12992c1f46dcSZachary Turner   StringList auto_generated_function;
13002c1f46dcSZachary Turner   auto_generated_function.AppendString(signature);
1301b9c1b51eSKate Stone   auto_generated_function.AppendString(
1302b9c1b51eSKate Stone       "     global_dict = globals()"); // Grab the global dictionary
1303b9c1b51eSKate Stone   auto_generated_function.AppendString(
1304b9c1b51eSKate Stone       "     new_keys = internal_dict.keys()"); // Make a list of keys in the
1305b9c1b51eSKate Stone                                                // session dict
1306b9c1b51eSKate Stone   auto_generated_function.AppendString(
1307b9c1b51eSKate Stone       "     old_keys = global_dict.keys()"); // Save list of keys in global dict
1308b9c1b51eSKate Stone   auto_generated_function.AppendString(
1309b9c1b51eSKate Stone       "     global_dict.update (internal_dict)"); // Add the session dictionary
1310b9c1b51eSKate Stone                                                   // to the
13112c1f46dcSZachary Turner   // global dictionary.
13122c1f46dcSZachary Turner 
13132c1f46dcSZachary Turner   // Wrap everything up inside the function, increasing the indentation.
13142c1f46dcSZachary Turner 
13152c1f46dcSZachary Turner   auto_generated_function.AppendString("     if True:");
1316b9c1b51eSKate Stone   for (int i = 0; i < num_lines; ++i) {
13172c1f46dcSZachary Turner     sstr.Clear();
13182c1f46dcSZachary Turner     sstr.Printf("       %s", input.GetStringAtIndex(i));
13192c1f46dcSZachary Turner     auto_generated_function.AppendString(sstr.GetData());
13202c1f46dcSZachary Turner   }
1321b9c1b51eSKate Stone   auto_generated_function.AppendString(
1322b9c1b51eSKate Stone       "     for key in new_keys:"); // Iterate over all the keys from session
1323b9c1b51eSKate Stone                                     // dict
1324b9c1b51eSKate Stone   auto_generated_function.AppendString(
1325b9c1b51eSKate Stone       "         internal_dict[key] = global_dict[key]"); // Update session dict
1326b9c1b51eSKate Stone                                                          // values
1327b9c1b51eSKate Stone   auto_generated_function.AppendString(
1328b9c1b51eSKate Stone       "         if key not in old_keys:"); // If key was not originally in
1329b9c1b51eSKate Stone                                            // global dict
1330b9c1b51eSKate Stone   auto_generated_function.AppendString(
1331b9c1b51eSKate Stone       "             del global_dict[key]"); //  ...then remove key/value from
1332b9c1b51eSKate Stone                                             //  global dict
13332c1f46dcSZachary Turner 
13342c1f46dcSZachary Turner   // Verify that the results are valid Python.
13352c1f46dcSZachary Turner 
13362c1f46dcSZachary Turner   error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
13372c1f46dcSZachary Turner 
13382c1f46dcSZachary Turner   return error;
13392c1f46dcSZachary Turner }
13402c1f46dcSZachary Turner 
134163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1342b9c1b51eSKate Stone     StringList &user_input, std::string &output, const void *name_token) {
13432c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
13442c1f46dcSZachary Turner   user_input.RemoveBlankLines();
13452c1f46dcSZachary Turner   StreamString sstr;
13462c1f46dcSZachary Turner 
13472c1f46dcSZachary Turner   // Check to see if we have any data; if not, just return.
13482c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
13492c1f46dcSZachary Turner     return false;
13502c1f46dcSZachary Turner 
1351b9c1b51eSKate Stone   // Take what the user wrote, wrap it all up inside one big auto-generated
135205097246SAdrian Prantl   // Python function, passing in the ValueObject as parameter to the function.
13532c1f46dcSZachary Turner 
1354b9c1b51eSKate Stone   std::string auto_generated_function_name(
1355b9c1b51eSKate Stone       GenerateUniqueName("lldb_autogen_python_type_print_func",
1356b9c1b51eSKate Stone                          num_created_functions, name_token));
1357b9c1b51eSKate Stone   sstr.Printf("def %s (valobj, internal_dict):",
1358b9c1b51eSKate Stone               auto_generated_function_name.c_str());
13592c1f46dcSZachary Turner 
13602c1f46dcSZachary Turner   if (!GenerateFunction(sstr.GetData(), user_input).Success())
13612c1f46dcSZachary Turner     return false;
13622c1f46dcSZachary Turner 
13632c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
13642c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
13652c1f46dcSZachary Turner   return true;
13662c1f46dcSZachary Turner }
13672c1f46dcSZachary Turner 
136863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1369b9c1b51eSKate Stone     StringList &user_input, std::string &output) {
13702c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
13712c1f46dcSZachary Turner   user_input.RemoveBlankLines();
13722c1f46dcSZachary Turner   StreamString sstr;
13732c1f46dcSZachary Turner 
13742c1f46dcSZachary Turner   // Check to see if we have any data; if not, just return.
13752c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
13762c1f46dcSZachary Turner     return false;
13772c1f46dcSZachary Turner 
1378b9c1b51eSKate Stone   std::string auto_generated_function_name(GenerateUniqueName(
1379b9c1b51eSKate Stone       "lldb_autogen_python_cmd_alias_func", num_created_functions));
13802c1f46dcSZachary Turner 
1381b9c1b51eSKate Stone   sstr.Printf("def %s (debugger, args, result, internal_dict):",
1382b9c1b51eSKate Stone               auto_generated_function_name.c_str());
13832c1f46dcSZachary Turner 
13842c1f46dcSZachary Turner   if (!GenerateFunction(sstr.GetData(), user_input).Success())
13852c1f46dcSZachary Turner     return false;
13862c1f46dcSZachary Turner 
13872c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
13882c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
13892c1f46dcSZachary Turner   return true;
13902c1f46dcSZachary Turner }
13912c1f46dcSZachary Turner 
139263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
139363dd5d25SJonas Devlieghere     StringList &user_input, std::string &output, const void *name_token) {
13942c1f46dcSZachary Turner   static uint32_t num_created_classes = 0;
13952c1f46dcSZachary Turner   user_input.RemoveBlankLines();
13962c1f46dcSZachary Turner   int num_lines = user_input.GetSize();
13972c1f46dcSZachary Turner   StreamString sstr;
13982c1f46dcSZachary Turner 
13992c1f46dcSZachary Turner   // Check to see if we have any data; if not, just return.
14002c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
14012c1f46dcSZachary Turner     return false;
14022c1f46dcSZachary Turner 
14032c1f46dcSZachary Turner   // Wrap all user input into a Python class
14042c1f46dcSZachary Turner 
1405b9c1b51eSKate Stone   std::string auto_generated_class_name(GenerateUniqueName(
1406b9c1b51eSKate Stone       "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
14072c1f46dcSZachary Turner 
14082c1f46dcSZachary Turner   StringList auto_generated_class;
14092c1f46dcSZachary Turner 
14102c1f46dcSZachary Turner   // Create the function name & definition string.
14112c1f46dcSZachary Turner 
14122c1f46dcSZachary Turner   sstr.Printf("class %s:", auto_generated_class_name.c_str());
1413c156427dSZachary Turner   auto_generated_class.AppendString(sstr.GetString());
14142c1f46dcSZachary Turner 
141505097246SAdrian Prantl   // Wrap everything up inside the class, increasing the indentation. we don't
141605097246SAdrian Prantl   // need to play any fancy indentation tricks here because there is no
14172c1f46dcSZachary Turner   // surrounding code whose indentation we need to honor
1418b9c1b51eSKate Stone   for (int i = 0; i < num_lines; ++i) {
14192c1f46dcSZachary Turner     sstr.Clear();
14202c1f46dcSZachary Turner     sstr.Printf("     %s", user_input.GetStringAtIndex(i));
1421c156427dSZachary Turner     auto_generated_class.AppendString(sstr.GetString());
14222c1f46dcSZachary Turner   }
14232c1f46dcSZachary Turner 
142405097246SAdrian Prantl   // Verify that the results are valid Python. (even though the method is
142505097246SAdrian Prantl   // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
14262c1f46dcSZachary Turner   // (TODO: rename that method to ExportDefinitionToInterpreter)
14272c1f46dcSZachary Turner   if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
14282c1f46dcSZachary Turner     return false;
14292c1f46dcSZachary Turner 
14302c1f46dcSZachary Turner   // Store the name of the auto-generated class
14312c1f46dcSZachary Turner 
14322c1f46dcSZachary Turner   output.assign(auto_generated_class_name);
14332c1f46dcSZachary Turner   return true;
14342c1f46dcSZachary Turner }
14352c1f46dcSZachary Turner 
143663dd5d25SJonas Devlieghere StructuredData::GenericSP
143763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
143841ae8e74SKuba Mracek   if (class_name == nullptr || class_name[0] == '\0')
143941ae8e74SKuba Mracek     return StructuredData::GenericSP();
144041ae8e74SKuba Mracek 
144141ae8e74SKuba Mracek   void *ret_val;
144241ae8e74SKuba Mracek 
144341ae8e74SKuba Mracek   {
144441ae8e74SKuba Mracek     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
144541ae8e74SKuba Mracek                    Locker::FreeLock);
144605495c5dSJonas Devlieghere     ret_val = LLDBSWIGPython_CreateFrameRecognizer(class_name,
144705495c5dSJonas Devlieghere                                                    m_dictionary_name.c_str());
144841ae8e74SKuba Mracek   }
144941ae8e74SKuba Mracek 
145041ae8e74SKuba Mracek   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
145141ae8e74SKuba Mracek }
145241ae8e74SKuba Mracek 
145363dd5d25SJonas Devlieghere lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
145441ae8e74SKuba Mracek     const StructuredData::ObjectSP &os_plugin_object_sp,
145541ae8e74SKuba Mracek     lldb::StackFrameSP frame_sp) {
145641ae8e74SKuba Mracek   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
145741ae8e74SKuba Mracek 
145863dd5d25SJonas Devlieghere   if (!os_plugin_object_sp)
145963dd5d25SJonas Devlieghere     return ValueObjectListSP();
146041ae8e74SKuba Mracek 
146141ae8e74SKuba Mracek   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
146263dd5d25SJonas Devlieghere   if (!generic)
146363dd5d25SJonas Devlieghere     return nullptr;
146441ae8e74SKuba Mracek 
146541ae8e74SKuba Mracek   PythonObject implementor(PyRefType::Borrowed,
146641ae8e74SKuba Mracek                            (PyObject *)generic->GetValue());
146741ae8e74SKuba Mracek 
146863dd5d25SJonas Devlieghere   if (!implementor.IsAllocated())
146963dd5d25SJonas Devlieghere     return ValueObjectListSP();
147041ae8e74SKuba Mracek 
14719a14adeaSPavel Labath   PythonObject py_return(
14729a14adeaSPavel Labath       PyRefType::Owned,
14739a14adeaSPavel Labath       LLDBSwigPython_GetRecognizedArguments(implementor.get(), frame_sp));
147441ae8e74SKuba Mracek 
147541ae8e74SKuba Mracek   // if it fails, print the error but otherwise go on
147641ae8e74SKuba Mracek   if (PyErr_Occurred()) {
147741ae8e74SKuba Mracek     PyErr_Print();
147841ae8e74SKuba Mracek     PyErr_Clear();
147941ae8e74SKuba Mracek   }
148041ae8e74SKuba Mracek   if (py_return.get()) {
148141ae8e74SKuba Mracek     PythonList result_list(PyRefType::Borrowed, py_return.get());
148241ae8e74SKuba Mracek     ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
14838f81aed1SDavid Bolvansky     for (size_t i = 0; i < result_list.GetSize(); i++) {
148441ae8e74SKuba Mracek       PyObject *item = result_list.GetItemAtIndex(i).get();
148541ae8e74SKuba Mracek       lldb::SBValue *sb_value_ptr =
148605495c5dSJonas Devlieghere           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
148705495c5dSJonas Devlieghere       auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
148863dd5d25SJonas Devlieghere       if (valobj_sp)
148963dd5d25SJonas Devlieghere         result->Append(valobj_sp);
149041ae8e74SKuba Mracek     }
149141ae8e74SKuba Mracek     return result;
149241ae8e74SKuba Mracek   }
149341ae8e74SKuba Mracek   return ValueObjectListSP();
149441ae8e74SKuba Mracek }
149541ae8e74SKuba Mracek 
149663dd5d25SJonas Devlieghere StructuredData::GenericSP
149763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject(
1498b9c1b51eSKate Stone     const char *class_name, lldb::ProcessSP process_sp) {
14992c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
15002c1f46dcSZachary Turner     return StructuredData::GenericSP();
15012c1f46dcSZachary Turner 
15022c1f46dcSZachary Turner   if (!process_sp)
15032c1f46dcSZachary Turner     return StructuredData::GenericSP();
15042c1f46dcSZachary Turner 
15052c1f46dcSZachary Turner   void *ret_val;
15062c1f46dcSZachary Turner 
15072c1f46dcSZachary Turner   {
1508b9c1b51eSKate Stone     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
15092c1f46dcSZachary Turner                    Locker::FreeLock);
151005495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonCreateOSPlugin(
151105495c5dSJonas Devlieghere         class_name, m_dictionary_name.c_str(), process_sp);
15122c1f46dcSZachary Turner   }
15132c1f46dcSZachary Turner 
15142c1f46dcSZachary Turner   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
15152c1f46dcSZachary Turner }
15162c1f46dcSZachary Turner 
151763dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo(
1518b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp) {
1519b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
15202c1f46dcSZachary Turner 
15212c1f46dcSZachary Turner   static char callee_name[] = "get_register_info";
15222c1f46dcSZachary Turner 
15232c1f46dcSZachary Turner   if (!os_plugin_object_sp)
15242c1f46dcSZachary Turner     return StructuredData::DictionarySP();
15252c1f46dcSZachary Turner 
15262c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
15272c1f46dcSZachary Turner   if (!generic)
15282c1f46dcSZachary Turner     return nullptr;
15292c1f46dcSZachary Turner 
1530b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1531b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
15322c1f46dcSZachary Turner 
1533f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
15342c1f46dcSZachary Turner     return StructuredData::DictionarySP();
15352c1f46dcSZachary Turner 
1536b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1537b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
15382c1f46dcSZachary Turner 
15392c1f46dcSZachary Turner   if (PyErr_Occurred())
15402c1f46dcSZachary Turner     PyErr_Clear();
15412c1f46dcSZachary Turner 
1542f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
15432c1f46dcSZachary Turner     return StructuredData::DictionarySP();
15442c1f46dcSZachary Turner 
1545b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
15462c1f46dcSZachary Turner     if (PyErr_Occurred())
15472c1f46dcSZachary Turner       PyErr_Clear();
15482c1f46dcSZachary Turner 
15492c1f46dcSZachary Turner     return StructuredData::DictionarySP();
15502c1f46dcSZachary Turner   }
15512c1f46dcSZachary Turner 
15522c1f46dcSZachary Turner   if (PyErr_Occurred())
15532c1f46dcSZachary Turner     PyErr_Clear();
15542c1f46dcSZachary Turner 
15552c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1556b9c1b51eSKate Stone   PythonObject py_return(
1557b9c1b51eSKate Stone       PyRefType::Owned,
1558b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
15592c1f46dcSZachary Turner 
15602c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1561b9c1b51eSKate Stone   if (PyErr_Occurred()) {
15622c1f46dcSZachary Turner     PyErr_Print();
15632c1f46dcSZachary Turner     PyErr_Clear();
15642c1f46dcSZachary Turner   }
1565b9c1b51eSKate Stone   if (py_return.get()) {
1566f8b22f8fSZachary Turner     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
15672c1f46dcSZachary Turner     return result_dict.CreateStructuredDictionary();
15682c1f46dcSZachary Turner   }
156958b794aeSGreg Clayton   return StructuredData::DictionarySP();
157058b794aeSGreg Clayton }
15712c1f46dcSZachary Turner 
157263dd5d25SJonas Devlieghere StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo(
1573b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp) {
1574b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
15752c1f46dcSZachary Turner 
15762c1f46dcSZachary Turner   static char callee_name[] = "get_thread_info";
15772c1f46dcSZachary Turner 
15782c1f46dcSZachary Turner   if (!os_plugin_object_sp)
15792c1f46dcSZachary Turner     return StructuredData::ArraySP();
15802c1f46dcSZachary Turner 
15812c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
15822c1f46dcSZachary Turner   if (!generic)
15832c1f46dcSZachary Turner     return nullptr;
15842c1f46dcSZachary Turner 
1585b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1586b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
1587f8b22f8fSZachary Turner 
1588f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
15892c1f46dcSZachary Turner     return StructuredData::ArraySP();
15902c1f46dcSZachary Turner 
1591b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1592b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
15932c1f46dcSZachary Turner 
15942c1f46dcSZachary Turner   if (PyErr_Occurred())
15952c1f46dcSZachary Turner     PyErr_Clear();
15962c1f46dcSZachary Turner 
1597f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
15982c1f46dcSZachary Turner     return StructuredData::ArraySP();
15992c1f46dcSZachary Turner 
1600b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
16012c1f46dcSZachary Turner     if (PyErr_Occurred())
16022c1f46dcSZachary Turner       PyErr_Clear();
16032c1f46dcSZachary Turner 
16042c1f46dcSZachary Turner     return StructuredData::ArraySP();
16052c1f46dcSZachary Turner   }
16062c1f46dcSZachary Turner 
16072c1f46dcSZachary Turner   if (PyErr_Occurred())
16082c1f46dcSZachary Turner     PyErr_Clear();
16092c1f46dcSZachary Turner 
16102c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1611b9c1b51eSKate Stone   PythonObject py_return(
1612b9c1b51eSKate Stone       PyRefType::Owned,
1613b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
16142c1f46dcSZachary Turner 
16152c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1616b9c1b51eSKate Stone   if (PyErr_Occurred()) {
16172c1f46dcSZachary Turner     PyErr_Print();
16182c1f46dcSZachary Turner     PyErr_Clear();
16192c1f46dcSZachary Turner   }
16202c1f46dcSZachary Turner 
1621b9c1b51eSKate Stone   if (py_return.get()) {
1622f8b22f8fSZachary Turner     PythonList result_list(PyRefType::Borrowed, py_return.get());
1623f8b22f8fSZachary Turner     return result_list.CreateStructuredArray();
16242c1f46dcSZachary Turner   }
162558b794aeSGreg Clayton   return StructuredData::ArraySP();
162658b794aeSGreg Clayton }
16272c1f46dcSZachary Turner 
162863dd5d25SJonas Devlieghere StructuredData::StringSP
162963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData(
1630b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
1631b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
16322c1f46dcSZachary Turner 
16332c1f46dcSZachary Turner   static char callee_name[] = "get_register_data";
1634b9c1b51eSKate Stone   static char *param_format =
1635b9c1b51eSKate Stone       const_cast<char *>(GetPythonValueFormatString(tid));
16362c1f46dcSZachary Turner 
16372c1f46dcSZachary Turner   if (!os_plugin_object_sp)
16382c1f46dcSZachary Turner     return StructuredData::StringSP();
16392c1f46dcSZachary Turner 
16402c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
16412c1f46dcSZachary Turner   if (!generic)
16422c1f46dcSZachary Turner     return nullptr;
1643b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1644b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
16452c1f46dcSZachary Turner 
1646f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
16472c1f46dcSZachary Turner     return StructuredData::StringSP();
16482c1f46dcSZachary Turner 
1649b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1650b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
16512c1f46dcSZachary Turner 
16522c1f46dcSZachary Turner   if (PyErr_Occurred())
16532c1f46dcSZachary Turner     PyErr_Clear();
16542c1f46dcSZachary Turner 
1655f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
16562c1f46dcSZachary Turner     return StructuredData::StringSP();
16572c1f46dcSZachary Turner 
1658b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
16592c1f46dcSZachary Turner     if (PyErr_Occurred())
16602c1f46dcSZachary Turner       PyErr_Clear();
16612c1f46dcSZachary Turner     return StructuredData::StringSP();
16622c1f46dcSZachary Turner   }
16632c1f46dcSZachary Turner 
16642c1f46dcSZachary Turner   if (PyErr_Occurred())
16652c1f46dcSZachary Turner     PyErr_Clear();
16662c1f46dcSZachary Turner 
16672c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1668b9c1b51eSKate Stone   PythonObject py_return(
1669b9c1b51eSKate Stone       PyRefType::Owned,
1670b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, param_format, tid));
16712c1f46dcSZachary Turner 
16722c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1673b9c1b51eSKate Stone   if (PyErr_Occurred()) {
16742c1f46dcSZachary Turner     PyErr_Print();
16752c1f46dcSZachary Turner     PyErr_Clear();
16762c1f46dcSZachary Turner   }
1677f8b22f8fSZachary Turner 
1678b9c1b51eSKate Stone   if (py_return.get()) {
16797a76845cSZachary Turner     PythonBytes result(PyRefType::Borrowed, py_return.get());
16807a76845cSZachary Turner     return result.CreateStructuredString();
16812c1f46dcSZachary Turner   }
168258b794aeSGreg Clayton   return StructuredData::StringSP();
168358b794aeSGreg Clayton }
16842c1f46dcSZachary Turner 
168563dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread(
1686b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
1687b9c1b51eSKate Stone     lldb::addr_t context) {
1688b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
16892c1f46dcSZachary Turner 
16902c1f46dcSZachary Turner   static char callee_name[] = "create_thread";
16912c1f46dcSZachary Turner   std::string param_format;
16922c1f46dcSZachary Turner   param_format += GetPythonValueFormatString(tid);
16932c1f46dcSZachary Turner   param_format += GetPythonValueFormatString(context);
16942c1f46dcSZachary Turner 
16952c1f46dcSZachary Turner   if (!os_plugin_object_sp)
16962c1f46dcSZachary Turner     return StructuredData::DictionarySP();
16972c1f46dcSZachary Turner 
16982c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
16992c1f46dcSZachary Turner   if (!generic)
17002c1f46dcSZachary Turner     return nullptr;
17012c1f46dcSZachary Turner 
1702b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1703b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
1704f8b22f8fSZachary Turner 
1705f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
17062c1f46dcSZachary Turner     return StructuredData::DictionarySP();
17072c1f46dcSZachary Turner 
1708b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1709b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
17102c1f46dcSZachary Turner 
17112c1f46dcSZachary Turner   if (PyErr_Occurred())
17122c1f46dcSZachary Turner     PyErr_Clear();
17132c1f46dcSZachary Turner 
1714f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
17152c1f46dcSZachary Turner     return StructuredData::DictionarySP();
17162c1f46dcSZachary Turner 
1717b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
17182c1f46dcSZachary Turner     if (PyErr_Occurred())
17192c1f46dcSZachary Turner       PyErr_Clear();
17202c1f46dcSZachary Turner     return StructuredData::DictionarySP();
17212c1f46dcSZachary Turner   }
17222c1f46dcSZachary Turner 
17232c1f46dcSZachary Turner   if (PyErr_Occurred())
17242c1f46dcSZachary Turner     PyErr_Clear();
17252c1f46dcSZachary Turner 
17262c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1727b9c1b51eSKate Stone   PythonObject py_return(PyRefType::Owned,
1728b9c1b51eSKate Stone                          PyObject_CallMethod(implementor.get(), callee_name,
1729b9c1b51eSKate Stone                                              &param_format[0], tid, context));
17302c1f46dcSZachary Turner 
17312c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1732b9c1b51eSKate Stone   if (PyErr_Occurred()) {
17332c1f46dcSZachary Turner     PyErr_Print();
17342c1f46dcSZachary Turner     PyErr_Clear();
17352c1f46dcSZachary Turner   }
17362c1f46dcSZachary Turner 
1737b9c1b51eSKate Stone   if (py_return.get()) {
1738f8b22f8fSZachary Turner     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
17392c1f46dcSZachary Turner     return result_dict.CreateStructuredDictionary();
17402c1f46dcSZachary Turner   }
174158b794aeSGreg Clayton   return StructuredData::DictionarySP();
174258b794aeSGreg Clayton }
17432c1f46dcSZachary Turner 
174463dd5d25SJonas Devlieghere StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan(
174582de8df2SPavel Labath     const char *class_name, const StructuredDataImpl &args_data,
1746a69bbe02SLawrence D'Anna     std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) {
17472c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
17482c1f46dcSZachary Turner     return StructuredData::ObjectSP();
17492c1f46dcSZachary Turner 
17502c1f46dcSZachary Turner   if (!thread_plan_sp.get())
175193c98346SJim Ingham     return {};
17522c1f46dcSZachary Turner 
17532c1f46dcSZachary Turner   Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
175463dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
1755d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
17562c1f46dcSZachary Turner 
1757d055e3a0SPedro Tammela   if (!python_interpreter)
175893c98346SJim Ingham     return {};
17592c1f46dcSZachary Turner 
17602c1f46dcSZachary Turner   void *ret_val;
17612c1f46dcSZachary Turner 
17622c1f46dcSZachary Turner   {
1763b9c1b51eSKate Stone     Locker py_lock(this,
1764b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
176505495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateScriptedThreadPlan(
1766b9c1b51eSKate Stone         class_name, python_interpreter->m_dictionary_name.c_str(),
176727a14f19SJim Ingham         args_data, error_str, thread_plan_sp);
176893c98346SJim Ingham     if (!ret_val)
176993c98346SJim Ingham       return {};
17702c1f46dcSZachary Turner   }
17712c1f46dcSZachary Turner 
17722c1f46dcSZachary Turner   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
17732c1f46dcSZachary Turner }
17742c1f46dcSZachary Turner 
177563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop(
1776b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
17772c1f46dcSZachary Turner   bool explains_stop = true;
17782c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
17792c1f46dcSZachary Turner   if (implementor_sp)
17802c1f46dcSZachary Turner     generic = implementor_sp->GetAsGeneric();
1781b9c1b51eSKate Stone   if (generic) {
1782b9c1b51eSKate Stone     Locker py_lock(this,
1783b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
178405495c5dSJonas Devlieghere     explains_stop = LLDBSWIGPythonCallThreadPlan(
1785b9c1b51eSKate Stone         generic->GetValue(), "explains_stop", event, script_error);
17862c1f46dcSZachary Turner     if (script_error)
17872c1f46dcSZachary Turner       return true;
17882c1f46dcSZachary Turner   }
17892c1f46dcSZachary Turner   return explains_stop;
17902c1f46dcSZachary Turner }
17912c1f46dcSZachary Turner 
179263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop(
1793b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
17942c1f46dcSZachary Turner   bool should_stop = true;
17952c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
17962c1f46dcSZachary Turner   if (implementor_sp)
17972c1f46dcSZachary Turner     generic = implementor_sp->GetAsGeneric();
1798b9c1b51eSKate Stone   if (generic) {
1799b9c1b51eSKate Stone     Locker py_lock(this,
1800b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
180105495c5dSJonas Devlieghere     should_stop = LLDBSWIGPythonCallThreadPlan(
180205495c5dSJonas Devlieghere         generic->GetValue(), "should_stop", event, script_error);
18032c1f46dcSZachary Turner     if (script_error)
18042c1f46dcSZachary Turner       return true;
18052c1f46dcSZachary Turner   }
18062c1f46dcSZachary Turner   return should_stop;
18072c1f46dcSZachary Turner }
18082c1f46dcSZachary Turner 
180963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale(
1810b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1811c915a7d2SJim Ingham   bool is_stale = true;
1812c915a7d2SJim Ingham   StructuredData::Generic *generic = nullptr;
1813c915a7d2SJim Ingham   if (implementor_sp)
1814c915a7d2SJim Ingham     generic = implementor_sp->GetAsGeneric();
1815b9c1b51eSKate Stone   if (generic) {
1816b9c1b51eSKate Stone     Locker py_lock(this,
1817b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
181805495c5dSJonas Devlieghere     is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale",
181905495c5dSJonas Devlieghere                                             nullptr, script_error);
1820c915a7d2SJim Ingham     if (script_error)
1821c915a7d2SJim Ingham       return true;
1822c915a7d2SJim Ingham   }
1823c915a7d2SJim Ingham   return is_stale;
1824c915a7d2SJim Ingham }
1825c915a7d2SJim Ingham 
182663dd5d25SJonas Devlieghere lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState(
1827b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, bool &script_error) {
18282c1f46dcSZachary Turner   bool should_step = false;
18292c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
18302c1f46dcSZachary Turner   if (implementor_sp)
18312c1f46dcSZachary Turner     generic = implementor_sp->GetAsGeneric();
1832b9c1b51eSKate Stone   if (generic) {
1833b9c1b51eSKate Stone     Locker py_lock(this,
1834b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
183505495c5dSJonas Devlieghere     should_step = LLDBSWIGPythonCallThreadPlan(
1836248a1305SKonrad Kleine         generic->GetValue(), "should_step", nullptr, script_error);
18372c1f46dcSZachary Turner     if (script_error)
18382c1f46dcSZachary Turner       should_step = true;
18392c1f46dcSZachary Turner   }
18402c1f46dcSZachary Turner   if (should_step)
18412c1f46dcSZachary Turner     return lldb::eStateStepping;
18422c1f46dcSZachary Turner   return lldb::eStateRunning;
18432c1f46dcSZachary Turner }
18442c1f46dcSZachary Turner 
18453815e702SJim Ingham StructuredData::GenericSP
184663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
184782de8df2SPavel Labath     const char *class_name, const StructuredDataImpl &args_data,
18483815e702SJim Ingham     lldb::BreakpointSP &bkpt_sp) {
18493815e702SJim Ingham 
18503815e702SJim Ingham   if (class_name == nullptr || class_name[0] == '\0')
18513815e702SJim Ingham     return StructuredData::GenericSP();
18523815e702SJim Ingham 
18533815e702SJim Ingham   if (!bkpt_sp.get())
18543815e702SJim Ingham     return StructuredData::GenericSP();
18553815e702SJim Ingham 
18563815e702SJim Ingham   Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
185763dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
1858d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
18593815e702SJim Ingham 
1860d055e3a0SPedro Tammela   if (!python_interpreter)
18613815e702SJim Ingham     return StructuredData::GenericSP();
18623815e702SJim Ingham 
18633815e702SJim Ingham   void *ret_val;
18643815e702SJim Ingham 
18653815e702SJim Ingham   {
18663815e702SJim Ingham     Locker py_lock(this,
18673815e702SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
18683815e702SJim Ingham 
186905495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver(
187005495c5dSJonas Devlieghere         class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
187105495c5dSJonas Devlieghere         bkpt_sp);
18723815e702SJim Ingham   }
18733815e702SJim Ingham 
18743815e702SJim Ingham   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
18753815e702SJim Ingham }
18763815e702SJim Ingham 
187763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
187863dd5d25SJonas Devlieghere     StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
18793815e702SJim Ingham   bool should_continue = false;
18803815e702SJim Ingham 
18813815e702SJim Ingham   if (implementor_sp) {
18823815e702SJim Ingham     Locker py_lock(this,
18833815e702SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
188405495c5dSJonas Devlieghere     should_continue = LLDBSwigPythonCallBreakpointResolver(
188505495c5dSJonas Devlieghere         implementor_sp->GetValue(), "__callback__", sym_ctx);
18863815e702SJim Ingham     if (PyErr_Occurred()) {
18873815e702SJim Ingham       PyErr_Print();
18883815e702SJim Ingham       PyErr_Clear();
18893815e702SJim Ingham     }
18903815e702SJim Ingham   }
18913815e702SJim Ingham   return should_continue;
18923815e702SJim Ingham }
18933815e702SJim Ingham 
18943815e702SJim Ingham lldb::SearchDepth
189563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
18963815e702SJim Ingham     StructuredData::GenericSP implementor_sp) {
18973815e702SJim Ingham   int depth_as_int = lldb::eSearchDepthModule;
18983815e702SJim Ingham   if (implementor_sp) {
18993815e702SJim Ingham     Locker py_lock(this,
19003815e702SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
190105495c5dSJonas Devlieghere     depth_as_int = LLDBSwigPythonCallBreakpointResolver(
190205495c5dSJonas Devlieghere         implementor_sp->GetValue(), "__get_depth__", nullptr);
19033815e702SJim Ingham     if (PyErr_Occurred()) {
19043815e702SJim Ingham       PyErr_Print();
19053815e702SJim Ingham       PyErr_Clear();
19063815e702SJim Ingham     }
19073815e702SJim Ingham   }
19083815e702SJim Ingham   if (depth_as_int == lldb::eSearchDepthInvalid)
19093815e702SJim Ingham     return lldb::eSearchDepthModule;
19103815e702SJim Ingham 
19113815e702SJim Ingham   if (depth_as_int <= lldb::kLastSearchDepthKind)
19123815e702SJim Ingham     return (lldb::SearchDepth)depth_as_int;
19133815e702SJim Ingham   return lldb::eSearchDepthModule;
19143815e702SJim Ingham }
19153815e702SJim Ingham 
19161b1d9815SJim Ingham StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
191782de8df2SPavel Labath     TargetSP target_sp, const char *class_name,
191882de8df2SPavel Labath     const StructuredDataImpl &args_data, Status &error) {
19191b1d9815SJim Ingham 
19201b1d9815SJim Ingham   if (!target_sp) {
19211b1d9815SJim Ingham     error.SetErrorString("No target for scripted stop-hook.");
19221b1d9815SJim Ingham     return StructuredData::GenericSP();
19231b1d9815SJim Ingham   }
19241b1d9815SJim Ingham 
19251b1d9815SJim Ingham   if (class_name == nullptr || class_name[0] == '\0') {
19261b1d9815SJim Ingham     error.SetErrorString("No class name for scripted stop-hook.");
19271b1d9815SJim Ingham     return StructuredData::GenericSP();
19281b1d9815SJim Ingham   }
19291b1d9815SJim Ingham 
19301b1d9815SJim Ingham   ScriptInterpreterPythonImpl *python_interpreter =
1931d055e3a0SPedro Tammela       GetPythonInterpreter(m_debugger);
19321b1d9815SJim Ingham 
1933d055e3a0SPedro Tammela   if (!python_interpreter) {
19341b1d9815SJim Ingham     error.SetErrorString("No script interpreter for scripted stop-hook.");
19351b1d9815SJim Ingham     return StructuredData::GenericSP();
19361b1d9815SJim Ingham   }
19371b1d9815SJim Ingham 
19381b1d9815SJim Ingham   void *ret_val;
19391b1d9815SJim Ingham 
19401b1d9815SJim Ingham   {
19411b1d9815SJim Ingham     Locker py_lock(this,
19421b1d9815SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19431b1d9815SJim Ingham 
19441b1d9815SJim Ingham     ret_val = LLDBSwigPythonCreateScriptedStopHook(
19451b1d9815SJim Ingham         target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
19461b1d9815SJim Ingham         args_data, error);
19471b1d9815SJim Ingham   }
19481b1d9815SJim Ingham 
19491b1d9815SJim Ingham   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
19501b1d9815SJim Ingham }
19511b1d9815SJim Ingham 
19521b1d9815SJim Ingham bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
19531b1d9815SJim Ingham     StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
19541b1d9815SJim Ingham     lldb::StreamSP stream_sp) {
19551b1d9815SJim Ingham   assert(implementor_sp &&
19561b1d9815SJim Ingham          "can't call a stop hook with an invalid implementor");
19571b1d9815SJim Ingham   assert(stream_sp && "can't call a stop hook with an invalid stream");
19581b1d9815SJim Ingham 
19591b1d9815SJim Ingham   Locker py_lock(this,
19601b1d9815SJim Ingham                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19611b1d9815SJim Ingham 
19621b1d9815SJim Ingham   lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
19631b1d9815SJim Ingham 
19641b1d9815SJim Ingham   bool ret_val = LLDBSwigPythonStopHookCallHandleStop(
19651b1d9815SJim Ingham       implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
19661b1d9815SJim Ingham   return ret_val;
19671b1d9815SJim Ingham }
19681b1d9815SJim Ingham 
19692c1f46dcSZachary Turner StructuredData::ObjectSP
197063dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
197197206d57SZachary Turner                                               lldb_private::Status &error) {
1972dbd7fabaSJonas Devlieghere   if (!FileSystem::Instance().Exists(file_spec)) {
19732c1f46dcSZachary Turner     error.SetErrorString("no such file");
19742c1f46dcSZachary Turner     return StructuredData::ObjectSP();
19752c1f46dcSZachary Turner   }
19762c1f46dcSZachary Turner 
19772c1f46dcSZachary Turner   StructuredData::ObjectSP module_sp;
19782c1f46dcSZachary Turner 
1979f9517353SJonas Devlieghere   LoadScriptOptions load_script_options =
1980f9517353SJonas Devlieghere       LoadScriptOptions().SetInitSession(true).SetSilent(false);
1981f9517353SJonas Devlieghere   if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1982f9517353SJonas Devlieghere                           error, &module_sp))
19832c1f46dcSZachary Turner     return module_sp;
19842c1f46dcSZachary Turner 
19852c1f46dcSZachary Turner   return StructuredData::ObjectSP();
19862c1f46dcSZachary Turner }
19872c1f46dcSZachary Turner 
198863dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
1989b9c1b51eSKate Stone     StructuredData::ObjectSP plugin_module_sp, Target *target,
199097206d57SZachary Turner     const char *setting_name, lldb_private::Status &error) {
199105495c5dSJonas Devlieghere   if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
19922c1f46dcSZachary Turner     return StructuredData::DictionarySP();
19932c1f46dcSZachary Turner   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
19942c1f46dcSZachary Turner   if (!generic)
19952c1f46dcSZachary Turner     return StructuredData::DictionarySP();
19962c1f46dcSZachary Turner 
1997b9c1b51eSKate Stone   Locker py_lock(this,
1998b9c1b51eSKate Stone                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19992c1f46dcSZachary Turner   TargetSP target_sp(target->shared_from_this());
20002c1f46dcSZachary Turner 
200104edd189SLawrence D'Anna   auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting(
200204edd189SLawrence D'Anna       generic->GetValue(), setting_name, target_sp);
200304edd189SLawrence D'Anna 
200404edd189SLawrence D'Anna   if (!setting)
200504edd189SLawrence D'Anna     return StructuredData::DictionarySP();
200604edd189SLawrence D'Anna 
200704edd189SLawrence D'Anna   PythonDictionary py_dict =
200804edd189SLawrence D'Anna       unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
200904edd189SLawrence D'Anna 
201004edd189SLawrence D'Anna   if (!py_dict)
201104edd189SLawrence D'Anna     return StructuredData::DictionarySP();
201204edd189SLawrence D'Anna 
20132c1f46dcSZachary Turner   return py_dict.CreateStructuredDictionary();
20142c1f46dcSZachary Turner }
20152c1f46dcSZachary Turner 
20162c1f46dcSZachary Turner StructuredData::ObjectSP
201763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
2018b9c1b51eSKate Stone     const char *class_name, lldb::ValueObjectSP valobj) {
20192c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
20202c1f46dcSZachary Turner     return StructuredData::ObjectSP();
20212c1f46dcSZachary Turner 
20222c1f46dcSZachary Turner   if (!valobj.get())
20232c1f46dcSZachary Turner     return StructuredData::ObjectSP();
20242c1f46dcSZachary Turner 
20252c1f46dcSZachary Turner   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
20262c1f46dcSZachary Turner   Target *target = exe_ctx.GetTargetPtr();
20272c1f46dcSZachary Turner 
20282c1f46dcSZachary Turner   if (!target)
20292c1f46dcSZachary Turner     return StructuredData::ObjectSP();
20302c1f46dcSZachary Turner 
20312c1f46dcSZachary Turner   Debugger &debugger = target->GetDebugger();
203263dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
2033d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
20342c1f46dcSZachary Turner 
2035d055e3a0SPedro Tammela   if (!python_interpreter)
20362c1f46dcSZachary Turner     return StructuredData::ObjectSP();
20372c1f46dcSZachary Turner 
20382c1f46dcSZachary Turner   void *ret_val = nullptr;
20392c1f46dcSZachary Turner 
20402c1f46dcSZachary Turner   {
2041b9c1b51eSKate Stone     Locker py_lock(this,
2042b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
204305495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateSyntheticProvider(
2044b9c1b51eSKate Stone         class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
20452c1f46dcSZachary Turner   }
20462c1f46dcSZachary Turner 
20472c1f46dcSZachary Turner   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
20482c1f46dcSZachary Turner }
20492c1f46dcSZachary Turner 
20502c1f46dcSZachary Turner StructuredData::GenericSP
205163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
20528d1fb843SJonas Devlieghere   DebuggerSP debugger_sp(m_debugger.shared_from_this());
20532c1f46dcSZachary Turner 
20542c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
20552c1f46dcSZachary Turner     return StructuredData::GenericSP();
20562c1f46dcSZachary Turner 
20572c1f46dcSZachary Turner   if (!debugger_sp.get())
20582c1f46dcSZachary Turner     return StructuredData::GenericSP();
20592c1f46dcSZachary Turner 
20602c1f46dcSZachary Turner   void *ret_val;
20612c1f46dcSZachary Turner 
20622c1f46dcSZachary Turner   {
2063b9c1b51eSKate Stone     Locker py_lock(this,
2064b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
206505495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateCommandObject(
206605495c5dSJonas Devlieghere         class_name, m_dictionary_name.c_str(), debugger_sp);
20672c1f46dcSZachary Turner   }
20682c1f46dcSZachary Turner 
20692c1f46dcSZachary Turner   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
20702c1f46dcSZachary Turner }
20712c1f46dcSZachary Turner 
207263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
2073b9c1b51eSKate Stone     const char *oneliner, std::string &output, const void *name_token) {
20742c1f46dcSZachary Turner   StringList input;
20752c1f46dcSZachary Turner   input.SplitIntoLines(oneliner, strlen(oneliner));
20762c1f46dcSZachary Turner   return GenerateTypeScriptFunction(input, output, name_token);
20772c1f46dcSZachary Turner }
20782c1f46dcSZachary Turner 
207963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
208063dd5d25SJonas Devlieghere     const char *oneliner, std::string &output, const void *name_token) {
20812c1f46dcSZachary Turner   StringList input;
20822c1f46dcSZachary Turner   input.SplitIntoLines(oneliner, strlen(oneliner));
20832c1f46dcSZachary Turner   return GenerateTypeSynthClass(input, output, name_token);
20842c1f46dcSZachary Turner }
20852c1f46dcSZachary Turner 
208663dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
2087738af7a6SJim Ingham     StringList &user_input, std::string &output,
2088738af7a6SJim Ingham     bool has_extra_args) {
20892c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
20902c1f46dcSZachary Turner   user_input.RemoveBlankLines();
20912c1f46dcSZachary Turner   StreamString sstr;
209297206d57SZachary Turner   Status error;
2093b9c1b51eSKate Stone   if (user_input.GetSize() == 0) {
20942c1f46dcSZachary Turner     error.SetErrorString("No input data.");
20952c1f46dcSZachary Turner     return error;
20962c1f46dcSZachary Turner   }
20972c1f46dcSZachary Turner 
2098b9c1b51eSKate Stone   std::string auto_generated_function_name(GenerateUniqueName(
2099b9c1b51eSKate Stone       "lldb_autogen_python_bp_callback_func_", num_created_functions));
2100738af7a6SJim Ingham   if (has_extra_args)
2101738af7a6SJim Ingham     sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
2102738af7a6SJim Ingham                 auto_generated_function_name.c_str());
2103738af7a6SJim Ingham   else
2104b9c1b51eSKate Stone     sstr.Printf("def %s (frame, bp_loc, internal_dict):",
2105b9c1b51eSKate Stone                 auto_generated_function_name.c_str());
21062c1f46dcSZachary Turner 
21072c1f46dcSZachary Turner   error = GenerateFunction(sstr.GetData(), user_input);
21082c1f46dcSZachary Turner   if (!error.Success())
21092c1f46dcSZachary Turner     return error;
21102c1f46dcSZachary Turner 
21112c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
21122c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
21132c1f46dcSZachary Turner   return error;
21142c1f46dcSZachary Turner }
21152c1f46dcSZachary Turner 
211663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
2117b9c1b51eSKate Stone     StringList &user_input, std::string &output) {
21182c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
21192c1f46dcSZachary Turner   user_input.RemoveBlankLines();
21202c1f46dcSZachary Turner   StreamString sstr;
21212c1f46dcSZachary Turner 
21222c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
21232c1f46dcSZachary Turner     return false;
21242c1f46dcSZachary Turner 
2125b9c1b51eSKate Stone   std::string auto_generated_function_name(GenerateUniqueName(
2126b9c1b51eSKate Stone       "lldb_autogen_python_wp_callback_func_", num_created_functions));
2127b9c1b51eSKate Stone   sstr.Printf("def %s (frame, wp, internal_dict):",
2128b9c1b51eSKate Stone               auto_generated_function_name.c_str());
21292c1f46dcSZachary Turner 
21302c1f46dcSZachary Turner   if (!GenerateFunction(sstr.GetData(), user_input).Success())
21312c1f46dcSZachary Turner     return false;
21322c1f46dcSZachary Turner 
21332c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
21342c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
21352c1f46dcSZachary Turner   return true;
21362c1f46dcSZachary Turner }
21372c1f46dcSZachary Turner 
213863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetScriptedSummary(
2139b9c1b51eSKate Stone     const char *python_function_name, lldb::ValueObjectSP valobj,
2140b9c1b51eSKate Stone     StructuredData::ObjectSP &callee_wrapper_sp,
2141b9c1b51eSKate Stone     const TypeSummaryOptions &options, std::string &retval) {
21422c1f46dcSZachary Turner 
21435c1c8443SJonas Devlieghere   LLDB_SCOPED_TIMER();
21442c1f46dcSZachary Turner 
2145b9c1b51eSKate Stone   if (!valobj.get()) {
21462c1f46dcSZachary Turner     retval.assign("<no object>");
21472c1f46dcSZachary Turner     return false;
21482c1f46dcSZachary Turner   }
21492c1f46dcSZachary Turner 
21502c1f46dcSZachary Turner   void *old_callee = nullptr;
21512c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
2152b9c1b51eSKate Stone   if (callee_wrapper_sp) {
21532c1f46dcSZachary Turner     generic = callee_wrapper_sp->GetAsGeneric();
21542c1f46dcSZachary Turner     if (generic)
21552c1f46dcSZachary Turner       old_callee = generic->GetValue();
21562c1f46dcSZachary Turner   }
21572c1f46dcSZachary Turner   void *new_callee = old_callee;
21582c1f46dcSZachary Turner 
21592c1f46dcSZachary Turner   bool ret_val;
2160b9c1b51eSKate Stone   if (python_function_name && *python_function_name) {
21612c1f46dcSZachary Turner     {
2162b9c1b51eSKate Stone       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
2163b9c1b51eSKate Stone                                Locker::NoSTDIN);
21642c1f46dcSZachary Turner       {
21652c1f46dcSZachary Turner         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
21662c1f46dcSZachary Turner 
216705495c5dSJonas Devlieghere         static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
216805495c5dSJonas Devlieghere         Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
216905495c5dSJonas Devlieghere         ret_val = LLDBSwigPythonCallTypeScript(
2170b9c1b51eSKate Stone             python_function_name, GetSessionDictionary().get(), valobj,
2171b9c1b51eSKate Stone             &new_callee, options_sp, retval);
21722c1f46dcSZachary Turner       }
21732c1f46dcSZachary Turner     }
2174b9c1b51eSKate Stone   } else {
21752c1f46dcSZachary Turner     retval.assign("<no function name>");
21762c1f46dcSZachary Turner     return false;
21772c1f46dcSZachary Turner   }
21782c1f46dcSZachary Turner 
21792c1f46dcSZachary Turner   if (new_callee && old_callee != new_callee)
2180796ac80bSJonas Devlieghere     callee_wrapper_sp = std::make_shared<StructuredPythonObject>(new_callee);
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)
2832796ac80bSJonas Devlieghere       *module_sp = std::make_shared<StructuredPythonObject>(module_pyobj);
28332c1f46dcSZachary Turner   }
28342c1f46dcSZachary Turner 
28352c1f46dcSZachary Turner   return true;
28362c1f46dcSZachary Turner }
28372c1f46dcSZachary Turner 
283863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
28392c1f46dcSZachary Turner   if (!word || !word[0])
28402c1f46dcSZachary Turner     return false;
28412c1f46dcSZachary Turner 
28422c1f46dcSZachary Turner   llvm::StringRef word_sr(word);
28432c1f46dcSZachary Turner 
284405097246SAdrian Prantl   // filter out a few characters that would just confuse us and that are
284505097246SAdrian Prantl   // clearly not keyword material anyway
284610b113e8SJonas Devlieghere   if (word_sr.find('"') != llvm::StringRef::npos ||
284710b113e8SJonas Devlieghere       word_sr.find('\'') != llvm::StringRef::npos)
28482c1f46dcSZachary Turner     return false;
28492c1f46dcSZachary Turner 
28502c1f46dcSZachary Turner   StreamString command_stream;
28512c1f46dcSZachary Turner   command_stream.Printf("keyword.iskeyword('%s')", word);
28522c1f46dcSZachary Turner   bool result;
28532c1f46dcSZachary Turner   ExecuteScriptOptions options;
28542c1f46dcSZachary Turner   options.SetEnableIO(false);
28552c1f46dcSZachary Turner   options.SetMaskoutErrors(true);
28562c1f46dcSZachary Turner   options.SetSetLLDBGlobals(false);
2857b9c1b51eSKate Stone   if (ExecuteOneLineWithReturn(command_stream.GetData(),
2858b9c1b51eSKate Stone                                ScriptInterpreter::eScriptReturnTypeBool,
2859b9c1b51eSKate Stone                                &result, options))
28602c1f46dcSZachary Turner     return result;
28612c1f46dcSZachary Turner   return false;
28622c1f46dcSZachary Turner }
28632c1f46dcSZachary Turner 
286463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2865b9c1b51eSKate Stone     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2866b9c1b51eSKate Stone     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2867b9c1b51eSKate Stone       m_old_asynch(debugger_sp->GetAsyncExecution()) {
28682c1f46dcSZachary Turner   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
28692c1f46dcSZachary Turner     m_debugger_sp->SetAsyncExecution(false);
28702c1f46dcSZachary Turner   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
28712c1f46dcSZachary Turner     m_debugger_sp->SetAsyncExecution(true);
28722c1f46dcSZachary Turner }
28732c1f46dcSZachary Turner 
287463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
28752c1f46dcSZachary Turner   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
28762c1f46dcSZachary Turner     m_debugger_sp->SetAsyncExecution(m_old_asynch);
28772c1f46dcSZachary Turner }
28782c1f46dcSZachary Turner 
287963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
28804d51a902SRaphael Isemann     const char *impl_function, llvm::StringRef args,
28812c1f46dcSZachary Turner     ScriptedCommandSynchronicity synchronicity,
288297206d57SZachary Turner     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2883b9c1b51eSKate Stone     const lldb_private::ExecutionContext &exe_ctx) {
2884b9c1b51eSKate Stone   if (!impl_function) {
28852c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
28862c1f46dcSZachary Turner     return false;
28872c1f46dcSZachary Turner   }
28882c1f46dcSZachary Turner 
28898d1fb843SJonas Devlieghere   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
28902c1f46dcSZachary Turner   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
28912c1f46dcSZachary Turner 
2892b9c1b51eSKate Stone   if (!debugger_sp.get()) {
28932c1f46dcSZachary Turner     error.SetErrorString("invalid Debugger pointer");
28942c1f46dcSZachary Turner     return false;
28952c1f46dcSZachary Turner   }
28962c1f46dcSZachary Turner 
28972c1f46dcSZachary Turner   bool ret_val = false;
28982c1f46dcSZachary Turner 
28992c1f46dcSZachary Turner   std::string err_msg;
29002c1f46dcSZachary Turner 
29012c1f46dcSZachary Turner   {
29022c1f46dcSZachary Turner     Locker py_lock(this,
2903b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession |
2904b9c1b51eSKate Stone                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
29052c1f46dcSZachary Turner                    Locker::FreeLock | Locker::TearDownSession);
29062c1f46dcSZachary Turner 
2907b9c1b51eSKate Stone     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
29082c1f46dcSZachary Turner 
29094d51a902SRaphael Isemann     std::string args_str = args.str();
291005495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCallCommand(
291105495c5dSJonas Devlieghere         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
291205495c5dSJonas Devlieghere         cmd_retobj, exe_ctx_ref_sp);
29132c1f46dcSZachary Turner   }
29142c1f46dcSZachary Turner 
29152c1f46dcSZachary Turner   if (!ret_val)
29162c1f46dcSZachary Turner     error.SetErrorString("unable to execute script function");
29172c1f46dcSZachary Turner   else
29182c1f46dcSZachary Turner     error.Clear();
29192c1f46dcSZachary Turner 
29202c1f46dcSZachary Turner   return ret_val;
29212c1f46dcSZachary Turner }
29222c1f46dcSZachary Turner 
292363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
29244d51a902SRaphael Isemann     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
29252c1f46dcSZachary Turner     ScriptedCommandSynchronicity synchronicity,
292697206d57SZachary Turner     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2927b9c1b51eSKate Stone     const lldb_private::ExecutionContext &exe_ctx) {
2928b9c1b51eSKate Stone   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
29292c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
29302c1f46dcSZachary Turner     return false;
29312c1f46dcSZachary Turner   }
29322c1f46dcSZachary Turner 
29338d1fb843SJonas Devlieghere   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
29342c1f46dcSZachary Turner   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
29352c1f46dcSZachary Turner 
2936b9c1b51eSKate Stone   if (!debugger_sp.get()) {
29372c1f46dcSZachary Turner     error.SetErrorString("invalid Debugger pointer");
29382c1f46dcSZachary Turner     return false;
29392c1f46dcSZachary Turner   }
29402c1f46dcSZachary Turner 
29412c1f46dcSZachary Turner   bool ret_val = false;
29422c1f46dcSZachary Turner 
29432c1f46dcSZachary Turner   std::string err_msg;
29442c1f46dcSZachary Turner 
29452c1f46dcSZachary Turner   {
29462c1f46dcSZachary Turner     Locker py_lock(this,
2947b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession |
2948b9c1b51eSKate Stone                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
29492c1f46dcSZachary Turner                    Locker::FreeLock | Locker::TearDownSession);
29502c1f46dcSZachary Turner 
2951b9c1b51eSKate Stone     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
29522c1f46dcSZachary Turner 
29534d51a902SRaphael Isemann     std::string args_str = args.str();
29549a14adeaSPavel Labath     ret_val = LLDBSwigPythonCallCommandObject(
29559a14adeaSPavel Labath         static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
29569a14adeaSPavel Labath         args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
29572c1f46dcSZachary Turner   }
29582c1f46dcSZachary Turner 
29592c1f46dcSZachary Turner   if (!ret_val)
29602c1f46dcSZachary Turner     error.SetErrorString("unable to execute script function");
29612c1f46dcSZachary Turner   else
29622c1f46dcSZachary Turner     error.Clear();
29632c1f46dcSZachary Turner 
29642c1f46dcSZachary Turner   return ret_val;
29652c1f46dcSZachary Turner }
29662c1f46dcSZachary Turner 
296793571c3cSJonas Devlieghere /// In Python, a special attribute __doc__ contains the docstring for an object
296893571c3cSJonas Devlieghere /// (function, method, class, ...) if any is defined Otherwise, the attribute's
296993571c3cSJonas Devlieghere /// value is None.
297063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
2971b9c1b51eSKate Stone                                                           std::string &dest) {
29722c1f46dcSZachary Turner   dest.clear();
297393571c3cSJonas Devlieghere 
29742c1f46dcSZachary Turner   if (!item || !*item)
29752c1f46dcSZachary Turner     return false;
297693571c3cSJonas Devlieghere 
29772c1f46dcSZachary Turner   std::string command(item);
29782c1f46dcSZachary Turner   command += ".__doc__";
29792c1f46dcSZachary Turner 
298093571c3cSJonas Devlieghere   // Python is going to point this to valid data if ExecuteOneLineWithReturn
298193571c3cSJonas Devlieghere   // returns successfully.
298293571c3cSJonas Devlieghere   char *result_ptr = nullptr;
29832c1f46dcSZachary Turner 
2984b9c1b51eSKate Stone   if (ExecuteOneLineWithReturn(
298593571c3cSJonas Devlieghere           command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
29862c1f46dcSZachary Turner           &result_ptr,
2987fd2433e1SJonas Devlieghere           ExecuteScriptOptions().SetEnableIO(false))) {
29882c1f46dcSZachary Turner     if (result_ptr)
29892c1f46dcSZachary Turner       dest.assign(result_ptr);
29902c1f46dcSZachary Turner     return true;
29912c1f46dcSZachary Turner   }
299293571c3cSJonas Devlieghere 
299393571c3cSJonas Devlieghere   StreamString str_stream;
299493571c3cSJonas Devlieghere   str_stream << "Function " << item
299593571c3cSJonas Devlieghere              << " was not found. Containing module might be missing.";
299693571c3cSJonas Devlieghere   dest = std::string(str_stream.GetString());
299793571c3cSJonas Devlieghere 
299893571c3cSJonas Devlieghere   return false;
29992c1f46dcSZachary Turner }
30002c1f46dcSZachary Turner 
300163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
3002b9c1b51eSKate Stone     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
30032c1f46dcSZachary Turner   dest.clear();
30042c1f46dcSZachary Turner 
3005b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
30062c1f46dcSZachary Turner 
30072c1f46dcSZachary Turner   static char callee_name[] = "get_short_help";
30082c1f46dcSZachary Turner 
30092c1f46dcSZachary Turner   if (!cmd_obj_sp)
30102c1f46dcSZachary Turner     return false;
30112c1f46dcSZachary Turner 
3012b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
3013b9c1b51eSKate Stone                            (PyObject *)cmd_obj_sp->GetValue());
30142c1f46dcSZachary Turner 
3015f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
30162c1f46dcSZachary Turner     return false;
30172c1f46dcSZachary Turner 
3018b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
3019b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
30202c1f46dcSZachary Turner 
30212c1f46dcSZachary Turner   if (PyErr_Occurred())
30222c1f46dcSZachary Turner     PyErr_Clear();
30232c1f46dcSZachary Turner 
3024f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
30252c1f46dcSZachary Turner     return false;
30262c1f46dcSZachary Turner 
3027b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
30282c1f46dcSZachary Turner     if (PyErr_Occurred())
30292c1f46dcSZachary Turner       PyErr_Clear();
30302c1f46dcSZachary Turner     return false;
30312c1f46dcSZachary Turner   }
30322c1f46dcSZachary Turner 
30332c1f46dcSZachary Turner   if (PyErr_Occurred())
30342c1f46dcSZachary Turner     PyErr_Clear();
30352c1f46dcSZachary Turner 
303693571c3cSJonas Devlieghere   // Right now we know this function exists and is callable.
3037b9c1b51eSKate Stone   PythonObject py_return(
3038b9c1b51eSKate Stone       PyRefType::Owned,
3039b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
30402c1f46dcSZachary Turner 
304193571c3cSJonas Devlieghere   // If it fails, print the error but otherwise go on.
3042b9c1b51eSKate Stone   if (PyErr_Occurred()) {
30432c1f46dcSZachary Turner     PyErr_Print();
30442c1f46dcSZachary Turner     PyErr_Clear();
30452c1f46dcSZachary Turner   }
30462c1f46dcSZachary Turner 
3047b9c1b51eSKate Stone   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3048f8b22f8fSZachary Turner     PythonString py_string(PyRefType::Borrowed, py_return.get());
304922c8efcdSZachary Turner     llvm::StringRef return_data(py_string.GetString());
305022c8efcdSZachary Turner     dest.assign(return_data.data(), return_data.size());
305193571c3cSJonas Devlieghere     return true;
30522c1f46dcSZachary Turner   }
305393571c3cSJonas Devlieghere 
305493571c3cSJonas Devlieghere   return false;
30552c1f46dcSZachary Turner }
30562c1f46dcSZachary Turner 
305763dd5d25SJonas Devlieghere uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
3058b9c1b51eSKate Stone     StructuredData::GenericSP cmd_obj_sp) {
30592c1f46dcSZachary Turner   uint32_t result = 0;
30602c1f46dcSZachary Turner 
3061b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
30622c1f46dcSZachary Turner 
30632c1f46dcSZachary Turner   static char callee_name[] = "get_flags";
30642c1f46dcSZachary Turner 
30652c1f46dcSZachary Turner   if (!cmd_obj_sp)
30662c1f46dcSZachary Turner     return result;
30672c1f46dcSZachary Turner 
3068b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
3069b9c1b51eSKate Stone                            (PyObject *)cmd_obj_sp->GetValue());
30702c1f46dcSZachary Turner 
3071f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
30722c1f46dcSZachary Turner     return result;
30732c1f46dcSZachary Turner 
3074b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
3075b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
30762c1f46dcSZachary Turner 
30772c1f46dcSZachary Turner   if (PyErr_Occurred())
30782c1f46dcSZachary Turner     PyErr_Clear();
30792c1f46dcSZachary Turner 
3080f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
30812c1f46dcSZachary Turner     return result;
30822c1f46dcSZachary Turner 
3083b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
30842c1f46dcSZachary Turner     if (PyErr_Occurred())
30852c1f46dcSZachary Turner       PyErr_Clear();
30862c1f46dcSZachary Turner     return result;
30872c1f46dcSZachary Turner   }
30882c1f46dcSZachary Turner 
30892c1f46dcSZachary Turner   if (PyErr_Occurred())
30902c1f46dcSZachary Turner     PyErr_Clear();
30912c1f46dcSZachary Turner 
309252712d3fSLawrence D'Anna   long long py_return = unwrapOrSetPythonException(
309352712d3fSLawrence D'Anna       As<long long>(implementor.CallMethod(callee_name)));
30942c1f46dcSZachary Turner 
30952c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
3096b9c1b51eSKate Stone   if (PyErr_Occurred()) {
30972c1f46dcSZachary Turner     PyErr_Print();
30982c1f46dcSZachary Turner     PyErr_Clear();
309952712d3fSLawrence D'Anna   } else {
310052712d3fSLawrence D'Anna     result = py_return;
31012c1f46dcSZachary Turner   }
31022c1f46dcSZachary Turner 
31032c1f46dcSZachary Turner   return result;
31042c1f46dcSZachary Turner }
31052c1f46dcSZachary Turner 
310663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3107b9c1b51eSKate Stone     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
31082c1f46dcSZachary Turner   bool got_string = false;
31092c1f46dcSZachary Turner   dest.clear();
31102c1f46dcSZachary Turner 
3111b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
31122c1f46dcSZachary Turner 
31132c1f46dcSZachary Turner   static char callee_name[] = "get_long_help";
31142c1f46dcSZachary Turner 
31152c1f46dcSZachary Turner   if (!cmd_obj_sp)
31162c1f46dcSZachary Turner     return false;
31172c1f46dcSZachary Turner 
3118b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
3119b9c1b51eSKate Stone                            (PyObject *)cmd_obj_sp->GetValue());
31202c1f46dcSZachary Turner 
3121f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
31222c1f46dcSZachary Turner     return false;
31232c1f46dcSZachary Turner 
3124b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
3125b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
31262c1f46dcSZachary Turner 
31272c1f46dcSZachary Turner   if (PyErr_Occurred())
31282c1f46dcSZachary Turner     PyErr_Clear();
31292c1f46dcSZachary Turner 
3130f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
31312c1f46dcSZachary Turner     return false;
31322c1f46dcSZachary Turner 
3133b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
31342c1f46dcSZachary Turner     if (PyErr_Occurred())
31352c1f46dcSZachary Turner       PyErr_Clear();
31362c1f46dcSZachary Turner 
31372c1f46dcSZachary Turner     return false;
31382c1f46dcSZachary Turner   }
31392c1f46dcSZachary Turner 
31402c1f46dcSZachary Turner   if (PyErr_Occurred())
31412c1f46dcSZachary Turner     PyErr_Clear();
31422c1f46dcSZachary Turner 
31432c1f46dcSZachary Turner   // right now we know this function exists and is callable..
3144b9c1b51eSKate Stone   PythonObject py_return(
3145b9c1b51eSKate Stone       PyRefType::Owned,
3146b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
31472c1f46dcSZachary Turner 
31482c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
3149b9c1b51eSKate Stone   if (PyErr_Occurred()) {
31502c1f46dcSZachary Turner     PyErr_Print();
31512c1f46dcSZachary Turner     PyErr_Clear();
31522c1f46dcSZachary Turner   }
31532c1f46dcSZachary Turner 
3154b9c1b51eSKate Stone   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3155f8b22f8fSZachary Turner     PythonString str(PyRefType::Borrowed, py_return.get());
315622c8efcdSZachary Turner     llvm::StringRef str_data(str.GetString());
315722c8efcdSZachary Turner     dest.assign(str_data.data(), str_data.size());
31582c1f46dcSZachary Turner     got_string = true;
31592c1f46dcSZachary Turner   }
31602c1f46dcSZachary Turner 
31612c1f46dcSZachary Turner   return got_string;
31622c1f46dcSZachary Turner }
31632c1f46dcSZachary Turner 
31642c1f46dcSZachary Turner std::unique_ptr<ScriptInterpreterLocker>
316563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3166b9c1b51eSKate Stone   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3167b9c1b51eSKate Stone       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
31682c1f46dcSZachary Turner       Locker::FreeLock | Locker::TearDownSession));
31692c1f46dcSZachary Turner   return py_lock;
31702c1f46dcSZachary Turner }
31712c1f46dcSZachary Turner 
3172*049ae930SJonas Devlieghere #if LLDB_USE_PYTHON_SET_INTERRUPT
3173*049ae930SJonas Devlieghere namespace {
3174*049ae930SJonas Devlieghere /// Saves the current signal handler for the specified signal and restores
3175*049ae930SJonas Devlieghere /// it at the end of the current scope.
3176*049ae930SJonas Devlieghere struct RestoreSignalHandlerScope {
3177*049ae930SJonas Devlieghere   /// The signal handler.
3178*049ae930SJonas Devlieghere   struct sigaction m_prev_handler;
3179*049ae930SJonas Devlieghere   int m_signal_code;
3180*049ae930SJonas Devlieghere   RestoreSignalHandlerScope(int signal_code) : m_signal_code(signal_code) {
3181*049ae930SJonas Devlieghere     // Initialize sigaction to their default state.
3182*049ae930SJonas Devlieghere     std::memset(&m_prev_handler, 0, sizeof(m_prev_handler));
3183*049ae930SJonas Devlieghere     // Don't install a new handler, just read back the old one.
3184*049ae930SJonas Devlieghere     struct sigaction *new_handler = nullptr;
3185*049ae930SJonas Devlieghere     int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler);
3186*049ae930SJonas Devlieghere     lldbassert(signal_err == 0 && "sigaction failed to read handler");
3187*049ae930SJonas Devlieghere   }
3188*049ae930SJonas Devlieghere   ~RestoreSignalHandlerScope() {
3189*049ae930SJonas Devlieghere     int signal_err = ::sigaction(m_signal_code, &m_prev_handler, nullptr);
3190*049ae930SJonas Devlieghere     lldbassert(signal_err == 0 && "sigaction failed to restore old handler");
3191*049ae930SJonas Devlieghere   }
3192*049ae930SJonas Devlieghere };
3193*049ae930SJonas Devlieghere } // namespace
3194*049ae930SJonas Devlieghere #endif
3195*049ae930SJonas Devlieghere 
319663dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::InitializePrivate() {
319715d1b4e2SEnrico Granata   if (g_initialized)
319815d1b4e2SEnrico Granata     return;
319915d1b4e2SEnrico Granata 
32002c1f46dcSZachary Turner   g_initialized = true;
32012c1f46dcSZachary Turner 
32025c1c8443SJonas Devlieghere   LLDB_SCOPED_TIMER();
32032c1f46dcSZachary Turner 
3204b9c1b51eSKate Stone   // RAII-based initialization which correctly handles multiple-initialization,
320505097246SAdrian Prantl   // version- specific differences among Python 2 and Python 3, and saving and
320605097246SAdrian Prantl   // restoring various other pieces of state that can get mucked with during
320705097246SAdrian Prantl   // initialization.
3208079fe48aSZachary Turner   InitializePythonRAII initialize_guard;
32092c1f46dcSZachary Turner 
321005495c5dSJonas Devlieghere   LLDBSwigPyInit();
32112c1f46dcSZachary Turner 
3212b9c1b51eSKate Stone   // Update the path python uses to search for modules to include the current
3213b9c1b51eSKate Stone   // directory.
32142c1f46dcSZachary Turner 
32152c1f46dcSZachary Turner   PyRun_SimpleString("import sys");
32162c1f46dcSZachary Turner   AddToSysPath(AddLocation::End, ".");
32172c1f46dcSZachary Turner 
3218b9c1b51eSKate Stone   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
321905097246SAdrian Prantl   // that use a backslash as the path separator, this will result in executing
322005097246SAdrian Prantl   // python code containing paths with unescaped backslashes.  But Python also
322105097246SAdrian Prantl   // accepts forward slashes, so to make life easier we just use that.
32222df331b0SPavel Labath   if (FileSpec file_spec = GetPythonDir())
32232c1f46dcSZachary Turner     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
322460f028ffSPavel Labath   if (FileSpec file_spec = HostInfo::GetShlibDir())
32252c1f46dcSZachary Turner     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
32262c1f46dcSZachary Turner 
3227b9c1b51eSKate Stone   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3228b9c1b51eSKate Stone                      "lldb.embedded_interpreter; from "
3229b9c1b51eSKate Stone                      "lldb.embedded_interpreter import run_python_interpreter; "
3230b9c1b51eSKate Stone                      "from lldb.embedded_interpreter import run_one_line");
3231*049ae930SJonas Devlieghere 
3232*049ae930SJonas Devlieghere #if LLDB_USE_PYTHON_SET_INTERRUPT
3233*049ae930SJonas Devlieghere   // Python will not just overwrite its internal SIGINT handler but also the
3234*049ae930SJonas Devlieghere   // one from the process. Backup the current SIGINT handler to prevent that
3235*049ae930SJonas Devlieghere   // Python deletes it.
3236*049ae930SJonas Devlieghere   RestoreSignalHandlerScope save_sigint(SIGINT);
3237*049ae930SJonas Devlieghere 
3238*049ae930SJonas Devlieghere   // Setup a default SIGINT signal handler that works the same way as the
3239*049ae930SJonas Devlieghere   // normal Python REPL signal handler which raises a KeyboardInterrupt.
3240*049ae930SJonas Devlieghere   // Also make sure to not pollute the user's REPL with the signal module nor
3241*049ae930SJonas Devlieghere   // our utility function.
3242*049ae930SJonas Devlieghere   PyRun_SimpleString("def lldb_setup_sigint_handler():\n"
3243*049ae930SJonas Devlieghere                      "  import signal;\n"
3244*049ae930SJonas Devlieghere                      "  def signal_handler(sig, frame):\n"
3245*049ae930SJonas Devlieghere                      "    raise KeyboardInterrupt()\n"
3246*049ae930SJonas Devlieghere                      "  signal.signal(signal.SIGINT, signal_handler);\n"
3247*049ae930SJonas Devlieghere                      "lldb_setup_sigint_handler();\n"
3248*049ae930SJonas Devlieghere                      "del lldb_setup_sigint_handler\n");
3249*049ae930SJonas Devlieghere #endif
32502c1f46dcSZachary Turner }
32512c1f46dcSZachary Turner 
325263dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3253b9c1b51eSKate Stone                                                std::string path) {
32542c1f46dcSZachary Turner   std::string path_copy;
32552c1f46dcSZachary Turner 
32562c1f46dcSZachary Turner   std::string statement;
3257b9c1b51eSKate Stone   if (location == AddLocation::Beginning) {
32582c1f46dcSZachary Turner     statement.assign("sys.path.insert(0,\"");
32592c1f46dcSZachary Turner     statement.append(path);
32602c1f46dcSZachary Turner     statement.append("\")");
3261b9c1b51eSKate Stone   } else {
32622c1f46dcSZachary Turner     statement.assign("sys.path.append(\"");
32632c1f46dcSZachary Turner     statement.append(path);
32642c1f46dcSZachary Turner     statement.append("\")");
32652c1f46dcSZachary Turner   }
32662c1f46dcSZachary Turner   PyRun_SimpleString(statement.c_str());
32672c1f46dcSZachary Turner }
32682c1f46dcSZachary Turner 
3269bcadb5a3SPavel Labath // We are intentionally NOT calling Py_Finalize here (this would be the logical
3270bcadb5a3SPavel Labath // place to call it).  Calling Py_Finalize here causes test suite runs to seg
3271bcadb5a3SPavel Labath // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
3272bcadb5a3SPavel Labath // be called 'at_exit'.  When the test suite Python harness finishes up, it
3273bcadb5a3SPavel Labath // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3274bcadb5a3SPavel Labath // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3275bcadb5a3SPavel Labath // which calls ScriptInterpreter::Terminate, which calls
327663dd5d25SJonas Devlieghere // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
327763dd5d25SJonas Devlieghere // end up with Py_Finalize being called from within Py_Finalize, which results
327863dd5d25SJonas Devlieghere // in a seg fault. Since this function only gets called when lldb is shutting
327963dd5d25SJonas Devlieghere // down and going away anyway, the fact that we don't actually call Py_Finalize
3280bcadb5a3SPavel Labath // should not cause any problems (everything should shut down/go away anyway
3281bcadb5a3SPavel Labath // when the process exits).
3282bcadb5a3SPavel Labath //
328363dd5d25SJonas Devlieghere // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3284d68983e3SPavel Labath 
32854e26cf2cSJonas Devlieghere #endif
3286