15ffd83dbSDimitry Andric //===-- ScriptInterpreterPython.cpp ---------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
9480093f4SDimitry Andric #include "lldb/Host/Config.h"
10e8d8bef9SDimitry Andric #include "lldb/lldb-enumerations.h"
110b57cec5SDimitry Andric 
12480093f4SDimitry Andric #if LLDB_ENABLE_PYTHON
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric // LLDB Python header must be included first
150b57cec5SDimitry Andric #include "lldb-python.h"
160b57cec5SDimitry Andric 
175f757f3fSDimitry Andric #include "Interfaces/OperatingSystemPythonInterface.h"
185f757f3fSDimitry Andric #include "Interfaces/ScriptedPlatformPythonInterface.h"
195f757f3fSDimitry Andric #include "Interfaces/ScriptedProcessPythonInterface.h"
205f757f3fSDimitry Andric #include "Interfaces/ScriptedThreadPythonInterface.h"
210b57cec5SDimitry Andric #include "PythonDataObjects.h"
22c14a5a88SDimitry Andric #include "PythonReadline.h"
23fe6060f1SDimitry Andric #include "SWIGPythonBridge.h"
240b57cec5SDimitry Andric #include "ScriptInterpreterPythonImpl.h"
25fe6060f1SDimitry Andric 
26fe6060f1SDimitry Andric #include "lldb/API/SBError.h"
270b57cec5SDimitry Andric #include "lldb/API/SBFrame.h"
280b57cec5SDimitry Andric #include "lldb/API/SBValue.h"
290b57cec5SDimitry Andric #include "lldb/Breakpoint/StoppointCallbackContext.h"
300b57cec5SDimitry Andric #include "lldb/Breakpoint/WatchpointOptions.h"
310b57cec5SDimitry Andric #include "lldb/Core/Debugger.h"
320b57cec5SDimitry Andric #include "lldb/Core/PluginManager.h"
33bdd1243dSDimitry Andric #include "lldb/Core/ThreadedCommunication.h"
340b57cec5SDimitry Andric #include "lldb/Core/ValueObject.h"
350b57cec5SDimitry Andric #include "lldb/DataFormatters/TypeSummary.h"
360b57cec5SDimitry Andric #include "lldb/Host/FileSystem.h"
370b57cec5SDimitry Andric #include "lldb/Host/HostInfo.h"
380b57cec5SDimitry Andric #include "lldb/Host/Pipe.h"
390b57cec5SDimitry Andric #include "lldb/Interpreter/CommandInterpreter.h"
400b57cec5SDimitry Andric #include "lldb/Interpreter/CommandReturnObject.h"
410b57cec5SDimitry Andric #include "lldb/Target/Thread.h"
420b57cec5SDimitry Andric #include "lldb/Target/ThreadPlan.h"
4304eeddc0SDimitry Andric #include "lldb/Utility/Instrumentation.h"
4481ad6265SDimitry Andric #include "lldb/Utility/LLDBLog.h"
450b57cec5SDimitry Andric #include "lldb/Utility/Timer.h"
460b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
470b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
485ffd83dbSDimitry Andric #include "llvm/Support/Error.h"
490b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
509dba64beSDimitry Andric #include "llvm/Support/FormatAdapters.h"
510b57cec5SDimitry Andric 
52fe6060f1SDimitry Andric #include <cstdio>
53fe6060f1SDimitry Andric #include <cstdlib>
540b57cec5SDimitry Andric #include <memory>
550b57cec5SDimitry Andric #include <mutex>
56bdd1243dSDimitry Andric #include <optional>
570b57cec5SDimitry Andric #include <string>
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric using namespace lldb;
600b57cec5SDimitry Andric using namespace lldb_private;
619dba64beSDimitry Andric using namespace lldb_private::python;
629dba64beSDimitry Andric using llvm::Expected;
630b57cec5SDimitry Andric 
645ffd83dbSDimitry Andric LLDB_PLUGIN_DEFINE(ScriptInterpreterPython)
655ffd83dbSDimitry Andric 
660b57cec5SDimitry Andric // Defined in the SWIG source file
670b57cec5SDimitry Andric extern "C" PyObject *PyInit__lldb(void);
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric #define LLDBSwigPyInit PyInit__lldb
700b57cec5SDimitry Andric 
7104eeddc0SDimitry Andric #if defined(_WIN32)
7204eeddc0SDimitry Andric // Don't mess with the signal handlers on Windows.
7304eeddc0SDimitry Andric #define LLDB_USE_PYTHON_SET_INTERRUPT 0
7404eeddc0SDimitry Andric #else
7504eeddc0SDimitry Andric // PyErr_SetInterrupt was introduced in 3.2.
7604eeddc0SDimitry Andric #define LLDB_USE_PYTHON_SET_INTERRUPT                                          \
7704eeddc0SDimitry Andric   (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
7804eeddc0SDimitry Andric #endif
790b57cec5SDimitry Andric 
GetPythonInterpreter(Debugger & debugger)80e8d8bef9SDimitry Andric static ScriptInterpreterPythonImpl *GetPythonInterpreter(Debugger &debugger) {
81e8d8bef9SDimitry Andric   ScriptInterpreter *script_interpreter =
82e8d8bef9SDimitry Andric       debugger.GetScriptInterpreter(true, lldb::eScriptLanguagePython);
83e8d8bef9SDimitry Andric   return static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
84e8d8bef9SDimitry Andric }
85e8d8bef9SDimitry Andric 
860b57cec5SDimitry Andric namespace {
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric // Initializing Python is not a straightforward process.  We cannot control
890b57cec5SDimitry Andric // what external code may have done before getting to this point in LLDB,
900b57cec5SDimitry Andric // including potentially having already initialized Python, so we need to do a
910b57cec5SDimitry Andric // lot of work to ensure that the existing state of the system is maintained
920b57cec5SDimitry Andric // across our initialization.  We do this by using an RAII pattern where we
930b57cec5SDimitry Andric // save off initial state at the beginning, and restore it at the end
940b57cec5SDimitry Andric struct InitializePythonRAII {
950b57cec5SDimitry Andric public:
InitializePythonRAII__anon39f5c0ba0111::InitializePythonRAII96fe6060f1SDimitry Andric   InitializePythonRAII() {
970b57cec5SDimitry Andric     InitializePythonHome();
980b57cec5SDimitry Andric 
99c14a5a88SDimitry Andric #ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
100c14a5a88SDimitry Andric     // Python's readline is incompatible with libedit being linked into lldb.
101c14a5a88SDimitry Andric     // Provide a patched version local to the embedded interpreter.
102c14a5a88SDimitry Andric     bool ReadlinePatched = false;
103bdd1243dSDimitry Andric     for (auto *p = PyImport_Inittab; p->name != nullptr; p++) {
104c14a5a88SDimitry Andric       if (strcmp(p->name, "readline") == 0) {
105c14a5a88SDimitry Andric         p->initfunc = initlldb_readline;
106c14a5a88SDimitry Andric         break;
107c14a5a88SDimitry Andric       }
108c14a5a88SDimitry Andric     }
109c14a5a88SDimitry Andric     if (!ReadlinePatched) {
110c14a5a88SDimitry Andric       PyImport_AppendInittab("readline", initlldb_readline);
111c14a5a88SDimitry Andric       ReadlinePatched = true;
112c14a5a88SDimitry Andric     }
113c14a5a88SDimitry Andric #endif
114c14a5a88SDimitry Andric 
1150b57cec5SDimitry Andric     // Register _lldb as a built-in module.
1160b57cec5SDimitry Andric     PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
1190b57cec5SDimitry Andric // calling `Py_Initialize` and `PyEval_InitThreads`.  < 3.2 requires that you
1200b57cec5SDimitry Andric // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
1210b57cec5SDimitry Andric #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
1220b57cec5SDimitry Andric     Py_InitializeEx(0);
1230b57cec5SDimitry Andric     InitializeThreadsPrivate();
1240b57cec5SDimitry Andric #else
1250b57cec5SDimitry Andric     InitializeThreadsPrivate();
1260b57cec5SDimitry Andric     Py_InitializeEx(0);
1270b57cec5SDimitry Andric #endif
1280b57cec5SDimitry Andric   }
1290b57cec5SDimitry Andric 
~InitializePythonRAII__anon39f5c0ba0111::InitializePythonRAII1300b57cec5SDimitry Andric   ~InitializePythonRAII() {
1310b57cec5SDimitry Andric     if (m_was_already_initialized) {
13281ad6265SDimitry Andric       Log *log = GetLog(LLDBLog::Script);
1330b57cec5SDimitry Andric       LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
1340b57cec5SDimitry Andric                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
1350b57cec5SDimitry Andric       PyGILState_Release(m_gil_state);
1360b57cec5SDimitry Andric     } else {
1370b57cec5SDimitry Andric       // We initialized the threads in this function, just unlock the GIL.
1380b57cec5SDimitry Andric       PyEval_SaveThread();
1390b57cec5SDimitry Andric     }
1400b57cec5SDimitry Andric   }
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric private:
InitializePythonHome__anon39f5c0ba0111::InitializePythonRAII1430b57cec5SDimitry Andric   void InitializePythonHome() {
1445ffd83dbSDimitry Andric #if LLDB_EMBED_PYTHON_HOME
1455ffd83dbSDimitry Andric     typedef wchar_t *str_type;
1465ffd83dbSDimitry Andric     static str_type g_python_home = []() -> str_type {
1475ffd83dbSDimitry Andric       const char *lldb_python_home = LLDB_PYTHON_HOME;
1485ffd83dbSDimitry Andric       const char *absolute_python_home = nullptr;
1495ffd83dbSDimitry Andric       llvm::SmallString<64> path;
1505ffd83dbSDimitry Andric       if (llvm::sys::path::is_absolute(lldb_python_home)) {
1515ffd83dbSDimitry Andric         absolute_python_home = lldb_python_home;
1525ffd83dbSDimitry Andric       } else {
1535ffd83dbSDimitry Andric         FileSpec spec = HostInfo::GetShlibDir();
1545ffd83dbSDimitry Andric         if (!spec)
1555ffd83dbSDimitry Andric           return nullptr;
1565ffd83dbSDimitry Andric         spec.GetPath(path);
1575ffd83dbSDimitry Andric         llvm::sys::path::append(path, lldb_python_home);
1585ffd83dbSDimitry Andric         absolute_python_home = path.c_str();
1595ffd83dbSDimitry Andric       }
1600b57cec5SDimitry Andric       size_t size = 0;
1615ffd83dbSDimitry Andric       return Py_DecodeLocale(absolute_python_home, &size);
1625ffd83dbSDimitry Andric     }();
1635ffd83dbSDimitry Andric     if (g_python_home != nullptr) {
1640b57cec5SDimitry Andric       Py_SetPythonHome(g_python_home);
1655ffd83dbSDimitry Andric     }
1660b57cec5SDimitry Andric #endif
1670b57cec5SDimitry Andric   }
1680b57cec5SDimitry Andric 
InitializeThreadsPrivate__anon39f5c0ba0111::InitializePythonRAII1690b57cec5SDimitry Andric   void InitializeThreadsPrivate() {
1700b57cec5SDimitry Andric // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself,
1710b57cec5SDimitry Andric // so there is no way to determine whether the embedded interpreter
1720b57cec5SDimitry Andric // was already initialized by some external code. `PyEval_ThreadsInitialized`
1730b57cec5SDimitry Andric // would always return `true` and `PyGILState_Ensure/Release` flow would be
1740b57cec5SDimitry Andric // executed instead of unlocking GIL with `PyEval_SaveThread`. When
1750b57cec5SDimitry Andric // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock.
1760b57cec5SDimitry Andric #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3)
1770b57cec5SDimitry Andric     // The only case we should go further and acquire the GIL: it is unlocked.
1780b57cec5SDimitry Andric     if (PyGILState_Check())
1790b57cec5SDimitry Andric       return;
1800b57cec5SDimitry Andric #endif
1810b57cec5SDimitry Andric 
1825f757f3fSDimitry Andric // `PyEval_ThreadsInitialized` was deprecated in Python 3.9 and removed in
1835f757f3fSDimitry Andric // Python 3.13. It has been returning `true` always since Python 3.7.
1845f757f3fSDimitry Andric #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 9) || (PY_MAJOR_VERSION < 3)
1850b57cec5SDimitry Andric     if (PyEval_ThreadsInitialized()) {
1865f757f3fSDimitry Andric #else
1875f757f3fSDimitry Andric     if (true) {
1885f757f3fSDimitry Andric #endif
18981ad6265SDimitry Andric       Log *log = GetLog(LLDBLog::Script);
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric       m_was_already_initialized = true;
1920b57cec5SDimitry Andric       m_gil_state = PyGILState_Ensure();
1930b57cec5SDimitry Andric       LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n",
1940b57cec5SDimitry Andric                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
1955f757f3fSDimitry Andric 
1965f757f3fSDimitry Andric // `PyEval_InitThreads` was deprecated in Python 3.9 and removed in
1975f757f3fSDimitry Andric // Python 3.13.
1985f757f3fSDimitry Andric #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 9) || (PY_MAJOR_VERSION < 3)
1990b57cec5SDimitry Andric       return;
2000b57cec5SDimitry Andric     }
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric     // InitThreads acquires the GIL if it hasn't been called before.
2030b57cec5SDimitry Andric     PyEval_InitThreads();
2045f757f3fSDimitry Andric #else
2055f757f3fSDimitry Andric     }
2065f757f3fSDimitry Andric #endif
2070b57cec5SDimitry Andric   }
2080b57cec5SDimitry Andric 
209fe6060f1SDimitry Andric   PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
210fe6060f1SDimitry Andric   bool m_was_already_initialized = false;
2110b57cec5SDimitry Andric };
21204eeddc0SDimitry Andric 
21304eeddc0SDimitry Andric #if LLDB_USE_PYTHON_SET_INTERRUPT
21404eeddc0SDimitry Andric /// Saves the current signal handler for the specified signal and restores
21504eeddc0SDimitry Andric /// it at the end of the current scope.
21604eeddc0SDimitry Andric struct RestoreSignalHandlerScope {
21704eeddc0SDimitry Andric   /// The signal handler.
21804eeddc0SDimitry Andric   struct sigaction m_prev_handler;
21904eeddc0SDimitry Andric   int m_signal_code;
RestoreSignalHandlerScope__anon39f5c0ba0111::RestoreSignalHandlerScope22004eeddc0SDimitry Andric   RestoreSignalHandlerScope(int signal_code) : m_signal_code(signal_code) {
22104eeddc0SDimitry Andric     // Initialize sigaction to their default state.
22204eeddc0SDimitry Andric     std::memset(&m_prev_handler, 0, sizeof(m_prev_handler));
22304eeddc0SDimitry Andric     // Don't install a new handler, just read back the old one.
22404eeddc0SDimitry Andric     struct sigaction *new_handler = nullptr;
22504eeddc0SDimitry Andric     int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler);
22604eeddc0SDimitry Andric     lldbassert(signal_err == 0 && "sigaction failed to read handler");
22704eeddc0SDimitry Andric   }
~RestoreSignalHandlerScope__anon39f5c0ba0111::RestoreSignalHandlerScope22804eeddc0SDimitry Andric   ~RestoreSignalHandlerScope() {
22904eeddc0SDimitry Andric     int signal_err = ::sigaction(m_signal_code, &m_prev_handler, nullptr);
23004eeddc0SDimitry Andric     lldbassert(signal_err == 0 && "sigaction failed to restore old handler");
23104eeddc0SDimitry Andric   }
23204eeddc0SDimitry Andric };
23304eeddc0SDimitry Andric #endif
2340b57cec5SDimitry Andric } // namespace
2350b57cec5SDimitry Andric 
ComputePythonDirForApple(llvm::SmallVectorImpl<char> & path)2360b57cec5SDimitry Andric void ScriptInterpreterPython::ComputePythonDirForApple(
2370b57cec5SDimitry Andric     llvm::SmallVectorImpl<char> &path) {
2380b57cec5SDimitry Andric   auto style = llvm::sys::path::Style::posix;
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric   llvm::StringRef path_ref(path.begin(), path.size());
2410b57cec5SDimitry Andric   auto rbegin = llvm::sys::path::rbegin(path_ref, style);
2420b57cec5SDimitry Andric   auto rend = llvm::sys::path::rend(path_ref);
2430b57cec5SDimitry Andric   auto framework = std::find(rbegin, rend, "LLDB.framework");
2440b57cec5SDimitry Andric   if (framework == rend) {
2459dba64beSDimitry Andric     ComputePythonDir(path);
2460b57cec5SDimitry Andric     return;
2470b57cec5SDimitry Andric   }
2480b57cec5SDimitry Andric   path.resize(framework - rend);
2490b57cec5SDimitry Andric   llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
2500b57cec5SDimitry Andric }
2510b57cec5SDimitry Andric 
ComputePythonDir(llvm::SmallVectorImpl<char> & path)2529dba64beSDimitry Andric void ScriptInterpreterPython::ComputePythonDir(
2530b57cec5SDimitry Andric     llvm::SmallVectorImpl<char> &path) {
2540b57cec5SDimitry Andric   // Build the path by backing out of the lib dir, then building with whatever
2550b57cec5SDimitry Andric   // the real python interpreter uses.  (e.g. lib for most, lib64 on RHEL
2569dba64beSDimitry Andric   // x86_64, or bin on Windows).
2579dba64beSDimitry Andric   llvm::sys::path::remove_filename(path);
2589dba64beSDimitry Andric   llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
2590b57cec5SDimitry Andric 
2609dba64beSDimitry Andric #if defined(_WIN32)
261bdd1243dSDimitry Andric   // This will be injected directly through FileSpec.SetDirectory(),
2620b57cec5SDimitry Andric   // so we need to normalize manually.
2630b57cec5SDimitry Andric   std::replace(path.begin(), path.end(), '\\', '/');
2649dba64beSDimitry Andric #endif
2650b57cec5SDimitry Andric }
2660b57cec5SDimitry Andric 
GetPythonDir()2670b57cec5SDimitry Andric FileSpec ScriptInterpreterPython::GetPythonDir() {
2680b57cec5SDimitry Andric   static FileSpec g_spec = []() {
2690b57cec5SDimitry Andric     FileSpec spec = HostInfo::GetShlibDir();
2700b57cec5SDimitry Andric     if (!spec)
2710b57cec5SDimitry Andric       return FileSpec();
2720b57cec5SDimitry Andric     llvm::SmallString<64> path;
2730b57cec5SDimitry Andric     spec.GetPath(path);
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric #if defined(__APPLE__)
2760b57cec5SDimitry Andric     ComputePythonDirForApple(path);
2770b57cec5SDimitry Andric #else
2789dba64beSDimitry Andric     ComputePythonDir(path);
2790b57cec5SDimitry Andric #endif
280bdd1243dSDimitry Andric     spec.SetDirectory(path);
2810b57cec5SDimitry Andric     return spec;
2820b57cec5SDimitry Andric   }();
2830b57cec5SDimitry Andric   return g_spec;
2840b57cec5SDimitry Andric }
2850b57cec5SDimitry Andric 
286349cc55cSDimitry Andric static const char GetInterpreterInfoScript[] = R"(
287349cc55cSDimitry Andric import os
288349cc55cSDimitry Andric import sys
289349cc55cSDimitry Andric 
290349cc55cSDimitry Andric def main(lldb_python_dir, python_exe_relative_path):
291349cc55cSDimitry Andric   info = {
292349cc55cSDimitry Andric     "lldb-pythonpath": lldb_python_dir,
293349cc55cSDimitry Andric     "language": "python",
294349cc55cSDimitry Andric     "prefix": sys.prefix,
295349cc55cSDimitry Andric     "executable": os.path.join(sys.prefix, python_exe_relative_path)
296349cc55cSDimitry Andric   }
297349cc55cSDimitry Andric   return info
298349cc55cSDimitry Andric )";
299349cc55cSDimitry Andric 
300349cc55cSDimitry Andric static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH;
301349cc55cSDimitry Andric 
GetInterpreterInfo()302349cc55cSDimitry Andric StructuredData::DictionarySP ScriptInterpreterPython::GetInterpreterInfo() {
303349cc55cSDimitry Andric   GIL gil;
304349cc55cSDimitry Andric   FileSpec python_dir_spec = GetPythonDir();
305349cc55cSDimitry Andric   if (!python_dir_spec)
306349cc55cSDimitry Andric     return nullptr;
307349cc55cSDimitry Andric   PythonScript get_info(GetInterpreterInfoScript);
308349cc55cSDimitry Andric   auto info_json = unwrapIgnoringErrors(
309349cc55cSDimitry Andric       As<PythonDictionary>(get_info(PythonString(python_dir_spec.GetPath()),
310349cc55cSDimitry Andric                                     PythonString(python_exe_relative_path))));
311349cc55cSDimitry Andric   if (!info_json)
312349cc55cSDimitry Andric     return nullptr;
313349cc55cSDimitry Andric   return info_json.CreateStructuredDictionary();
314349cc55cSDimitry Andric }
315349cc55cSDimitry Andric 
SharedLibraryDirectoryHelper(FileSpec & this_file)316fe6060f1SDimitry Andric void ScriptInterpreterPython::SharedLibraryDirectoryHelper(
317fe6060f1SDimitry Andric     FileSpec &this_file) {
318fe6060f1SDimitry Andric   // When we're loaded from python, this_file will point to the file inside the
319fe6060f1SDimitry Andric   // python package directory. Replace it with the one in the lib directory.
320fe6060f1SDimitry Andric #ifdef _WIN32
321fe6060f1SDimitry Andric   // On windows, we need to manually back out of the python tree, and go into
322fe6060f1SDimitry Andric   // the bin directory. This is pretty much the inverse of what ComputePythonDir
323fe6060f1SDimitry Andric   // does.
32406c3fb27SDimitry Andric   if (this_file.GetFileNameExtension() == ".pyd") {
325fe6060f1SDimitry Andric     this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd
326fe6060f1SDimitry Andric     this_file.RemoveLastPathComponent(); // lldb
327fe6060f1SDimitry Andric     llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
328fe6060f1SDimitry Andric     for (auto it = llvm::sys::path::begin(libdir),
329fe6060f1SDimitry Andric               end = llvm::sys::path::end(libdir);
330fe6060f1SDimitry Andric          it != end; ++it)
331fe6060f1SDimitry Andric       this_file.RemoveLastPathComponent();
332fe6060f1SDimitry Andric     this_file.AppendPathComponent("bin");
333fe6060f1SDimitry Andric     this_file.AppendPathComponent("liblldb.dll");
334fe6060f1SDimitry Andric   }
335fe6060f1SDimitry Andric #else
336fe6060f1SDimitry Andric   // The python file is a symlink, so we can find the real library by resolving
337fe6060f1SDimitry Andric   // it. We can do this unconditionally.
338fe6060f1SDimitry Andric   FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
339fe6060f1SDimitry Andric #endif
340fe6060f1SDimitry Andric }
341fe6060f1SDimitry Andric 
GetPluginDescriptionStatic()342349cc55cSDimitry Andric llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() {
3430b57cec5SDimitry Andric   return "Embedded Python interpreter";
3440b57cec5SDimitry Andric }
3450b57cec5SDimitry Andric 
Initialize()3460b57cec5SDimitry Andric void ScriptInterpreterPython::Initialize() {
3470b57cec5SDimitry Andric   static llvm::once_flag g_once_flag;
3480b57cec5SDimitry Andric   llvm::call_once(g_once_flag, []() {
3490b57cec5SDimitry Andric     PluginManager::RegisterPlugin(GetPluginNameStatic(),
3500b57cec5SDimitry Andric                                   GetPluginDescriptionStatic(),
3510b57cec5SDimitry Andric                                   lldb::eScriptLanguagePython,
3520b57cec5SDimitry Andric                                   ScriptInterpreterPythonImpl::CreateInstance);
35304eeddc0SDimitry Andric     ScriptInterpreterPythonImpl::Initialize();
3540b57cec5SDimitry Andric   });
3550b57cec5SDimitry Andric }
3560b57cec5SDimitry Andric 
Terminate()3570b57cec5SDimitry Andric void ScriptInterpreterPython::Terminate() {}
3580b57cec5SDimitry Andric 
Locker(ScriptInterpreterPythonImpl * py_interpreter,uint16_t on_entry,uint16_t on_leave,FileSP in,FileSP out,FileSP err)3590b57cec5SDimitry Andric ScriptInterpreterPythonImpl::Locker::Locker(
3600b57cec5SDimitry Andric     ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
3619dba64beSDimitry Andric     uint16_t on_leave, FileSP in, FileSP out, FileSP err)
3620b57cec5SDimitry Andric     : ScriptInterpreterLocker(),
3630b57cec5SDimitry Andric       m_teardown_session((on_leave & TearDownSession) == TearDownSession),
3640b57cec5SDimitry Andric       m_python_interpreter(py_interpreter) {
3650b57cec5SDimitry Andric   DoAcquireLock();
3660b57cec5SDimitry Andric   if ((on_entry & InitSession) == InitSession) {
3670b57cec5SDimitry Andric     if (!DoInitSession(on_entry, in, out, err)) {
3680b57cec5SDimitry Andric       // Don't teardown the session if we didn't init it.
3690b57cec5SDimitry Andric       m_teardown_session = false;
3700b57cec5SDimitry Andric     }
3710b57cec5SDimitry Andric   }
3720b57cec5SDimitry Andric }
3730b57cec5SDimitry Andric 
DoAcquireLock()3740b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
37581ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Script);
3760b57cec5SDimitry Andric   m_GILState = PyGILState_Ensure();
3770b57cec5SDimitry Andric   LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked",
3780b57cec5SDimitry Andric             m_GILState == PyGILState_UNLOCKED ? "un" : "");
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric   // we need to save the thread state when we first start the command because
3810b57cec5SDimitry Andric   // we might decide to interrupt it while some action is taking place outside
3820b57cec5SDimitry Andric   // of Python (e.g. printing to screen, waiting for the network, ...) in that
3830b57cec5SDimitry Andric   // case, _PyThreadState_Current will be NULL - and we would be unable to set
3840b57cec5SDimitry Andric   // the asynchronous exception - not a desirable situation
3850b57cec5SDimitry Andric   m_python_interpreter->SetThreadState(PyThreadState_Get());
3860b57cec5SDimitry Andric   m_python_interpreter->IncrementLockCount();
3870b57cec5SDimitry Andric   return true;
3880b57cec5SDimitry Andric }
3890b57cec5SDimitry Andric 
DoInitSession(uint16_t on_entry_flags,FileSP in,FileSP out,FileSP err)3900b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
3919dba64beSDimitry Andric                                                         FileSP in, FileSP out,
3929dba64beSDimitry Andric                                                         FileSP err) {
3930b57cec5SDimitry Andric   if (!m_python_interpreter)
3940b57cec5SDimitry Andric     return false;
3950b57cec5SDimitry Andric   return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
3960b57cec5SDimitry Andric }
3970b57cec5SDimitry Andric 
DoFreeLock()3980b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
39981ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Script);
4000b57cec5SDimitry Andric   LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
4010b57cec5SDimitry Andric             m_GILState == PyGILState_UNLOCKED ? "un" : "");
4020b57cec5SDimitry Andric   PyGILState_Release(m_GILState);
4030b57cec5SDimitry Andric   m_python_interpreter->DecrementLockCount();
4040b57cec5SDimitry Andric   return true;
4050b57cec5SDimitry Andric }
4060b57cec5SDimitry Andric 
DoTearDownSession()4070b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
4080b57cec5SDimitry Andric   if (!m_python_interpreter)
4090b57cec5SDimitry Andric     return false;
4100b57cec5SDimitry Andric   m_python_interpreter->LeaveSession();
4110b57cec5SDimitry Andric   return true;
4120b57cec5SDimitry Andric }
4130b57cec5SDimitry Andric 
~Locker()4140b57cec5SDimitry Andric ScriptInterpreterPythonImpl::Locker::~Locker() {
4150b57cec5SDimitry Andric   if (m_teardown_session)
4160b57cec5SDimitry Andric     DoTearDownSession();
4170b57cec5SDimitry Andric   DoFreeLock();
4180b57cec5SDimitry Andric }
4190b57cec5SDimitry Andric 
ScriptInterpreterPythonImpl(Debugger & debugger)4200b57cec5SDimitry Andric ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger)
4210b57cec5SDimitry Andric     : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
4220b57cec5SDimitry Andric       m_saved_stderr(), m_main_module(),
4230b57cec5SDimitry Andric       m_session_dict(PyInitialValue::Invalid),
4240b57cec5SDimitry Andric       m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(),
4250b57cec5SDimitry Andric       m_run_one_line_str_global(),
42606c3fb27SDimitry Andric       m_dictionary_name(m_debugger.GetInstanceName()),
4279dba64beSDimitry Andric       m_active_io_handler(eIOHandlerNone), m_session_is_active(false),
4285ffd83dbSDimitry Andric       m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
4299dba64beSDimitry Andric       m_command_thread_state(nullptr) {
430fe6060f1SDimitry Andric 
4310b57cec5SDimitry Andric   m_dictionary_name.append("_dict");
4320b57cec5SDimitry Andric   StreamString run_string;
4330b57cec5SDimitry Andric   run_string.Printf("%s = dict()", m_dictionary_name.c_str());
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric   Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock);
4360b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric   run_string.Clear();
4390b57cec5SDimitry Andric   run_string.Printf(
4400b57cec5SDimitry Andric       "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
4410b57cec5SDimitry Andric       m_dictionary_name.c_str());
4420b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric   // Reloading modules requires a different syntax in Python 2 and Python 3.
4450b57cec5SDimitry Andric   // This provides a consistent syntax no matter what version of Python.
4460b57cec5SDimitry Andric   run_string.Clear();
447bdd1243dSDimitry Andric   run_string.Printf("run_one_line (%s, 'from importlib import reload as reload_module')",
4480b57cec5SDimitry Andric                     m_dictionary_name.c_str());
4490b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric   // WARNING: temporary code that loads Cocoa formatters - this should be done
4520b57cec5SDimitry Andric   // on a per-platform basis rather than loading the whole set and letting the
4530b57cec5SDimitry Andric   // individual formatter classes exploit APIs to check whether they can/cannot
4540b57cec5SDimitry Andric   // do their task
4550b57cec5SDimitry Andric   run_string.Clear();
4560b57cec5SDimitry Andric   run_string.Printf(
45706c3fb27SDimitry Andric       "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp')",
4580b57cec5SDimitry Andric       m_dictionary_name.c_str());
4590b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
4600b57cec5SDimitry Andric   run_string.Clear();
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric   run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
4630b57cec5SDimitry Andric                     "lldb.embedded_interpreter import run_python_interpreter; "
4640b57cec5SDimitry Andric                     "from lldb.embedded_interpreter import run_one_line')",
4650b57cec5SDimitry Andric                     m_dictionary_name.c_str());
4660b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
4670b57cec5SDimitry Andric   run_string.Clear();
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
47006c3fb27SDimitry Andric                     "')",
4710b57cec5SDimitry Andric                     m_dictionary_name.c_str(), m_debugger.GetID());
4720b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
4730b57cec5SDimitry Andric }
4740b57cec5SDimitry Andric 
~ScriptInterpreterPythonImpl()4750b57cec5SDimitry Andric ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
4760b57cec5SDimitry Andric   // the session dictionary may hold objects with complex state which means
4770b57cec5SDimitry Andric   // that they may need to be torn down with some level of smarts and that, in
4780b57cec5SDimitry Andric   // turn, requires a valid thread state force Python to procure itself such a
4790b57cec5SDimitry Andric   // thread state, nuke the session dictionary and then release it for others
4800b57cec5SDimitry Andric   // to use and proceed with the rest of the shutdown
4810b57cec5SDimitry Andric   auto gil_state = PyGILState_Ensure();
4820b57cec5SDimitry Andric   m_session_dict.Reset();
4830b57cec5SDimitry Andric   PyGILState_Release(gil_state);
4840b57cec5SDimitry Andric }
4850b57cec5SDimitry Andric 
IOHandlerActivated(IOHandler & io_handler,bool interactive)4860b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler,
4870b57cec5SDimitry Andric                                                      bool interactive) {
4880b57cec5SDimitry Andric   const char *instructions = nullptr;
4890b57cec5SDimitry Andric 
4900b57cec5SDimitry Andric   switch (m_active_io_handler) {
4910b57cec5SDimitry Andric   case eIOHandlerNone:
4920b57cec5SDimitry Andric     break;
4930b57cec5SDimitry Andric   case eIOHandlerBreakpoint:
4940b57cec5SDimitry Andric     instructions = R"(Enter your Python command(s). Type 'DONE' to end.
4950b57cec5SDimitry Andric def function (frame, bp_loc, internal_dict):
4960b57cec5SDimitry Andric     """frame: the lldb.SBFrame for the location at which you stopped
4970b57cec5SDimitry Andric        bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
4980b57cec5SDimitry Andric        internal_dict: an LLDB support object not to be used"""
4990b57cec5SDimitry Andric )";
5000b57cec5SDimitry Andric     break;
5010b57cec5SDimitry Andric   case eIOHandlerWatchpoint:
5020b57cec5SDimitry Andric     instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
5030b57cec5SDimitry Andric     break;
5040b57cec5SDimitry Andric   }
5050b57cec5SDimitry Andric 
5060b57cec5SDimitry Andric   if (instructions) {
5079dba64beSDimitry Andric     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
5080b57cec5SDimitry Andric     if (output_sp && interactive) {
5090b57cec5SDimitry Andric       output_sp->PutCString(instructions);
5100b57cec5SDimitry Andric       output_sp->Flush();
5110b57cec5SDimitry Andric     }
5120b57cec5SDimitry Andric   }
5130b57cec5SDimitry Andric }
5140b57cec5SDimitry Andric 
IOHandlerInputComplete(IOHandler & io_handler,std::string & data)5150b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler,
5160b57cec5SDimitry Andric                                                          std::string &data) {
5170b57cec5SDimitry Andric   io_handler.SetIsDone(true);
5180b57cec5SDimitry Andric   bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
5190b57cec5SDimitry Andric 
5200b57cec5SDimitry Andric   switch (m_active_io_handler) {
5210b57cec5SDimitry Andric   case eIOHandlerNone:
5220b57cec5SDimitry Andric     break;
5230b57cec5SDimitry Andric   case eIOHandlerBreakpoint: {
524fe6060f1SDimitry Andric     std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
525fe6060f1SDimitry Andric         (std::vector<std::reference_wrapper<BreakpointOptions>> *)
526fe6060f1SDimitry Andric             io_handler.GetUserData();
527fe6060f1SDimitry Andric     for (BreakpointOptions &bp_options : *bp_options_vec) {
5280b57cec5SDimitry Andric 
5299dba64beSDimitry Andric       auto data_up = std::make_unique<CommandDataPython>();
5300b57cec5SDimitry Andric       if (!data_up)
5310b57cec5SDimitry Andric         break;
5320b57cec5SDimitry Andric       data_up->user_source.SplitIntoLines(data);
5330b57cec5SDimitry Andric 
534480093f4SDimitry Andric       StructuredData::ObjectSP empty_args_sp;
5350b57cec5SDimitry Andric       if (GenerateBreakpointCommandCallbackData(data_up->user_source,
536480093f4SDimitry Andric                                                 data_up->script_source,
53706c3fb27SDimitry Andric                                                 /*has_extra_args=*/false,
53806c3fb27SDimitry Andric                                                 /*is_callback=*/false)
5390b57cec5SDimitry Andric               .Success()) {
5400b57cec5SDimitry Andric         auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
5410b57cec5SDimitry Andric             std::move(data_up));
542fe6060f1SDimitry Andric         bp_options.SetCallback(
5430b57cec5SDimitry Andric             ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
5440b57cec5SDimitry Andric       } else if (!batch_mode) {
5459dba64beSDimitry Andric         StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
5460b57cec5SDimitry Andric         if (error_sp) {
5470b57cec5SDimitry Andric           error_sp->Printf("Warning: No command attached to breakpoint.\n");
5480b57cec5SDimitry Andric           error_sp->Flush();
5490b57cec5SDimitry Andric         }
5500b57cec5SDimitry Andric       }
5510b57cec5SDimitry Andric     }
5520b57cec5SDimitry Andric     m_active_io_handler = eIOHandlerNone;
5530b57cec5SDimitry Andric   } break;
5540b57cec5SDimitry Andric   case eIOHandlerWatchpoint: {
5550b57cec5SDimitry Andric     WatchpointOptions *wp_options =
5560b57cec5SDimitry Andric         (WatchpointOptions *)io_handler.GetUserData();
5579dba64beSDimitry Andric     auto data_up = std::make_unique<WatchpointOptions::CommandData>();
5580b57cec5SDimitry Andric     data_up->user_source.SplitIntoLines(data);
5590b57cec5SDimitry Andric 
5600b57cec5SDimitry Andric     if (GenerateWatchpointCommandCallbackData(data_up->user_source,
56106c3fb27SDimitry Andric                                               data_up->script_source,
56206c3fb27SDimitry Andric                                               /*is_callback=*/false)) {
5630b57cec5SDimitry Andric       auto baton_sp =
5640b57cec5SDimitry Andric           std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
5650b57cec5SDimitry Andric       wp_options->SetCallback(
5660b57cec5SDimitry Andric           ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
5670b57cec5SDimitry Andric     } else if (!batch_mode) {
5689dba64beSDimitry Andric       StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
5690b57cec5SDimitry Andric       if (error_sp) {
5700b57cec5SDimitry Andric         error_sp->Printf("Warning: No command attached to breakpoint.\n");
5710b57cec5SDimitry Andric         error_sp->Flush();
5720b57cec5SDimitry Andric       }
5730b57cec5SDimitry Andric     }
5740b57cec5SDimitry Andric     m_active_io_handler = eIOHandlerNone;
5750b57cec5SDimitry Andric   } break;
5760b57cec5SDimitry Andric   }
5770b57cec5SDimitry Andric }
5780b57cec5SDimitry Andric 
5790b57cec5SDimitry Andric lldb::ScriptInterpreterSP
CreateInstance(Debugger & debugger)5800b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) {
5810b57cec5SDimitry Andric   return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
5820b57cec5SDimitry Andric }
5830b57cec5SDimitry Andric 
LeaveSession()5840b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::LeaveSession() {
58581ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Script);
5860b57cec5SDimitry Andric   if (log)
5870b57cec5SDimitry Andric     log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
5880b57cec5SDimitry Andric 
5899dba64beSDimitry Andric   // Unset the LLDB global variables.
5909dba64beSDimitry Andric   PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
5919dba64beSDimitry Andric                      "= None; lldb.thread = None; lldb.frame = None");
5929dba64beSDimitry Andric 
5930b57cec5SDimitry Andric   // checking that we have a valid thread state - since we use our own
5940b57cec5SDimitry Andric   // threading and locking in some (rare) cases during cleanup Python may end
5950b57cec5SDimitry Andric   // up believing we have no thread state and PyImport_AddModule will crash if
5960b57cec5SDimitry Andric   // that is the case - since that seems to only happen when destroying the
5970b57cec5SDimitry Andric   // SBDebugger, we can make do without clearing up stdout and stderr
5980b57cec5SDimitry Andric   if (PyThreadState_GetDict()) {
5990b57cec5SDimitry Andric     PythonDictionary &sys_module_dict = GetSysModuleDictionary();
6000b57cec5SDimitry Andric     if (sys_module_dict.IsValid()) {
6010b57cec5SDimitry Andric       if (m_saved_stdin.IsValid()) {
6020b57cec5SDimitry Andric         sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
6030b57cec5SDimitry Andric         m_saved_stdin.Reset();
6040b57cec5SDimitry Andric       }
6050b57cec5SDimitry Andric       if (m_saved_stdout.IsValid()) {
6060b57cec5SDimitry Andric         sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
6070b57cec5SDimitry Andric         m_saved_stdout.Reset();
6080b57cec5SDimitry Andric       }
6090b57cec5SDimitry Andric       if (m_saved_stderr.IsValid()) {
6100b57cec5SDimitry Andric         sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
6110b57cec5SDimitry Andric         m_saved_stderr.Reset();
6120b57cec5SDimitry Andric       }
6130b57cec5SDimitry Andric     }
6140b57cec5SDimitry Andric   }
6150b57cec5SDimitry Andric 
6160b57cec5SDimitry Andric   m_session_is_active = false;
6170b57cec5SDimitry Andric }
6180b57cec5SDimitry Andric 
SetStdHandle(FileSP file_sp,const char * py_name,PythonObject & save_file,const char * mode)6199dba64beSDimitry Andric bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp,
6209dba64beSDimitry Andric                                                const char *py_name,
6219dba64beSDimitry Andric                                                PythonObject &save_file,
6220b57cec5SDimitry Andric                                                const char *mode) {
6239dba64beSDimitry Andric   if (!file_sp || !*file_sp) {
6249dba64beSDimitry Andric     save_file.Reset();
6259dba64beSDimitry Andric     return false;
6269dba64beSDimitry Andric   }
6279dba64beSDimitry Andric   File &file = *file_sp;
6289dba64beSDimitry Andric 
6290b57cec5SDimitry Andric   // Flush the file before giving it to python to avoid interleaved output.
6300b57cec5SDimitry Andric   file.Flush();
6310b57cec5SDimitry Andric 
6320b57cec5SDimitry Andric   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
6330b57cec5SDimitry Andric 
6349dba64beSDimitry Andric   auto new_file = PythonFile::FromFile(file, mode);
6359dba64beSDimitry Andric   if (!new_file) {
6369dba64beSDimitry Andric     llvm::consumeError(new_file.takeError());
6370b57cec5SDimitry Andric     return false;
6380b57cec5SDimitry Andric   }
6390b57cec5SDimitry Andric 
6409dba64beSDimitry Andric   save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
6419dba64beSDimitry Andric 
6429dba64beSDimitry Andric   sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
6439dba64beSDimitry Andric   return true;
6449dba64beSDimitry Andric }
6459dba64beSDimitry Andric 
EnterSession(uint16_t on_entry_flags,FileSP in_sp,FileSP out_sp,FileSP err_sp)6460b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
6479dba64beSDimitry Andric                                                FileSP in_sp, FileSP out_sp,
6489dba64beSDimitry Andric                                                FileSP err_sp) {
6490b57cec5SDimitry Andric   // If we have already entered the session, without having officially 'left'
6500b57cec5SDimitry Andric   // it, then there is no need to 'enter' it again.
65181ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Script);
6520b57cec5SDimitry Andric   if (m_session_is_active) {
6539dba64beSDimitry Andric     LLDB_LOGF(
6549dba64beSDimitry Andric         log,
6550b57cec5SDimitry Andric         "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
6560b57cec5SDimitry Andric         ") session is already active, returning without doing anything",
6570b57cec5SDimitry Andric         on_entry_flags);
6580b57cec5SDimitry Andric     return false;
6590b57cec5SDimitry Andric   }
6600b57cec5SDimitry Andric 
6619dba64beSDimitry Andric   LLDB_LOGF(
6629dba64beSDimitry Andric       log,
6639dba64beSDimitry Andric       "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
6640b57cec5SDimitry Andric       on_entry_flags);
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric   m_session_is_active = true;
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric   StreamString run_string;
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric   if (on_entry_flags & Locker::InitGlobals) {
6710b57cec5SDimitry Andric     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
6720b57cec5SDimitry Andric                       m_dictionary_name.c_str(), m_debugger.GetID());
6730b57cec5SDimitry Andric     run_string.Printf(
6740b57cec5SDimitry Andric         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
6750b57cec5SDimitry Andric         m_debugger.GetID());
6760b57cec5SDimitry Andric     run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
6770b57cec5SDimitry Andric     run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
6780b57cec5SDimitry Andric     run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
6790b57cec5SDimitry Andric     run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
6800b57cec5SDimitry Andric     run_string.PutCString("')");
6810b57cec5SDimitry Andric   } else {
6820b57cec5SDimitry Andric     // If we aren't initing the globals, we should still always set the
6830b57cec5SDimitry Andric     // debugger (since that is always unique.)
6840b57cec5SDimitry Andric     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
6850b57cec5SDimitry Andric                       m_dictionary_name.c_str(), m_debugger.GetID());
6860b57cec5SDimitry Andric     run_string.Printf(
6870b57cec5SDimitry Andric         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
6880b57cec5SDimitry Andric         m_debugger.GetID());
6890b57cec5SDimitry Andric     run_string.PutCString("')");
6900b57cec5SDimitry Andric   }
6910b57cec5SDimitry Andric 
6920b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
6930b57cec5SDimitry Andric   run_string.Clear();
6940b57cec5SDimitry Andric 
6950b57cec5SDimitry Andric   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
6960b57cec5SDimitry Andric   if (sys_module_dict.IsValid()) {
6979dba64beSDimitry Andric     lldb::FileSP top_in_sp;
6989dba64beSDimitry Andric     lldb::StreamFileSP top_out_sp, top_err_sp;
6999dba64beSDimitry Andric     if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
7009dba64beSDimitry Andric       m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
7019dba64beSDimitry Andric                                                  top_err_sp);
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric     if (on_entry_flags & Locker::NoSTDIN) {
7040b57cec5SDimitry Andric       m_saved_stdin.Reset();
7050b57cec5SDimitry Andric     } else {
7069dba64beSDimitry Andric       if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
7079dba64beSDimitry Andric         if (top_in_sp)
7089dba64beSDimitry Andric           SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
7090b57cec5SDimitry Andric       }
7100b57cec5SDimitry Andric     }
7110b57cec5SDimitry Andric 
7129dba64beSDimitry Andric     if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
7139dba64beSDimitry Andric       if (top_out_sp)
7149dba64beSDimitry Andric         SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w");
7150b57cec5SDimitry Andric     }
7160b57cec5SDimitry Andric 
7179dba64beSDimitry Andric     if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
7189dba64beSDimitry Andric       if (top_err_sp)
7199dba64beSDimitry Andric         SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w");
7200b57cec5SDimitry Andric     }
7210b57cec5SDimitry Andric   }
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric   if (PyErr_Occurred())
7240b57cec5SDimitry Andric     PyErr_Clear();
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric   return true;
7270b57cec5SDimitry Andric }
7280b57cec5SDimitry Andric 
GetMainModule()7299dba64beSDimitry Andric PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
7300b57cec5SDimitry Andric   if (!m_main_module.IsValid())
7319dba64beSDimitry Andric     m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__"));
7320b57cec5SDimitry Andric   return m_main_module;
7330b57cec5SDimitry Andric }
7340b57cec5SDimitry Andric 
GetSessionDictionary()7350b57cec5SDimitry Andric PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
7360b57cec5SDimitry Andric   if (m_session_dict.IsValid())
7370b57cec5SDimitry Andric     return m_session_dict;
7380b57cec5SDimitry Andric 
7390b57cec5SDimitry Andric   PythonObject &main_module = GetMainModule();
7400b57cec5SDimitry Andric   if (!main_module.IsValid())
7410b57cec5SDimitry Andric     return m_session_dict;
7420b57cec5SDimitry Andric 
7430b57cec5SDimitry Andric   PythonDictionary main_dict(PyRefType::Borrowed,
7440b57cec5SDimitry Andric                              PyModule_GetDict(main_module.get()));
7450b57cec5SDimitry Andric   if (!main_dict.IsValid())
7460b57cec5SDimitry Andric     return m_session_dict;
7470b57cec5SDimitry Andric 
7489dba64beSDimitry Andric   m_session_dict = unwrapIgnoringErrors(
7499dba64beSDimitry Andric       As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
7500b57cec5SDimitry Andric   return m_session_dict;
7510b57cec5SDimitry Andric }
7520b57cec5SDimitry Andric 
GetSysModuleDictionary()7530b57cec5SDimitry Andric PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
7540b57cec5SDimitry Andric   if (m_sys_module_dict.IsValid())
7550b57cec5SDimitry Andric     return m_sys_module_dict;
7569dba64beSDimitry Andric   PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys"));
7579dba64beSDimitry Andric   m_sys_module_dict = sys_module.GetDictionary();
7580b57cec5SDimitry Andric   return m_sys_module_dict;
7590b57cec5SDimitry Andric }
7600b57cec5SDimitry Andric 
761480093f4SDimitry Andric llvm::Expected<unsigned>
GetMaxPositionalArgumentsForCallable(const llvm::StringRef & callable_name)762480093f4SDimitry Andric ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
763480093f4SDimitry Andric     const llvm::StringRef &callable_name) {
764480093f4SDimitry Andric   if (callable_name.empty()) {
765480093f4SDimitry Andric     return llvm::createStringError(
766480093f4SDimitry Andric         llvm::inconvertibleErrorCode(),
767480093f4SDimitry Andric         "called with empty callable name.");
768480093f4SDimitry Andric   }
769480093f4SDimitry Andric   Locker py_lock(this, Locker::AcquireLock |
770480093f4SDimitry Andric                  Locker::InitSession |
771480093f4SDimitry Andric                  Locker::NoSTDIN);
772480093f4SDimitry Andric   auto dict = PythonModule::MainModule()
773480093f4SDimitry Andric       .ResolveName<PythonDictionary>(m_dictionary_name);
774480093f4SDimitry Andric   auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
775480093f4SDimitry Andric       callable_name, dict);
776480093f4SDimitry Andric   if (!pfunc.IsAllocated()) {
777480093f4SDimitry Andric     return llvm::createStringError(
778480093f4SDimitry Andric         llvm::inconvertibleErrorCode(),
779480093f4SDimitry Andric         "can't find callable: %s", callable_name.str().c_str());
780480093f4SDimitry Andric   }
781480093f4SDimitry Andric   llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
782480093f4SDimitry Andric   if (!arg_info)
783480093f4SDimitry Andric     return arg_info.takeError();
784480093f4SDimitry Andric   return arg_info.get().max_positional_args;
785480093f4SDimitry Andric }
786480093f4SDimitry Andric 
GenerateUniqueName(const char * base_name_wanted,uint32_t & functions_counter,const void * name_token=nullptr)7870b57cec5SDimitry Andric static std::string GenerateUniqueName(const char *base_name_wanted,
7880b57cec5SDimitry Andric                                       uint32_t &functions_counter,
7890b57cec5SDimitry Andric                                       const void *name_token = nullptr) {
7900b57cec5SDimitry Andric   StreamString sstr;
7910b57cec5SDimitry Andric 
7920b57cec5SDimitry Andric   if (!base_name_wanted)
7930b57cec5SDimitry Andric     return std::string();
7940b57cec5SDimitry Andric 
7950b57cec5SDimitry Andric   if (!name_token)
7960b57cec5SDimitry Andric     sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
7970b57cec5SDimitry Andric   else
7980b57cec5SDimitry Andric     sstr.Printf("%s_%p", base_name_wanted, name_token);
7990b57cec5SDimitry Andric 
8005ffd83dbSDimitry Andric   return std::string(sstr.GetString());
8010b57cec5SDimitry Andric }
8020b57cec5SDimitry Andric 
GetEmbeddedInterpreterModuleObjects()8030b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
8040b57cec5SDimitry Andric   if (m_run_one_line_function.IsValid())
8050b57cec5SDimitry Andric     return true;
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric   PythonObject module(PyRefType::Borrowed,
8080b57cec5SDimitry Andric                       PyImport_AddModule("lldb.embedded_interpreter"));
8090b57cec5SDimitry Andric   if (!module.IsValid())
8100b57cec5SDimitry Andric     return false;
8110b57cec5SDimitry Andric 
8120b57cec5SDimitry Andric   PythonDictionary module_dict(PyRefType::Borrowed,
8130b57cec5SDimitry Andric                                PyModule_GetDict(module.get()));
8140b57cec5SDimitry Andric   if (!module_dict.IsValid())
8150b57cec5SDimitry Andric     return false;
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric   m_run_one_line_function =
8180b57cec5SDimitry Andric       module_dict.GetItemForKey(PythonString("run_one_line"));
8190b57cec5SDimitry Andric   m_run_one_line_str_global =
8200b57cec5SDimitry Andric       module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
8210b57cec5SDimitry Andric   return m_run_one_line_function.IsValid();
8220b57cec5SDimitry Andric }
8230b57cec5SDimitry Andric 
ExecuteOneLine(llvm::StringRef command,CommandReturnObject * result,const ExecuteScriptOptions & options)8240b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ExecuteOneLine(
8250b57cec5SDimitry Andric     llvm::StringRef command, CommandReturnObject *result,
8260b57cec5SDimitry Andric     const ExecuteScriptOptions &options) {
8270b57cec5SDimitry Andric   std::string command_str = command.str();
8280b57cec5SDimitry Andric 
8290b57cec5SDimitry Andric   if (!m_valid_session)
8300b57cec5SDimitry Andric     return false;
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric   if (!command.empty()) {
8330b57cec5SDimitry Andric     // We want to call run_one_line, passing in the dictionary and the command
8340b57cec5SDimitry Andric     // string.  We cannot do this through PyRun_SimpleString here because the
8350b57cec5SDimitry Andric     // command string may contain escaped characters, and putting it inside
8360b57cec5SDimitry Andric     // another string to pass to PyRun_SimpleString messes up the escaping.  So
8370b57cec5SDimitry Andric     // we use the following more complicated method to pass the command string
8380b57cec5SDimitry Andric     // directly down to Python.
8395ffd83dbSDimitry Andric     llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
8405ffd83dbSDimitry Andric         io_redirect_or_error = ScriptInterpreterIORedirect::Create(
8415ffd83dbSDimitry Andric             options.GetEnableIO(), m_debugger, result);
8425ffd83dbSDimitry Andric     if (!io_redirect_or_error) {
8435ffd83dbSDimitry Andric       if (result)
8445ffd83dbSDimitry Andric         result->AppendErrorWithFormatv(
8455ffd83dbSDimitry Andric             "failed to redirect I/O: {0}\n",
8465ffd83dbSDimitry Andric             llvm::fmt_consume(io_redirect_or_error.takeError()));
8475ffd83dbSDimitry Andric       else
8485ffd83dbSDimitry Andric         llvm::consumeError(io_redirect_or_error.takeError());
8499dba64beSDimitry Andric       return false;
8509dba64beSDimitry Andric     }
8515ffd83dbSDimitry Andric 
8525ffd83dbSDimitry Andric     ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
8530b57cec5SDimitry Andric 
8540b57cec5SDimitry Andric     bool success = false;
8550b57cec5SDimitry Andric     {
8560b57cec5SDimitry Andric       // WARNING!  It's imperative that this RAII scope be as tight as
8570b57cec5SDimitry Andric       // possible. In particular, the scope must end *before* we try to join
8580b57cec5SDimitry Andric       // the read thread.  The reason for this is that a pre-requisite for
8590b57cec5SDimitry Andric       // joining the read thread is that we close the write handle (to break
8600b57cec5SDimitry Andric       // the pipe and cause it to wake up and exit).  But acquiring the GIL as
8610b57cec5SDimitry Andric       // below will redirect Python's stdio to use this same handle.  If we
8620b57cec5SDimitry Andric       // close the handle while Python is still using it, bad things will
8630b57cec5SDimitry Andric       // happen.
8640b57cec5SDimitry Andric       Locker locker(
8650b57cec5SDimitry Andric           this,
8660b57cec5SDimitry Andric           Locker::AcquireLock | Locker::InitSession |
8670b57cec5SDimitry Andric               (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
8680b57cec5SDimitry Andric               ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
8695ffd83dbSDimitry Andric           Locker::FreeAcquiredLock | Locker::TearDownSession,
8705ffd83dbSDimitry Andric           io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
8715ffd83dbSDimitry Andric           io_redirect.GetErrorFile());
8720b57cec5SDimitry Andric 
8730b57cec5SDimitry Andric       // Find the correct script interpreter dictionary in the main module.
8740b57cec5SDimitry Andric       PythonDictionary &session_dict = GetSessionDictionary();
8750b57cec5SDimitry Andric       if (session_dict.IsValid()) {
8760b57cec5SDimitry Andric         if (GetEmbeddedInterpreterModuleObjects()) {
8770b57cec5SDimitry Andric           if (PyCallable_Check(m_run_one_line_function.get())) {
8780b57cec5SDimitry Andric             PythonObject pargs(
8790b57cec5SDimitry Andric                 PyRefType::Owned,
8800b57cec5SDimitry Andric                 Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
8810b57cec5SDimitry Andric             if (pargs.IsValid()) {
8820b57cec5SDimitry Andric               PythonObject return_value(
8830b57cec5SDimitry Andric                   PyRefType::Owned,
8840b57cec5SDimitry Andric                   PyObject_CallObject(m_run_one_line_function.get(),
8850b57cec5SDimitry Andric                                       pargs.get()));
8860b57cec5SDimitry Andric               if (return_value.IsValid())
8870b57cec5SDimitry Andric                 success = true;
8880b57cec5SDimitry Andric               else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
8890b57cec5SDimitry Andric                 PyErr_Print();
8900b57cec5SDimitry Andric                 PyErr_Clear();
8910b57cec5SDimitry Andric               }
8920b57cec5SDimitry Andric             }
8930b57cec5SDimitry Andric           }
8940b57cec5SDimitry Andric         }
8950b57cec5SDimitry Andric       }
8960b57cec5SDimitry Andric 
8975ffd83dbSDimitry Andric       io_redirect.Flush();
8980b57cec5SDimitry Andric     }
8990b57cec5SDimitry Andric 
9000b57cec5SDimitry Andric     if (success)
9010b57cec5SDimitry Andric       return true;
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric     // The one-liner failed.  Append the error message.
9040b57cec5SDimitry Andric     if (result) {
9050b57cec5SDimitry Andric       result->AppendErrorWithFormat(
9060b57cec5SDimitry Andric           "python failed attempting to evaluate '%s'\n", command_str.c_str());
9070b57cec5SDimitry Andric     }
9080b57cec5SDimitry Andric     return false;
9090b57cec5SDimitry Andric   }
9100b57cec5SDimitry Andric 
9110b57cec5SDimitry Andric   if (result)
9120b57cec5SDimitry Andric     result->AppendError("empty command passed to python\n");
9130b57cec5SDimitry Andric   return false;
9140b57cec5SDimitry Andric }
9150b57cec5SDimitry Andric 
ExecuteInterpreterLoop()9160b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
917e8d8bef9SDimitry Andric   LLDB_SCOPED_TIMER();
9180b57cec5SDimitry Andric 
9190b57cec5SDimitry Andric   Debugger &debugger = m_debugger;
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric   // At the moment, the only time the debugger does not have an input file
9220b57cec5SDimitry Andric   // handle is when this is called directly from Python, in which case it is
9230b57cec5SDimitry Andric   // both dangerous and unnecessary (not to mention confusing) to try to embed
9240b57cec5SDimitry Andric   // a running interpreter loop inside the already running Python interpreter
9250b57cec5SDimitry Andric   // loop, so we won't do it.
9260b57cec5SDimitry Andric 
9279dba64beSDimitry Andric   if (!debugger.GetInputFile().IsValid())
9280b57cec5SDimitry Andric     return;
9290b57cec5SDimitry Andric 
9300b57cec5SDimitry Andric   IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
9310b57cec5SDimitry Andric   if (io_handler_sp) {
9325ffd83dbSDimitry Andric     debugger.RunIOHandlerAsync(io_handler_sp);
9330b57cec5SDimitry Andric   }
9340b57cec5SDimitry Andric }
9350b57cec5SDimitry Andric 
Interrupt()9360b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Interrupt() {
93704eeddc0SDimitry Andric #if LLDB_USE_PYTHON_SET_INTERRUPT
93804eeddc0SDimitry Andric   // If the interpreter isn't evaluating any Python at the moment then return
93904eeddc0SDimitry Andric   // false to signal that this function didn't handle the interrupt and the
94004eeddc0SDimitry Andric   // next component should try handling it.
94104eeddc0SDimitry Andric   if (!IsExecutingPython())
94204eeddc0SDimitry Andric     return false;
94304eeddc0SDimitry Andric 
94404eeddc0SDimitry Andric   // Tell Python that it should pretend to have received a SIGINT.
94504eeddc0SDimitry Andric   PyErr_SetInterrupt();
94604eeddc0SDimitry Andric   // PyErr_SetInterrupt has no way to return an error so we can only pretend the
94704eeddc0SDimitry Andric   // signal got successfully handled and return true.
94804eeddc0SDimitry Andric   // Python 3.10 introduces PyErr_SetInterruptEx that could return an error, but
94904eeddc0SDimitry Andric   // the error handling is limited to checking the arguments which would be
95004eeddc0SDimitry Andric   // just our (hardcoded) input signal code SIGINT, so that's not useful at all.
95104eeddc0SDimitry Andric   return true;
95204eeddc0SDimitry Andric #else
95381ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Script);
9540b57cec5SDimitry Andric 
9550b57cec5SDimitry Andric   if (IsExecutingPython()) {
9560b57cec5SDimitry Andric     PyThreadState *state = PyThreadState_GET();
9570b57cec5SDimitry Andric     if (!state)
9580b57cec5SDimitry Andric       state = GetThreadState();
9590b57cec5SDimitry Andric     if (state) {
9600b57cec5SDimitry Andric       long tid = state->thread_id;
9610b57cec5SDimitry Andric       PyThreadState_Swap(state);
9620b57cec5SDimitry Andric       int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
9639dba64beSDimitry Andric       LLDB_LOGF(log,
9649dba64beSDimitry Andric                 "ScriptInterpreterPythonImpl::Interrupt() sending "
9650b57cec5SDimitry Andric                 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
9660b57cec5SDimitry Andric                 tid, num_threads);
9670b57cec5SDimitry Andric       return true;
9680b57cec5SDimitry Andric     }
9690b57cec5SDimitry Andric   }
9709dba64beSDimitry Andric   LLDB_LOGF(log,
9710b57cec5SDimitry Andric             "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
9720b57cec5SDimitry Andric             "can't interrupt");
9730b57cec5SDimitry Andric   return false;
97404eeddc0SDimitry Andric #endif
9750b57cec5SDimitry Andric }
9769dba64beSDimitry Andric 
ExecuteOneLineWithReturn(llvm::StringRef in_string,ScriptInterpreter::ScriptReturnType return_type,void * ret_value,const ExecuteScriptOptions & options)9770b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
9780b57cec5SDimitry Andric     llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
9790b57cec5SDimitry Andric     void *ret_value, const ExecuteScriptOptions &options) {
9800b57cec5SDimitry Andric 
981fe6060f1SDimitry Andric   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
982fe6060f1SDimitry Andric       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
983fe6060f1SDimitry Andric           options.GetEnableIO(), m_debugger, /*result=*/nullptr);
984fe6060f1SDimitry Andric 
985fe6060f1SDimitry Andric   if (!io_redirect_or_error) {
986fe6060f1SDimitry Andric     llvm::consumeError(io_redirect_or_error.takeError());
987fe6060f1SDimitry Andric     return false;
988fe6060f1SDimitry Andric   }
989fe6060f1SDimitry Andric 
990fe6060f1SDimitry Andric   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
991fe6060f1SDimitry Andric 
9920b57cec5SDimitry Andric   Locker locker(this,
9930b57cec5SDimitry Andric                 Locker::AcquireLock | Locker::InitSession |
9940b57cec5SDimitry Andric                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
9950b57cec5SDimitry Andric                     Locker::NoSTDIN,
996fe6060f1SDimitry Andric                 Locker::FreeAcquiredLock | Locker::TearDownSession,
997fe6060f1SDimitry Andric                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
998fe6060f1SDimitry Andric                 io_redirect.GetErrorFile());
9990b57cec5SDimitry Andric 
10009dba64beSDimitry Andric   PythonModule &main_module = GetMainModule();
10019dba64beSDimitry Andric   PythonDictionary globals = main_module.GetDictionary();
10020b57cec5SDimitry Andric 
10030b57cec5SDimitry Andric   PythonDictionary locals = GetSessionDictionary();
10049dba64beSDimitry Andric   if (!locals.IsValid())
10059dba64beSDimitry Andric     locals = unwrapIgnoringErrors(
10069dba64beSDimitry Andric         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
10070b57cec5SDimitry Andric   if (!locals.IsValid())
10080b57cec5SDimitry Andric     locals = globals;
10090b57cec5SDimitry Andric 
10109dba64beSDimitry Andric   Expected<PythonObject> maybe_py_return =
10119dba64beSDimitry Andric       runStringOneLine(in_string, globals, locals);
10120b57cec5SDimitry Andric 
10139dba64beSDimitry Andric   if (!maybe_py_return) {
10149dba64beSDimitry Andric     llvm::handleAllErrors(
10159dba64beSDimitry Andric         maybe_py_return.takeError(),
10169dba64beSDimitry Andric         [&](PythonException &E) {
10179dba64beSDimitry Andric           E.Restore();
10189dba64beSDimitry Andric           if (options.GetMaskoutErrors()) {
10199dba64beSDimitry Andric             if (E.Matches(PyExc_SyntaxError)) {
10209dba64beSDimitry Andric               PyErr_Print();
10210b57cec5SDimitry Andric             }
10229dba64beSDimitry Andric             PyErr_Clear();
10239dba64beSDimitry Andric           }
10249dba64beSDimitry Andric         },
10259dba64beSDimitry Andric         [](const llvm::ErrorInfoBase &E) {});
10269dba64beSDimitry Andric     return false;
10270b57cec5SDimitry Andric   }
10280b57cec5SDimitry Andric 
10299dba64beSDimitry Andric   PythonObject py_return = std::move(maybe_py_return.get());
10309dba64beSDimitry Andric   assert(py_return.IsValid());
10319dba64beSDimitry Andric 
10320b57cec5SDimitry Andric   switch (return_type) {
10330b57cec5SDimitry Andric   case eScriptReturnTypeCharPtr: // "char *"
10340b57cec5SDimitry Andric   {
10350b57cec5SDimitry Andric     const char format[3] = "s#";
10369dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
10370b57cec5SDimitry Andric   }
10380b57cec5SDimitry Andric   case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
10390b57cec5SDimitry Andric                                        // Py_None
10400b57cec5SDimitry Andric   {
10410b57cec5SDimitry Andric     const char format[3] = "z";
10429dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
10430b57cec5SDimitry Andric   }
10440b57cec5SDimitry Andric   case eScriptReturnTypeBool: {
10450b57cec5SDimitry Andric     const char format[2] = "b";
10469dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
10470b57cec5SDimitry Andric   }
10480b57cec5SDimitry Andric   case eScriptReturnTypeShortInt: {
10490b57cec5SDimitry Andric     const char format[2] = "h";
10509dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (short *)ret_value);
10510b57cec5SDimitry Andric   }
10520b57cec5SDimitry Andric   case eScriptReturnTypeShortIntUnsigned: {
10530b57cec5SDimitry Andric     const char format[2] = "H";
10549dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
10550b57cec5SDimitry Andric   }
10560b57cec5SDimitry Andric   case eScriptReturnTypeInt: {
10570b57cec5SDimitry Andric     const char format[2] = "i";
10589dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (int *)ret_value);
10590b57cec5SDimitry Andric   }
10600b57cec5SDimitry Andric   case eScriptReturnTypeIntUnsigned: {
10610b57cec5SDimitry Andric     const char format[2] = "I";
10629dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
10630b57cec5SDimitry Andric   }
10640b57cec5SDimitry Andric   case eScriptReturnTypeLongInt: {
10650b57cec5SDimitry Andric     const char format[2] = "l";
10669dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (long *)ret_value);
10670b57cec5SDimitry Andric   }
10680b57cec5SDimitry Andric   case eScriptReturnTypeLongIntUnsigned: {
10690b57cec5SDimitry Andric     const char format[2] = "k";
10709dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
10710b57cec5SDimitry Andric   }
10720b57cec5SDimitry Andric   case eScriptReturnTypeLongLong: {
10730b57cec5SDimitry Andric     const char format[2] = "L";
10749dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
10750b57cec5SDimitry Andric   }
10760b57cec5SDimitry Andric   case eScriptReturnTypeLongLongUnsigned: {
10770b57cec5SDimitry Andric     const char format[2] = "K";
10789dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format,
10799dba64beSDimitry Andric                        (unsigned long long *)ret_value);
10800b57cec5SDimitry Andric   }
10810b57cec5SDimitry Andric   case eScriptReturnTypeFloat: {
10820b57cec5SDimitry Andric     const char format[2] = "f";
10839dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (float *)ret_value);
10840b57cec5SDimitry Andric   }
10850b57cec5SDimitry Andric   case eScriptReturnTypeDouble: {
10860b57cec5SDimitry Andric     const char format[2] = "d";
10879dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (double *)ret_value);
10880b57cec5SDimitry Andric   }
10890b57cec5SDimitry Andric   case eScriptReturnTypeChar: {
10900b57cec5SDimitry Andric     const char format[2] = "c";
10919dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (char *)ret_value);
10920b57cec5SDimitry Andric   }
10930b57cec5SDimitry Andric   case eScriptReturnTypeOpaqueObject: {
10949dba64beSDimitry Andric     *((PyObject **)ret_value) = py_return.release();
10959dba64beSDimitry Andric     return true;
10960b57cec5SDimitry Andric   }
10970b57cec5SDimitry Andric   }
1098480093f4SDimitry Andric   llvm_unreachable("Fully covered switch!");
10990b57cec5SDimitry Andric }
11000b57cec5SDimitry Andric 
ExecuteMultipleLines(const char * in_string,const ExecuteScriptOptions & options)11010b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
11020b57cec5SDimitry Andric     const char *in_string, const ExecuteScriptOptions &options) {
11039dba64beSDimitry Andric 
11049dba64beSDimitry Andric   if (in_string == nullptr)
11059dba64beSDimitry Andric     return Status();
11060b57cec5SDimitry Andric 
1107fe6060f1SDimitry Andric   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1108fe6060f1SDimitry Andric       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1109fe6060f1SDimitry Andric           options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1110fe6060f1SDimitry Andric 
1111fe6060f1SDimitry Andric   if (!io_redirect_or_error)
1112fe6060f1SDimitry Andric     return Status(io_redirect_or_error.takeError());
1113fe6060f1SDimitry Andric 
1114fe6060f1SDimitry Andric   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1115fe6060f1SDimitry Andric 
11160b57cec5SDimitry Andric   Locker locker(this,
11170b57cec5SDimitry Andric                 Locker::AcquireLock | Locker::InitSession |
11180b57cec5SDimitry Andric                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
11190b57cec5SDimitry Andric                     Locker::NoSTDIN,
1120fe6060f1SDimitry Andric                 Locker::FreeAcquiredLock | Locker::TearDownSession,
1121fe6060f1SDimitry Andric                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1122fe6060f1SDimitry Andric                 io_redirect.GetErrorFile());
11230b57cec5SDimitry Andric 
11249dba64beSDimitry Andric   PythonModule &main_module = GetMainModule();
11259dba64beSDimitry Andric   PythonDictionary globals = main_module.GetDictionary();
11260b57cec5SDimitry Andric 
11270b57cec5SDimitry Andric   PythonDictionary locals = GetSessionDictionary();
11280b57cec5SDimitry Andric   if (!locals.IsValid())
11299dba64beSDimitry Andric     locals = unwrapIgnoringErrors(
11309dba64beSDimitry Andric         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
11310b57cec5SDimitry Andric   if (!locals.IsValid())
11320b57cec5SDimitry Andric     locals = globals;
11330b57cec5SDimitry Andric 
11349dba64beSDimitry Andric   Expected<PythonObject> return_value =
11359dba64beSDimitry Andric       runStringMultiLine(in_string, globals, locals);
11360b57cec5SDimitry Andric 
11379dba64beSDimitry Andric   if (!return_value) {
11389dba64beSDimitry Andric     llvm::Error error =
11399dba64beSDimitry Andric         llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
11409dba64beSDimitry Andric           llvm::Error error = llvm::createStringError(
11419dba64beSDimitry Andric               llvm::inconvertibleErrorCode(), E.ReadBacktrace());
11429dba64beSDimitry Andric           if (!options.GetMaskoutErrors())
11439dba64beSDimitry Andric             E.Restore();
11440b57cec5SDimitry Andric           return error;
11459dba64beSDimitry Andric         });
11469dba64beSDimitry Andric     return Status(std::move(error));
11479dba64beSDimitry Andric   }
11489dba64beSDimitry Andric 
11499dba64beSDimitry Andric   return Status();
11500b57cec5SDimitry Andric }
11510b57cec5SDimitry Andric 
CollectDataForBreakpointCommandCallback(std::vector<std::reference_wrapper<BreakpointOptions>> & bp_options_vec,CommandReturnObject & result)11520b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1153fe6060f1SDimitry Andric     std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
11540b57cec5SDimitry Andric     CommandReturnObject &result) {
11550b57cec5SDimitry Andric   m_active_io_handler = eIOHandlerBreakpoint;
11560b57cec5SDimitry Andric   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1157480093f4SDimitry Andric       "    ", *this, &bp_options_vec);
11580b57cec5SDimitry Andric }
11590b57cec5SDimitry Andric 
CollectDataForWatchpointCommandCallback(WatchpointOptions * wp_options,CommandReturnObject & result)11600b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
11610b57cec5SDimitry Andric     WatchpointOptions *wp_options, CommandReturnObject &result) {
11620b57cec5SDimitry Andric   m_active_io_handler = eIOHandlerWatchpoint;
11630b57cec5SDimitry Andric   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1164480093f4SDimitry Andric       "    ", *this, wp_options);
11650b57cec5SDimitry Andric }
11660b57cec5SDimitry Andric 
SetBreakpointCommandCallbackFunction(BreakpointOptions & bp_options,const char * function_name,StructuredData::ObjectSP extra_args_sp)1167480093f4SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1168fe6060f1SDimitry Andric     BreakpointOptions &bp_options, const char *function_name,
1169480093f4SDimitry Andric     StructuredData::ObjectSP extra_args_sp) {
1170480093f4SDimitry Andric   Status error;
11710b57cec5SDimitry Andric   // For now just cons up a oneliner that calls the provided function.
117206c3fb27SDimitry Andric   std::string function_signature = function_name;
1173480093f4SDimitry Andric 
1174480093f4SDimitry Andric   llvm::Expected<unsigned> maybe_args =
1175480093f4SDimitry Andric       GetMaxPositionalArgumentsForCallable(function_name);
1176480093f4SDimitry Andric   if (!maybe_args) {
1177480093f4SDimitry Andric     error.SetErrorStringWithFormat(
1178480093f4SDimitry Andric         "could not get num args: %s",
1179480093f4SDimitry Andric         llvm::toString(maybe_args.takeError()).c_str());
1180480093f4SDimitry Andric     return error;
1181480093f4SDimitry Andric   }
1182480093f4SDimitry Andric   size_t max_args = *maybe_args;
1183480093f4SDimitry Andric 
1184480093f4SDimitry Andric   bool uses_extra_args = false;
1185480093f4SDimitry Andric   if (max_args >= 4) {
1186480093f4SDimitry Andric     uses_extra_args = true;
118706c3fb27SDimitry Andric     function_signature += "(frame, bp_loc, extra_args, internal_dict)";
1188480093f4SDimitry Andric   } else if (max_args >= 3) {
1189480093f4SDimitry Andric     if (extra_args_sp) {
1190480093f4SDimitry Andric       error.SetErrorString("cannot pass extra_args to a three argument callback"
1191480093f4SDimitry Andric                           );
1192480093f4SDimitry Andric       return error;
1193480093f4SDimitry Andric     }
1194480093f4SDimitry Andric     uses_extra_args = false;
119506c3fb27SDimitry Andric     function_signature += "(frame, bp_loc, internal_dict)";
1196480093f4SDimitry Andric   } else {
1197480093f4SDimitry Andric     error.SetErrorStringWithFormat("expected 3 or 4 argument "
1198480093f4SDimitry Andric                                    "function, %s can only take %zu",
1199480093f4SDimitry Andric                                    function_name, max_args);
1200480093f4SDimitry Andric     return error;
1201480093f4SDimitry Andric   }
1202480093f4SDimitry Andric 
120306c3fb27SDimitry Andric   SetBreakpointCommandCallback(bp_options, function_signature.c_str(),
120406c3fb27SDimitry Andric                                extra_args_sp, uses_extra_args,
120506c3fb27SDimitry Andric                                /*is_callback=*/true);
1206480093f4SDimitry Andric   return error;
12070b57cec5SDimitry Andric }
12080b57cec5SDimitry Andric 
SetBreakpointCommandCallback(BreakpointOptions & bp_options,std::unique_ptr<BreakpointOptions::CommandData> & cmd_data_up)12090b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1210fe6060f1SDimitry Andric     BreakpointOptions &bp_options,
12110b57cec5SDimitry Andric     std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
12120b57cec5SDimitry Andric   Status error;
12130b57cec5SDimitry Andric   error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1214480093f4SDimitry Andric                                                 cmd_data_up->script_source,
121506c3fb27SDimitry Andric                                                 /*has_extra_args=*/false,
121606c3fb27SDimitry Andric                                                 /*is_callback=*/false);
12170b57cec5SDimitry Andric   if (error.Fail()) {
12180b57cec5SDimitry Andric     return error;
12190b57cec5SDimitry Andric   }
12200b57cec5SDimitry Andric   auto baton_sp =
12210b57cec5SDimitry Andric       std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1222fe6060f1SDimitry Andric   bp_options.SetCallback(
12230b57cec5SDimitry Andric       ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
12240b57cec5SDimitry Andric   return error;
12250b57cec5SDimitry Andric }
12260b57cec5SDimitry Andric 
SetBreakpointCommandCallback(BreakpointOptions & bp_options,const char * command_body_text,bool is_callback)12270b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
122806c3fb27SDimitry Andric     BreakpointOptions &bp_options, const char *command_body_text,
122906c3fb27SDimitry Andric     bool is_callback) {
123006c3fb27SDimitry Andric   return SetBreakpointCommandCallback(bp_options, command_body_text, {},
123106c3fb27SDimitry Andric                                       /*uses_extra_args=*/false, is_callback);
1232480093f4SDimitry Andric }
12330b57cec5SDimitry Andric 
1234480093f4SDimitry Andric // Set a Python one-liner as the callback for the breakpoint.
SetBreakpointCommandCallback(BreakpointOptions & bp_options,const char * command_body_text,StructuredData::ObjectSP extra_args_sp,bool uses_extra_args,bool is_callback)1235480093f4SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1236fe6060f1SDimitry Andric     BreakpointOptions &bp_options, const char *command_body_text,
123706c3fb27SDimitry Andric     StructuredData::ObjectSP extra_args_sp, bool uses_extra_args,
123806c3fb27SDimitry Andric     bool is_callback) {
1239480093f4SDimitry Andric   auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
12400b57cec5SDimitry Andric   // Split the command_body_text into lines, and pass that to
12410b57cec5SDimitry Andric   // GenerateBreakpointCommandCallbackData.  That will wrap the body in an
12420b57cec5SDimitry Andric   // auto-generated function, and return the function name in script_source.
12430b57cec5SDimitry Andric   // That is what the callback will actually invoke.
12440b57cec5SDimitry Andric 
12450b57cec5SDimitry Andric   data_up->user_source.SplitIntoLines(command_body_text);
124606c3fb27SDimitry Andric   Status error = GenerateBreakpointCommandCallbackData(
124706c3fb27SDimitry Andric       data_up->user_source, data_up->script_source, uses_extra_args,
124806c3fb27SDimitry Andric       is_callback);
12490b57cec5SDimitry Andric   if (error.Success()) {
12500b57cec5SDimitry Andric     auto baton_sp =
12510b57cec5SDimitry Andric         std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1252fe6060f1SDimitry Andric     bp_options.SetCallback(
12530b57cec5SDimitry Andric         ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
12540b57cec5SDimitry Andric     return error;
12555ffd83dbSDimitry Andric   }
12560b57cec5SDimitry Andric   return error;
12570b57cec5SDimitry Andric }
12580b57cec5SDimitry Andric 
12590b57cec5SDimitry Andric // Set a Python one-liner as the callback for the watchpoint.
SetWatchpointCommandCallback(WatchpointOptions * wp_options,const char * user_input,bool is_callback)12600b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
126106c3fb27SDimitry Andric     WatchpointOptions *wp_options, const char *user_input,
126206c3fb27SDimitry Andric     bool is_callback) {
12639dba64beSDimitry Andric   auto data_up = std::make_unique<WatchpointOptions::CommandData>();
12640b57cec5SDimitry Andric 
12650b57cec5SDimitry Andric   // It's necessary to set both user_source and script_source to the oneliner.
12660b57cec5SDimitry Andric   // The former is used to generate callback description (as in watchpoint
12670b57cec5SDimitry Andric   // command list) while the latter is used for Python to interpret during the
12680b57cec5SDimitry Andric   // actual callback.
12690b57cec5SDimitry Andric 
127006c3fb27SDimitry Andric   data_up->user_source.AppendString(user_input);
127106c3fb27SDimitry Andric   data_up->script_source.assign(user_input);
12720b57cec5SDimitry Andric 
127306c3fb27SDimitry Andric   if (GenerateWatchpointCommandCallbackData(
127406c3fb27SDimitry Andric           data_up->user_source, data_up->script_source, is_callback)) {
12750b57cec5SDimitry Andric     auto baton_sp =
12760b57cec5SDimitry Andric         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
12770b57cec5SDimitry Andric     wp_options->SetCallback(
12780b57cec5SDimitry Andric         ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
12790b57cec5SDimitry Andric   }
12800b57cec5SDimitry Andric }
12810b57cec5SDimitry Andric 
ExportFunctionDefinitionToInterpreter(StringList & function_def)12820b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
12830b57cec5SDimitry Andric     StringList &function_def) {
12840b57cec5SDimitry Andric   // Convert StringList to one long, newline delimited, const char *.
12850b57cec5SDimitry Andric   std::string function_def_string(function_def.CopyList());
12860b57cec5SDimitry Andric 
12870b57cec5SDimitry Andric   Status error = ExecuteMultipleLines(
12880b57cec5SDimitry Andric       function_def_string.c_str(),
1289fe6060f1SDimitry Andric       ExecuteScriptOptions().SetEnableIO(false));
12900b57cec5SDimitry Andric   return error;
12910b57cec5SDimitry Andric }
12920b57cec5SDimitry Andric 
GenerateFunction(const char * signature,const StringList & input,bool is_callback)12930b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature,
129406c3fb27SDimitry Andric                                                      const StringList &input,
129506c3fb27SDimitry Andric                                                      bool is_callback) {
12960b57cec5SDimitry Andric   Status error;
12970b57cec5SDimitry Andric   int num_lines = input.GetSize();
12980b57cec5SDimitry Andric   if (num_lines == 0) {
12990b57cec5SDimitry Andric     error.SetErrorString("No input data.");
13000b57cec5SDimitry Andric     return error;
13010b57cec5SDimitry Andric   }
13020b57cec5SDimitry Andric 
13030b57cec5SDimitry Andric   if (!signature || *signature == 0) {
13040b57cec5SDimitry Andric     error.SetErrorString("No output function name.");
13050b57cec5SDimitry Andric     return error;
13060b57cec5SDimitry Andric   }
13070b57cec5SDimitry Andric 
13080b57cec5SDimitry Andric   StreamString sstr;
13090b57cec5SDimitry Andric   StringList auto_generated_function;
13100b57cec5SDimitry Andric   auto_generated_function.AppendString(signature);
13110b57cec5SDimitry Andric   auto_generated_function.AppendString(
13120b57cec5SDimitry Andric       "    global_dict = globals()"); // Grab the global dictionary
13130b57cec5SDimitry Andric   auto_generated_function.AppendString(
13140b57cec5SDimitry Andric       "    new_keys = internal_dict.keys()"); // Make a list of keys in the
13150b57cec5SDimitry Andric                                               // session dict
13160b57cec5SDimitry Andric   auto_generated_function.AppendString(
13170b57cec5SDimitry Andric       "    old_keys = global_dict.keys()"); // Save list of keys in global dict
13180b57cec5SDimitry Andric   auto_generated_function.AppendString(
13190b57cec5SDimitry Andric       "    global_dict.update(internal_dict)"); // Add the session dictionary
132006c3fb27SDimitry Andric                                                 // to the global dictionary.
13210b57cec5SDimitry Andric 
132206c3fb27SDimitry Andric   if (is_callback) {
132306c3fb27SDimitry Andric     // If the user input is a callback to a python function, make sure the input
132406c3fb27SDimitry Andric     // is only 1 line, otherwise appending the user input would break the
132506c3fb27SDimitry Andric     // generated wrapped function
132606c3fb27SDimitry Andric     if (num_lines == 1) {
132706c3fb27SDimitry Andric       sstr.Clear();
132806c3fb27SDimitry Andric       sstr.Printf("    __return_val = %s", input.GetStringAtIndex(0));
132906c3fb27SDimitry Andric       auto_generated_function.AppendString(sstr.GetData());
133006c3fb27SDimitry Andric     } else {
133106c3fb27SDimitry Andric       return Status("ScriptInterpreterPythonImpl::GenerateFunction(is_callback="
133206c3fb27SDimitry Andric                     "true) = ERROR: python function is multiline.");
133306c3fb27SDimitry Andric     }
133406c3fb27SDimitry Andric   } else {
133506c3fb27SDimitry Andric     auto_generated_function.AppendString(
133606c3fb27SDimitry Andric         "    __return_val = None"); // Initialize user callback return value.
133706c3fb27SDimitry Andric     auto_generated_function.AppendString(
133806c3fb27SDimitry Andric         "    def __user_code():"); // Create a nested function that will wrap
133906c3fb27SDimitry Andric                                    // the user input. This is necessary to
134006c3fb27SDimitry Andric                                    // capture the return value of the user input
134106c3fb27SDimitry Andric                                    // and prevent early returns.
13420b57cec5SDimitry Andric     for (int i = 0; i < num_lines; ++i) {
13430b57cec5SDimitry Andric       sstr.Clear();
13440b57cec5SDimitry Andric       sstr.Printf("      %s", input.GetStringAtIndex(i));
13450b57cec5SDimitry Andric       auto_generated_function.AppendString(sstr.GetData());
13460b57cec5SDimitry Andric     }
13470b57cec5SDimitry Andric     auto_generated_function.AppendString(
134806c3fb27SDimitry Andric         "    __return_val = __user_code()"); //  Call user code and capture
134906c3fb27SDimitry Andric                                              //  return value
135006c3fb27SDimitry Andric   }
135106c3fb27SDimitry Andric   auto_generated_function.AppendString(
13520b57cec5SDimitry Andric       "    for key in new_keys:"); // Iterate over all the keys from session
13530b57cec5SDimitry Andric                                    // dict
13540b57cec5SDimitry Andric   auto_generated_function.AppendString(
13550b57cec5SDimitry Andric       "        internal_dict[key] = global_dict[key]"); // Update session dict
13560b57cec5SDimitry Andric                                                         // values
13570b57cec5SDimitry Andric   auto_generated_function.AppendString(
13580b57cec5SDimitry Andric       "        if key not in old_keys:"); // If key was not originally in
13590b57cec5SDimitry Andric                                           // global dict
13600b57cec5SDimitry Andric   auto_generated_function.AppendString(
13610b57cec5SDimitry Andric       "            del global_dict[key]"); //  ...then remove key/value from
13620b57cec5SDimitry Andric                                            //  global dict
136306c3fb27SDimitry Andric   auto_generated_function.AppendString(
136406c3fb27SDimitry Andric       "    return __return_val"); //  Return the user callback return value.
13650b57cec5SDimitry Andric 
13660b57cec5SDimitry Andric   // Verify that the results are valid Python.
13670b57cec5SDimitry Andric   error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
13680b57cec5SDimitry Andric 
13690b57cec5SDimitry Andric   return error;
13700b57cec5SDimitry Andric }
13710b57cec5SDimitry Andric 
GenerateTypeScriptFunction(StringList & user_input,std::string & output,const void * name_token)13720b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
13730b57cec5SDimitry Andric     StringList &user_input, std::string &output, const void *name_token) {
13740b57cec5SDimitry Andric   static uint32_t num_created_functions = 0;
13750b57cec5SDimitry Andric   user_input.RemoveBlankLines();
13760b57cec5SDimitry Andric   StreamString sstr;
13770b57cec5SDimitry Andric 
13780b57cec5SDimitry Andric   // Check to see if we have any data; if not, just return.
13790b57cec5SDimitry Andric   if (user_input.GetSize() == 0)
13800b57cec5SDimitry Andric     return false;
13810b57cec5SDimitry Andric 
13820b57cec5SDimitry Andric   // Take what the user wrote, wrap it all up inside one big auto-generated
13830b57cec5SDimitry Andric   // Python function, passing in the ValueObject as parameter to the function.
13840b57cec5SDimitry Andric 
13850b57cec5SDimitry Andric   std::string auto_generated_function_name(
13860b57cec5SDimitry Andric       GenerateUniqueName("lldb_autogen_python_type_print_func",
13870b57cec5SDimitry Andric                          num_created_functions, name_token));
13880b57cec5SDimitry Andric   sstr.Printf("def %s (valobj, internal_dict):",
13890b57cec5SDimitry Andric               auto_generated_function_name.c_str());
13900b57cec5SDimitry Andric 
139106c3fb27SDimitry Andric   if (!GenerateFunction(sstr.GetData(), user_input, /*is_callback=*/false)
139206c3fb27SDimitry Andric            .Success())
13930b57cec5SDimitry Andric     return false;
13940b57cec5SDimitry Andric 
13950b57cec5SDimitry Andric   // Store the name of the auto-generated function to be called.
13960b57cec5SDimitry Andric   output.assign(auto_generated_function_name);
13970b57cec5SDimitry Andric   return true;
13980b57cec5SDimitry Andric }
13990b57cec5SDimitry Andric 
GenerateScriptAliasFunction(StringList & user_input,std::string & output)14000b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
14010b57cec5SDimitry Andric     StringList &user_input, std::string &output) {
14020b57cec5SDimitry Andric   static uint32_t num_created_functions = 0;
14030b57cec5SDimitry Andric   user_input.RemoveBlankLines();
14040b57cec5SDimitry Andric   StreamString sstr;
14050b57cec5SDimitry Andric 
14060b57cec5SDimitry Andric   // Check to see if we have any data; if not, just return.
14070b57cec5SDimitry Andric   if (user_input.GetSize() == 0)
14080b57cec5SDimitry Andric     return false;
14090b57cec5SDimitry Andric 
14100b57cec5SDimitry Andric   std::string auto_generated_function_name(GenerateUniqueName(
14110b57cec5SDimitry Andric       "lldb_autogen_python_cmd_alias_func", num_created_functions));
14120b57cec5SDimitry Andric 
1413bdd1243dSDimitry Andric   sstr.Printf("def %s (debugger, args, exe_ctx, result, internal_dict):",
14140b57cec5SDimitry Andric               auto_generated_function_name.c_str());
14150b57cec5SDimitry Andric 
141606c3fb27SDimitry Andric   if (!GenerateFunction(sstr.GetData(), user_input, /*is_callback=*/true)
141706c3fb27SDimitry Andric            .Success())
14180b57cec5SDimitry Andric     return false;
14190b57cec5SDimitry Andric 
14200b57cec5SDimitry Andric   // Store the name of the auto-generated function to be called.
14210b57cec5SDimitry Andric   output.assign(auto_generated_function_name);
14220b57cec5SDimitry Andric   return true;
14230b57cec5SDimitry Andric }
14240b57cec5SDimitry Andric 
GenerateTypeSynthClass(StringList & user_input,std::string & output,const void * name_token)14250b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
14260b57cec5SDimitry Andric     StringList &user_input, std::string &output, const void *name_token) {
14270b57cec5SDimitry Andric   static uint32_t num_created_classes = 0;
14280b57cec5SDimitry Andric   user_input.RemoveBlankLines();
14290b57cec5SDimitry Andric   int num_lines = user_input.GetSize();
14300b57cec5SDimitry Andric   StreamString sstr;
14310b57cec5SDimitry Andric 
14320b57cec5SDimitry Andric   // Check to see if we have any data; if not, just return.
14330b57cec5SDimitry Andric   if (user_input.GetSize() == 0)
14340b57cec5SDimitry Andric     return false;
14350b57cec5SDimitry Andric 
14360b57cec5SDimitry Andric   // Wrap all user input into a Python class
14370b57cec5SDimitry Andric 
14380b57cec5SDimitry Andric   std::string auto_generated_class_name(GenerateUniqueName(
14390b57cec5SDimitry Andric       "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
14400b57cec5SDimitry Andric 
14410b57cec5SDimitry Andric   StringList auto_generated_class;
14420b57cec5SDimitry Andric 
14430b57cec5SDimitry Andric   // Create the function name & definition string.
14440b57cec5SDimitry Andric 
14450b57cec5SDimitry Andric   sstr.Printf("class %s:", auto_generated_class_name.c_str());
14460b57cec5SDimitry Andric   auto_generated_class.AppendString(sstr.GetString());
14470b57cec5SDimitry Andric 
14480b57cec5SDimitry Andric   // Wrap everything up inside the class, increasing the indentation. we don't
14490b57cec5SDimitry Andric   // need to play any fancy indentation tricks here because there is no
14500b57cec5SDimitry Andric   // surrounding code whose indentation we need to honor
14510b57cec5SDimitry Andric   for (int i = 0; i < num_lines; ++i) {
14520b57cec5SDimitry Andric     sstr.Clear();
14530b57cec5SDimitry Andric     sstr.Printf("     %s", user_input.GetStringAtIndex(i));
14540b57cec5SDimitry Andric     auto_generated_class.AppendString(sstr.GetString());
14550b57cec5SDimitry Andric   }
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric   // Verify that the results are valid Python. (even though the method is
14580b57cec5SDimitry Andric   // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
14590b57cec5SDimitry Andric   // (TODO: rename that method to ExportDefinitionToInterpreter)
14600b57cec5SDimitry Andric   if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
14610b57cec5SDimitry Andric     return false;
14620b57cec5SDimitry Andric 
14630b57cec5SDimitry Andric   // Store the name of the auto-generated class
14640b57cec5SDimitry Andric 
14650b57cec5SDimitry Andric   output.assign(auto_generated_class_name);
14660b57cec5SDimitry Andric   return true;
14670b57cec5SDimitry Andric }
14680b57cec5SDimitry Andric 
14690b57cec5SDimitry Andric StructuredData::GenericSP
CreateFrameRecognizer(const char * class_name)14700b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
14710b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
14720b57cec5SDimitry Andric     return StructuredData::GenericSP();
14730b57cec5SDimitry Andric 
147404eeddc0SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
147506c3fb27SDimitry Andric   PythonObject ret_val = SWIGBridge::LLDBSWIGPython_CreateFrameRecognizer(
147604eeddc0SDimitry Andric       class_name, m_dictionary_name.c_str());
14770b57cec5SDimitry Andric 
147804eeddc0SDimitry Andric   return StructuredData::GenericSP(
147904eeddc0SDimitry Andric       new StructuredPythonObject(std::move(ret_val)));
14800b57cec5SDimitry Andric }
14810b57cec5SDimitry Andric 
GetRecognizedArguments(const StructuredData::ObjectSP & os_plugin_object_sp,lldb::StackFrameSP frame_sp)14820b57cec5SDimitry Andric lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
14830b57cec5SDimitry Andric     const StructuredData::ObjectSP &os_plugin_object_sp,
14840b57cec5SDimitry Andric     lldb::StackFrameSP frame_sp) {
14850b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
14860b57cec5SDimitry Andric 
14870b57cec5SDimitry Andric   if (!os_plugin_object_sp)
14880b57cec5SDimitry Andric     return ValueObjectListSP();
14890b57cec5SDimitry Andric 
14900b57cec5SDimitry Andric   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
14910b57cec5SDimitry Andric   if (!generic)
14920b57cec5SDimitry Andric     return nullptr;
14930b57cec5SDimitry Andric 
14940b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
14950b57cec5SDimitry Andric                            (PyObject *)generic->GetValue());
14960b57cec5SDimitry Andric 
14970b57cec5SDimitry Andric   if (!implementor.IsAllocated())
14980b57cec5SDimitry Andric     return ValueObjectListSP();
14990b57cec5SDimitry Andric 
150006c3fb27SDimitry Andric   PythonObject py_return(PyRefType::Owned,
150106c3fb27SDimitry Andric                          SWIGBridge::LLDBSwigPython_GetRecognizedArguments(
150206c3fb27SDimitry Andric                              implementor.get(), frame_sp));
15030b57cec5SDimitry Andric 
15040b57cec5SDimitry Andric   // if it fails, print the error but otherwise go on
15050b57cec5SDimitry Andric   if (PyErr_Occurred()) {
15060b57cec5SDimitry Andric     PyErr_Print();
15070b57cec5SDimitry Andric     PyErr_Clear();
15080b57cec5SDimitry Andric   }
15090b57cec5SDimitry Andric   if (py_return.get()) {
15100b57cec5SDimitry Andric     PythonList result_list(PyRefType::Borrowed, py_return.get());
15110b57cec5SDimitry Andric     ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
15120b57cec5SDimitry Andric     for (size_t i = 0; i < result_list.GetSize(); i++) {
15130b57cec5SDimitry Andric       PyObject *item = result_list.GetItemAtIndex(i).get();
15140b57cec5SDimitry Andric       lldb::SBValue *sb_value_ptr =
15150b57cec5SDimitry Andric           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
151606c3fb27SDimitry Andric       auto valobj_sp =
151706c3fb27SDimitry Andric           SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
15180b57cec5SDimitry Andric       if (valobj_sp)
15190b57cec5SDimitry Andric         result->Append(valobj_sp);
15200b57cec5SDimitry Andric     }
15210b57cec5SDimitry Andric     return result;
15220b57cec5SDimitry Andric   }
15230b57cec5SDimitry Andric   return ValueObjectListSP();
15240b57cec5SDimitry Andric }
15250b57cec5SDimitry Andric 
152606c3fb27SDimitry Andric ScriptedProcessInterfaceUP
CreateScriptedProcessInterface()152706c3fb27SDimitry Andric ScriptInterpreterPythonImpl::CreateScriptedProcessInterface() {
152806c3fb27SDimitry Andric   return std::make_unique<ScriptedProcessPythonInterface>(*this);
152906c3fb27SDimitry Andric }
153006c3fb27SDimitry Andric 
15315f757f3fSDimitry Andric ScriptedThreadInterfaceSP
CreateScriptedThreadInterface()15325f757f3fSDimitry Andric ScriptInterpreterPythonImpl::CreateScriptedThreadInterface() {
15335f757f3fSDimitry Andric   return std::make_shared<ScriptedThreadPythonInterface>(*this);
15345f757f3fSDimitry Andric }
15355f757f3fSDimitry Andric 
15365f757f3fSDimitry Andric OperatingSystemInterfaceSP
CreateOperatingSystemInterface()15375f757f3fSDimitry Andric ScriptInterpreterPythonImpl::CreateOperatingSystemInterface() {
15385f757f3fSDimitry Andric   return std::make_shared<OperatingSystemPythonInterface>(*this);
15395f757f3fSDimitry Andric }
15405f757f3fSDimitry Andric 
154106c3fb27SDimitry Andric StructuredData::ObjectSP
CreateStructuredDataFromScriptObject(ScriptObject obj)154206c3fb27SDimitry Andric ScriptInterpreterPythonImpl::CreateStructuredDataFromScriptObject(
154306c3fb27SDimitry Andric     ScriptObject obj) {
154406c3fb27SDimitry Andric   void *ptr = const_cast<void *>(obj.GetPointer());
154506c3fb27SDimitry Andric   PythonObject py_obj(PyRefType::Borrowed, static_cast<PyObject *>(ptr));
154606c3fb27SDimitry Andric   if (!py_obj.IsValid() || py_obj.IsNone())
154706c3fb27SDimitry Andric     return {};
154806c3fb27SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
154906c3fb27SDimitry Andric   return py_obj.CreateStructuredObject();
155006c3fb27SDimitry Andric }
155106c3fb27SDimitry Andric 
CreateScriptedThreadPlan(const char * class_name,const StructuredDataImpl & args_data,std::string & error_str,lldb::ThreadPlanSP thread_plan_sp)15520b57cec5SDimitry Andric StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan(
15530eae32dcSDimitry Andric     const char *class_name, const StructuredDataImpl &args_data,
1554480093f4SDimitry Andric     std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) {
15550b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
15560b57cec5SDimitry Andric     return StructuredData::ObjectSP();
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric   if (!thread_plan_sp.get())
15599dba64beSDimitry Andric     return {};
15600b57cec5SDimitry Andric 
15610b57cec5SDimitry Andric   Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
15620b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
1563e8d8bef9SDimitry Andric       GetPythonInterpreter(debugger);
15640b57cec5SDimitry Andric 
1565e8d8bef9SDimitry Andric   if (!python_interpreter)
15669dba64beSDimitry Andric     return {};
15670b57cec5SDimitry Andric 
15680b57cec5SDimitry Andric   Locker py_lock(this,
15690b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
157006c3fb27SDimitry Andric   PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateScriptedThreadPlan(
157104eeddc0SDimitry Andric       class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
157204eeddc0SDimitry Andric       error_str, thread_plan_sp);
15739dba64beSDimitry Andric   if (!ret_val)
15749dba64beSDimitry Andric     return {};
15750b57cec5SDimitry Andric 
157604eeddc0SDimitry Andric   return StructuredData::ObjectSP(
157704eeddc0SDimitry Andric       new StructuredPythonObject(std::move(ret_val)));
15780b57cec5SDimitry Andric }
15790b57cec5SDimitry Andric 
ScriptedThreadPlanExplainsStop(StructuredData::ObjectSP implementor_sp,Event * event,bool & script_error)15800b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop(
15810b57cec5SDimitry Andric     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
15820b57cec5SDimitry Andric   bool explains_stop = true;
15830b57cec5SDimitry Andric   StructuredData::Generic *generic = nullptr;
15840b57cec5SDimitry Andric   if (implementor_sp)
15850b57cec5SDimitry Andric     generic = implementor_sp->GetAsGeneric();
15860b57cec5SDimitry Andric   if (generic) {
15870b57cec5SDimitry Andric     Locker py_lock(this,
15880b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
158906c3fb27SDimitry Andric     explains_stop = SWIGBridge::LLDBSWIGPythonCallThreadPlan(
15900b57cec5SDimitry Andric         generic->GetValue(), "explains_stop", event, script_error);
15910b57cec5SDimitry Andric     if (script_error)
15920b57cec5SDimitry Andric       return true;
15930b57cec5SDimitry Andric   }
15940b57cec5SDimitry Andric   return explains_stop;
15950b57cec5SDimitry Andric }
15960b57cec5SDimitry Andric 
ScriptedThreadPlanShouldStop(StructuredData::ObjectSP implementor_sp,Event * event,bool & script_error)15970b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop(
15980b57cec5SDimitry Andric     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
15990b57cec5SDimitry Andric   bool should_stop = true;
16000b57cec5SDimitry Andric   StructuredData::Generic *generic = nullptr;
16010b57cec5SDimitry Andric   if (implementor_sp)
16020b57cec5SDimitry Andric     generic = implementor_sp->GetAsGeneric();
16030b57cec5SDimitry Andric   if (generic) {
16040b57cec5SDimitry Andric     Locker py_lock(this,
16050b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
160606c3fb27SDimitry Andric     should_stop = SWIGBridge::LLDBSWIGPythonCallThreadPlan(
16070b57cec5SDimitry Andric         generic->GetValue(), "should_stop", event, script_error);
16080b57cec5SDimitry Andric     if (script_error)
16090b57cec5SDimitry Andric       return true;
16100b57cec5SDimitry Andric   }
16110b57cec5SDimitry Andric   return should_stop;
16120b57cec5SDimitry Andric }
16130b57cec5SDimitry Andric 
ScriptedThreadPlanIsStale(StructuredData::ObjectSP implementor_sp,bool & script_error)16140b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale(
16150b57cec5SDimitry Andric     StructuredData::ObjectSP implementor_sp, bool &script_error) {
16160b57cec5SDimitry Andric   bool is_stale = true;
16170b57cec5SDimitry Andric   StructuredData::Generic *generic = nullptr;
16180b57cec5SDimitry Andric   if (implementor_sp)
16190b57cec5SDimitry Andric     generic = implementor_sp->GetAsGeneric();
16200b57cec5SDimitry Andric   if (generic) {
16210b57cec5SDimitry Andric     Locker py_lock(this,
16220b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
162306c3fb27SDimitry Andric     is_stale = SWIGBridge::LLDBSWIGPythonCallThreadPlan(
162406c3fb27SDimitry Andric         generic->GetValue(), "is_stale", (Event *)nullptr, script_error);
16250b57cec5SDimitry Andric     if (script_error)
16260b57cec5SDimitry Andric       return true;
16270b57cec5SDimitry Andric   }
16280b57cec5SDimitry Andric   return is_stale;
16290b57cec5SDimitry Andric }
16300b57cec5SDimitry Andric 
ScriptedThreadPlanGetRunState(StructuredData::ObjectSP implementor_sp,bool & script_error)16310b57cec5SDimitry Andric lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState(
16320b57cec5SDimitry Andric     StructuredData::ObjectSP implementor_sp, bool &script_error) {
16330b57cec5SDimitry Andric   bool should_step = false;
16340b57cec5SDimitry Andric   StructuredData::Generic *generic = nullptr;
16350b57cec5SDimitry Andric   if (implementor_sp)
16360b57cec5SDimitry Andric     generic = implementor_sp->GetAsGeneric();
16370b57cec5SDimitry Andric   if (generic) {
16380b57cec5SDimitry Andric     Locker py_lock(this,
16390b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
164006c3fb27SDimitry Andric     should_step = SWIGBridge::LLDBSWIGPythonCallThreadPlan(
164106c3fb27SDimitry Andric         generic->GetValue(), "should_step", (Event *)nullptr, script_error);
16420b57cec5SDimitry Andric     if (script_error)
16430b57cec5SDimitry Andric       should_step = true;
16440b57cec5SDimitry Andric   }
16450b57cec5SDimitry Andric   if (should_step)
16460b57cec5SDimitry Andric     return lldb::eStateStepping;
16470b57cec5SDimitry Andric   return lldb::eStateRunning;
16480b57cec5SDimitry Andric }
16490b57cec5SDimitry Andric 
165006c3fb27SDimitry Andric bool
ScriptedThreadPlanGetStopDescription(StructuredData::ObjectSP implementor_sp,lldb_private::Stream * stream,bool & script_error)165106c3fb27SDimitry Andric ScriptInterpreterPythonImpl::ScriptedThreadPlanGetStopDescription(
165206c3fb27SDimitry Andric     StructuredData::ObjectSP implementor_sp, lldb_private::Stream *stream,
165306c3fb27SDimitry Andric     bool &script_error) {
165406c3fb27SDimitry Andric   StructuredData::Generic *generic = nullptr;
165506c3fb27SDimitry Andric   if (implementor_sp)
165606c3fb27SDimitry Andric     generic = implementor_sp->GetAsGeneric();
165706c3fb27SDimitry Andric   if (!generic) {
165806c3fb27SDimitry Andric     script_error = true;
165906c3fb27SDimitry Andric     return false;
166006c3fb27SDimitry Andric   }
166106c3fb27SDimitry Andric   Locker py_lock(this,
166206c3fb27SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
166306c3fb27SDimitry Andric   return SWIGBridge::LLDBSWIGPythonCallThreadPlan(
166406c3fb27SDimitry Andric       generic->GetValue(), "stop_description", stream, script_error);
166506c3fb27SDimitry Andric }
166606c3fb27SDimitry Andric 
166706c3fb27SDimitry Andric 
16680b57cec5SDimitry Andric StructuredData::GenericSP
CreateScriptedBreakpointResolver(const char * class_name,const StructuredDataImpl & args_data,lldb::BreakpointSP & bkpt_sp)16690b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
16700eae32dcSDimitry Andric     const char *class_name, const StructuredDataImpl &args_data,
16710b57cec5SDimitry Andric     lldb::BreakpointSP &bkpt_sp) {
16720b57cec5SDimitry Andric 
16730b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
16740b57cec5SDimitry Andric     return StructuredData::GenericSP();
16750b57cec5SDimitry Andric 
16760b57cec5SDimitry Andric   if (!bkpt_sp.get())
16770b57cec5SDimitry Andric     return StructuredData::GenericSP();
16780b57cec5SDimitry Andric 
16790b57cec5SDimitry Andric   Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
16800b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
1681e8d8bef9SDimitry Andric       GetPythonInterpreter(debugger);
16820b57cec5SDimitry Andric 
1683e8d8bef9SDimitry Andric   if (!python_interpreter)
16840b57cec5SDimitry Andric     return StructuredData::GenericSP();
16850b57cec5SDimitry Andric 
16860b57cec5SDimitry Andric   Locker py_lock(this,
16870b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
16880b57cec5SDimitry Andric 
168906c3fb27SDimitry Andric   PythonObject ret_val =
169006c3fb27SDimitry Andric       SWIGBridge::LLDBSwigPythonCreateScriptedBreakpointResolver(
16910b57cec5SDimitry Andric           class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
16920b57cec5SDimitry Andric           bkpt_sp);
16930b57cec5SDimitry Andric 
169404eeddc0SDimitry Andric   return StructuredData::GenericSP(
169504eeddc0SDimitry Andric       new StructuredPythonObject(std::move(ret_val)));
16960b57cec5SDimitry Andric }
16970b57cec5SDimitry Andric 
ScriptedBreakpointResolverSearchCallback(StructuredData::GenericSP implementor_sp,SymbolContext * sym_ctx)16980b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
16990b57cec5SDimitry Andric     StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
17000b57cec5SDimitry Andric   bool should_continue = false;
17010b57cec5SDimitry Andric 
17020b57cec5SDimitry Andric   if (implementor_sp) {
17030b57cec5SDimitry Andric     Locker py_lock(this,
17040b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
170506c3fb27SDimitry Andric     should_continue = SWIGBridge::LLDBSwigPythonCallBreakpointResolver(
17060b57cec5SDimitry Andric         implementor_sp->GetValue(), "__callback__", sym_ctx);
17070b57cec5SDimitry Andric     if (PyErr_Occurred()) {
17080b57cec5SDimitry Andric       PyErr_Print();
17090b57cec5SDimitry Andric       PyErr_Clear();
17100b57cec5SDimitry Andric     }
17110b57cec5SDimitry Andric   }
17120b57cec5SDimitry Andric   return should_continue;
17130b57cec5SDimitry Andric }
17140b57cec5SDimitry Andric 
17150b57cec5SDimitry Andric lldb::SearchDepth
ScriptedBreakpointResolverSearchDepth(StructuredData::GenericSP implementor_sp)17160b57cec5SDimitry Andric ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
17170b57cec5SDimitry Andric     StructuredData::GenericSP implementor_sp) {
17180b57cec5SDimitry Andric   int depth_as_int = lldb::eSearchDepthModule;
17190b57cec5SDimitry Andric   if (implementor_sp) {
17200b57cec5SDimitry Andric     Locker py_lock(this,
17210b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
172206c3fb27SDimitry Andric     depth_as_int = SWIGBridge::LLDBSwigPythonCallBreakpointResolver(
17230b57cec5SDimitry Andric         implementor_sp->GetValue(), "__get_depth__", nullptr);
17240b57cec5SDimitry Andric     if (PyErr_Occurred()) {
17250b57cec5SDimitry Andric       PyErr_Print();
17260b57cec5SDimitry Andric       PyErr_Clear();
17270b57cec5SDimitry Andric     }
17280b57cec5SDimitry Andric   }
17290b57cec5SDimitry Andric   if (depth_as_int == lldb::eSearchDepthInvalid)
17300b57cec5SDimitry Andric     return lldb::eSearchDepthModule;
17310b57cec5SDimitry Andric 
17320b57cec5SDimitry Andric   if (depth_as_int <= lldb::kLastSearchDepthKind)
17330b57cec5SDimitry Andric     return (lldb::SearchDepth)depth_as_int;
17340b57cec5SDimitry Andric   return lldb::eSearchDepthModule;
17350b57cec5SDimitry Andric }
17360b57cec5SDimitry Andric 
CreateScriptedStopHook(TargetSP target_sp,const char * class_name,const StructuredDataImpl & args_data,Status & error)1737e8d8bef9SDimitry Andric StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
17380eae32dcSDimitry Andric     TargetSP target_sp, const char *class_name,
17390eae32dcSDimitry Andric     const StructuredDataImpl &args_data, Status &error) {
1740e8d8bef9SDimitry Andric 
1741e8d8bef9SDimitry Andric   if (!target_sp) {
1742e8d8bef9SDimitry Andric     error.SetErrorString("No target for scripted stop-hook.");
1743e8d8bef9SDimitry Andric     return StructuredData::GenericSP();
1744e8d8bef9SDimitry Andric   }
1745e8d8bef9SDimitry Andric 
1746e8d8bef9SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0') {
1747e8d8bef9SDimitry Andric     error.SetErrorString("No class name for scripted stop-hook.");
1748e8d8bef9SDimitry Andric     return StructuredData::GenericSP();
1749e8d8bef9SDimitry Andric   }
1750e8d8bef9SDimitry Andric 
1751e8d8bef9SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
1752e8d8bef9SDimitry Andric       GetPythonInterpreter(m_debugger);
1753e8d8bef9SDimitry Andric 
1754e8d8bef9SDimitry Andric   if (!python_interpreter) {
1755e8d8bef9SDimitry Andric     error.SetErrorString("No script interpreter for scripted stop-hook.");
1756e8d8bef9SDimitry Andric     return StructuredData::GenericSP();
1757e8d8bef9SDimitry Andric   }
1758e8d8bef9SDimitry Andric 
1759e8d8bef9SDimitry Andric   Locker py_lock(this,
1760e8d8bef9SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1761e8d8bef9SDimitry Andric 
176206c3fb27SDimitry Andric   PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateScriptedStopHook(
1763e8d8bef9SDimitry Andric       target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
1764e8d8bef9SDimitry Andric       args_data, error);
1765e8d8bef9SDimitry Andric 
176604eeddc0SDimitry Andric   return StructuredData::GenericSP(
176704eeddc0SDimitry Andric       new StructuredPythonObject(std::move(ret_val)));
1768e8d8bef9SDimitry Andric }
1769e8d8bef9SDimitry Andric 
ScriptedStopHookHandleStop(StructuredData::GenericSP implementor_sp,ExecutionContext & exc_ctx,lldb::StreamSP stream_sp)1770e8d8bef9SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
1771e8d8bef9SDimitry Andric     StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
1772e8d8bef9SDimitry Andric     lldb::StreamSP stream_sp) {
1773e8d8bef9SDimitry Andric   assert(implementor_sp &&
1774e8d8bef9SDimitry Andric          "can't call a stop hook with an invalid implementor");
1775e8d8bef9SDimitry Andric   assert(stream_sp && "can't call a stop hook with an invalid stream");
1776e8d8bef9SDimitry Andric 
1777e8d8bef9SDimitry Andric   Locker py_lock(this,
1778e8d8bef9SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1779e8d8bef9SDimitry Andric 
1780e8d8bef9SDimitry Andric   lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
1781e8d8bef9SDimitry Andric 
178206c3fb27SDimitry Andric   bool ret_val = SWIGBridge::LLDBSwigPythonStopHookCallHandleStop(
1783e8d8bef9SDimitry Andric       implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
1784e8d8bef9SDimitry Andric   return ret_val;
1785e8d8bef9SDimitry Andric }
1786e8d8bef9SDimitry Andric 
17870b57cec5SDimitry Andric StructuredData::ObjectSP
LoadPluginModule(const FileSpec & file_spec,lldb_private::Status & error)17880b57cec5SDimitry Andric ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
17890b57cec5SDimitry Andric                                               lldb_private::Status &error) {
17900b57cec5SDimitry Andric   if (!FileSystem::Instance().Exists(file_spec)) {
17910b57cec5SDimitry Andric     error.SetErrorString("no such file");
17920b57cec5SDimitry Andric     return StructuredData::ObjectSP();
17930b57cec5SDimitry Andric   }
17940b57cec5SDimitry Andric 
17950b57cec5SDimitry Andric   StructuredData::ObjectSP module_sp;
17960b57cec5SDimitry Andric 
1797fe6060f1SDimitry Andric   LoadScriptOptions load_script_options =
1798fe6060f1SDimitry Andric       LoadScriptOptions().SetInitSession(true).SetSilent(false);
1799fe6060f1SDimitry Andric   if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1800fe6060f1SDimitry Andric                           error, &module_sp))
18010b57cec5SDimitry Andric     return module_sp;
18020b57cec5SDimitry Andric 
18030b57cec5SDimitry Andric   return StructuredData::ObjectSP();
18040b57cec5SDimitry Andric }
18050b57cec5SDimitry Andric 
GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp,Target * target,const char * setting_name,lldb_private::Status & error)18060b57cec5SDimitry Andric StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
18070b57cec5SDimitry Andric     StructuredData::ObjectSP plugin_module_sp, Target *target,
18080b57cec5SDimitry Andric     const char *setting_name, lldb_private::Status &error) {
18090b57cec5SDimitry Andric   if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
18100b57cec5SDimitry Andric     return StructuredData::DictionarySP();
18110b57cec5SDimitry Andric   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
18120b57cec5SDimitry Andric   if (!generic)
18130b57cec5SDimitry Andric     return StructuredData::DictionarySP();
18140b57cec5SDimitry Andric 
18150b57cec5SDimitry Andric   Locker py_lock(this,
18160b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
18170b57cec5SDimitry Andric   TargetSP target_sp(target->shared_from_this());
18180b57cec5SDimitry Andric 
181906c3fb27SDimitry Andric   auto setting = (PyObject *)SWIGBridge::LLDBSWIGPython_GetDynamicSetting(
18209dba64beSDimitry Andric       generic->GetValue(), setting_name, target_sp);
18219dba64beSDimitry Andric 
18229dba64beSDimitry Andric   if (!setting)
18239dba64beSDimitry Andric     return StructuredData::DictionarySP();
18249dba64beSDimitry Andric 
18259dba64beSDimitry Andric   PythonDictionary py_dict =
18269dba64beSDimitry Andric       unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
18279dba64beSDimitry Andric 
18289dba64beSDimitry Andric   if (!py_dict)
18299dba64beSDimitry Andric     return StructuredData::DictionarySP();
18309dba64beSDimitry Andric 
18310b57cec5SDimitry Andric   return py_dict.CreateStructuredDictionary();
18320b57cec5SDimitry Andric }
18330b57cec5SDimitry Andric 
18340b57cec5SDimitry Andric StructuredData::ObjectSP
CreateSyntheticScriptedProvider(const char * class_name,lldb::ValueObjectSP valobj)18350b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
18360b57cec5SDimitry Andric     const char *class_name, lldb::ValueObjectSP valobj) {
18370b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
18380b57cec5SDimitry Andric     return StructuredData::ObjectSP();
18390b57cec5SDimitry Andric 
18400b57cec5SDimitry Andric   if (!valobj.get())
18410b57cec5SDimitry Andric     return StructuredData::ObjectSP();
18420b57cec5SDimitry Andric 
18430b57cec5SDimitry Andric   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
18440b57cec5SDimitry Andric   Target *target = exe_ctx.GetTargetPtr();
18450b57cec5SDimitry Andric 
18460b57cec5SDimitry Andric   if (!target)
18470b57cec5SDimitry Andric     return StructuredData::ObjectSP();
18480b57cec5SDimitry Andric 
18490b57cec5SDimitry Andric   Debugger &debugger = target->GetDebugger();
18500b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
1851e8d8bef9SDimitry Andric       GetPythonInterpreter(debugger);
18520b57cec5SDimitry Andric 
1853e8d8bef9SDimitry Andric   if (!python_interpreter)
18540b57cec5SDimitry Andric     return StructuredData::ObjectSP();
18550b57cec5SDimitry Andric 
18560b57cec5SDimitry Andric   Locker py_lock(this,
18570b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
185806c3fb27SDimitry Andric   PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateSyntheticProvider(
18590b57cec5SDimitry Andric       class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
18600b57cec5SDimitry Andric 
186104eeddc0SDimitry Andric   return StructuredData::ObjectSP(
186204eeddc0SDimitry Andric       new StructuredPythonObject(std::move(ret_val)));
18630b57cec5SDimitry Andric }
18640b57cec5SDimitry Andric 
18650b57cec5SDimitry Andric StructuredData::GenericSP
CreateScriptCommandObject(const char * class_name)18660b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
18670b57cec5SDimitry Andric   DebuggerSP debugger_sp(m_debugger.shared_from_this());
18680b57cec5SDimitry Andric 
18690b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
18700b57cec5SDimitry Andric     return StructuredData::GenericSP();
18710b57cec5SDimitry Andric 
18720b57cec5SDimitry Andric   if (!debugger_sp.get())
18730b57cec5SDimitry Andric     return StructuredData::GenericSP();
18740b57cec5SDimitry Andric 
18750b57cec5SDimitry Andric   Locker py_lock(this,
18760b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
187706c3fb27SDimitry Andric   PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateCommandObject(
18780b57cec5SDimitry Andric       class_name, m_dictionary_name.c_str(), debugger_sp);
18790b57cec5SDimitry Andric 
188006c3fb27SDimitry Andric   if (ret_val.IsValid())
188104eeddc0SDimitry Andric     return StructuredData::GenericSP(
188204eeddc0SDimitry Andric         new StructuredPythonObject(std::move(ret_val)));
188306c3fb27SDimitry Andric   else
188406c3fb27SDimitry Andric     return {};
18850b57cec5SDimitry Andric }
18860b57cec5SDimitry Andric 
GenerateTypeScriptFunction(const char * oneliner,std::string & output,const void * name_token)18870b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
18880b57cec5SDimitry Andric     const char *oneliner, std::string &output, const void *name_token) {
18890b57cec5SDimitry Andric   StringList input;
18900b57cec5SDimitry Andric   input.SplitIntoLines(oneliner, strlen(oneliner));
18910b57cec5SDimitry Andric   return GenerateTypeScriptFunction(input, output, name_token);
18920b57cec5SDimitry Andric }
18930b57cec5SDimitry Andric 
GenerateTypeSynthClass(const char * oneliner,std::string & output,const void * name_token)18940b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
18950b57cec5SDimitry Andric     const char *oneliner, std::string &output, const void *name_token) {
18960b57cec5SDimitry Andric   StringList input;
18970b57cec5SDimitry Andric   input.SplitIntoLines(oneliner, strlen(oneliner));
18980b57cec5SDimitry Andric   return GenerateTypeSynthClass(input, output, name_token);
18990b57cec5SDimitry Andric }
19000b57cec5SDimitry Andric 
GenerateBreakpointCommandCallbackData(StringList & user_input,std::string & output,bool has_extra_args,bool is_callback)19010b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
190206c3fb27SDimitry Andric     StringList &user_input, std::string &output, bool has_extra_args,
190306c3fb27SDimitry Andric     bool is_callback) {
19040b57cec5SDimitry Andric   static uint32_t num_created_functions = 0;
19050b57cec5SDimitry Andric   user_input.RemoveBlankLines();
19060b57cec5SDimitry Andric   StreamString sstr;
19070b57cec5SDimitry Andric   Status error;
19080b57cec5SDimitry Andric   if (user_input.GetSize() == 0) {
19090b57cec5SDimitry Andric     error.SetErrorString("No input data.");
19100b57cec5SDimitry Andric     return error;
19110b57cec5SDimitry Andric   }
19120b57cec5SDimitry Andric 
19130b57cec5SDimitry Andric   std::string auto_generated_function_name(GenerateUniqueName(
19140b57cec5SDimitry Andric       "lldb_autogen_python_bp_callback_func_", num_created_functions));
1915480093f4SDimitry Andric   if (has_extra_args)
1916480093f4SDimitry Andric     sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
1917480093f4SDimitry Andric                 auto_generated_function_name.c_str());
1918480093f4SDimitry Andric   else
19190b57cec5SDimitry Andric     sstr.Printf("def %s (frame, bp_loc, internal_dict):",
19200b57cec5SDimitry Andric                 auto_generated_function_name.c_str());
19210b57cec5SDimitry Andric 
192206c3fb27SDimitry Andric   error = GenerateFunction(sstr.GetData(), user_input, is_callback);
19230b57cec5SDimitry Andric   if (!error.Success())
19240b57cec5SDimitry Andric     return error;
19250b57cec5SDimitry Andric 
19260b57cec5SDimitry Andric   // Store the name of the auto-generated function to be called.
19270b57cec5SDimitry Andric   output.assign(auto_generated_function_name);
19280b57cec5SDimitry Andric   return error;
19290b57cec5SDimitry Andric }
19300b57cec5SDimitry Andric 
GenerateWatchpointCommandCallbackData(StringList & user_input,std::string & output,bool is_callback)19310b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
193206c3fb27SDimitry Andric     StringList &user_input, std::string &output, bool is_callback) {
19330b57cec5SDimitry Andric   static uint32_t num_created_functions = 0;
19340b57cec5SDimitry Andric   user_input.RemoveBlankLines();
19350b57cec5SDimitry Andric   StreamString sstr;
19360b57cec5SDimitry Andric 
19370b57cec5SDimitry Andric   if (user_input.GetSize() == 0)
19380b57cec5SDimitry Andric     return false;
19390b57cec5SDimitry Andric 
19400b57cec5SDimitry Andric   std::string auto_generated_function_name(GenerateUniqueName(
19410b57cec5SDimitry Andric       "lldb_autogen_python_wp_callback_func_", num_created_functions));
19420b57cec5SDimitry Andric   sstr.Printf("def %s (frame, wp, internal_dict):",
19430b57cec5SDimitry Andric               auto_generated_function_name.c_str());
19440b57cec5SDimitry Andric 
194506c3fb27SDimitry Andric   if (!GenerateFunction(sstr.GetData(), user_input, is_callback).Success())
19460b57cec5SDimitry Andric     return false;
19470b57cec5SDimitry Andric 
19480b57cec5SDimitry Andric   // Store the name of the auto-generated function to be called.
19490b57cec5SDimitry Andric   output.assign(auto_generated_function_name);
19500b57cec5SDimitry Andric   return true;
19510b57cec5SDimitry Andric }
19520b57cec5SDimitry Andric 
GetScriptedSummary(const char * python_function_name,lldb::ValueObjectSP valobj,StructuredData::ObjectSP & callee_wrapper_sp,const TypeSummaryOptions & options,std::string & retval)19530b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetScriptedSummary(
19540b57cec5SDimitry Andric     const char *python_function_name, lldb::ValueObjectSP valobj,
19550b57cec5SDimitry Andric     StructuredData::ObjectSP &callee_wrapper_sp,
19560b57cec5SDimitry Andric     const TypeSummaryOptions &options, std::string &retval) {
19570b57cec5SDimitry Andric 
1958e8d8bef9SDimitry Andric   LLDB_SCOPED_TIMER();
19590b57cec5SDimitry Andric 
19600b57cec5SDimitry Andric   if (!valobj.get()) {
19610b57cec5SDimitry Andric     retval.assign("<no object>");
19620b57cec5SDimitry Andric     return false;
19630b57cec5SDimitry Andric   }
19640b57cec5SDimitry Andric 
19650b57cec5SDimitry Andric   void *old_callee = nullptr;
19660b57cec5SDimitry Andric   StructuredData::Generic *generic = nullptr;
19670b57cec5SDimitry Andric   if (callee_wrapper_sp) {
19680b57cec5SDimitry Andric     generic = callee_wrapper_sp->GetAsGeneric();
19690b57cec5SDimitry Andric     if (generic)
19700b57cec5SDimitry Andric       old_callee = generic->GetValue();
19710b57cec5SDimitry Andric   }
19720b57cec5SDimitry Andric   void *new_callee = old_callee;
19730b57cec5SDimitry Andric 
19740b57cec5SDimitry Andric   bool ret_val;
19750b57cec5SDimitry Andric   if (python_function_name && *python_function_name) {
19760b57cec5SDimitry Andric     {
19770b57cec5SDimitry Andric       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
19780b57cec5SDimitry Andric                                Locker::NoSTDIN);
19790b57cec5SDimitry Andric       {
19800b57cec5SDimitry Andric         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
19810b57cec5SDimitry Andric 
19820b57cec5SDimitry Andric         static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
19830b57cec5SDimitry Andric         Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
198406c3fb27SDimitry Andric         ret_val = SWIGBridge::LLDBSwigPythonCallTypeScript(
19850b57cec5SDimitry Andric             python_function_name, GetSessionDictionary().get(), valobj,
19860b57cec5SDimitry Andric             &new_callee, options_sp, retval);
19870b57cec5SDimitry Andric       }
19880b57cec5SDimitry Andric     }
19890b57cec5SDimitry Andric   } else {
19900b57cec5SDimitry Andric     retval.assign("<no function name>");
19910b57cec5SDimitry Andric     return false;
19920b57cec5SDimitry Andric   }
19930b57cec5SDimitry Andric 
199404eeddc0SDimitry Andric   if (new_callee && old_callee != new_callee) {
199504eeddc0SDimitry Andric     Locker py_lock(this,
199604eeddc0SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
199704eeddc0SDimitry Andric     callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
199804eeddc0SDimitry Andric         PythonObject(PyRefType::Borrowed, static_cast<PyObject *>(new_callee)));
199904eeddc0SDimitry Andric   }
20000b57cec5SDimitry Andric 
20010b57cec5SDimitry Andric   return ret_val;
20020b57cec5SDimitry Andric }
20030b57cec5SDimitry Andric 
FormatterCallbackFunction(const char * python_function_name,TypeImplSP type_impl_sp)2004bdd1243dSDimitry Andric bool ScriptInterpreterPythonImpl::FormatterCallbackFunction(
2005bdd1243dSDimitry Andric     const char *python_function_name, TypeImplSP type_impl_sp) {
2006bdd1243dSDimitry Andric   Locker py_lock(this,
2007bdd1243dSDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
200806c3fb27SDimitry Andric   return SWIGBridge::LLDBSwigPythonFormatterCallbackFunction(
2009bdd1243dSDimitry Andric       python_function_name, m_dictionary_name.c_str(), type_impl_sp);
2010bdd1243dSDimitry Andric }
2011bdd1243dSDimitry Andric 
BreakpointCallbackFunction(void * baton,StoppointCallbackContext * context,user_id_t break_id,user_id_t break_loc_id)20120b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
20130b57cec5SDimitry Andric     void *baton, StoppointCallbackContext *context, user_id_t break_id,
20140b57cec5SDimitry Andric     user_id_t break_loc_id) {
20150b57cec5SDimitry Andric   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
20160b57cec5SDimitry Andric   const char *python_function_name = bp_option_data->script_source.c_str();
20170b57cec5SDimitry Andric 
20180b57cec5SDimitry Andric   if (!context)
20190b57cec5SDimitry Andric     return true;
20200b57cec5SDimitry Andric 
20210b57cec5SDimitry Andric   ExecutionContext exe_ctx(context->exe_ctx_ref);
20220b57cec5SDimitry Andric   Target *target = exe_ctx.GetTargetPtr();
20230b57cec5SDimitry Andric 
20240b57cec5SDimitry Andric   if (!target)
20250b57cec5SDimitry Andric     return true;
20260b57cec5SDimitry Andric 
20270b57cec5SDimitry Andric   Debugger &debugger = target->GetDebugger();
20280b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
2029e8d8bef9SDimitry Andric       GetPythonInterpreter(debugger);
20300b57cec5SDimitry Andric 
2031e8d8bef9SDimitry Andric   if (!python_interpreter)
20320b57cec5SDimitry Andric     return true;
20330b57cec5SDimitry Andric 
20340b57cec5SDimitry Andric   if (python_function_name && python_function_name[0]) {
20350b57cec5SDimitry Andric     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
20360b57cec5SDimitry Andric     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
20370b57cec5SDimitry Andric     if (breakpoint_sp) {
20380b57cec5SDimitry Andric       const BreakpointLocationSP bp_loc_sp(
20390b57cec5SDimitry Andric           breakpoint_sp->FindLocationByID(break_loc_id));
20400b57cec5SDimitry Andric 
20410b57cec5SDimitry Andric       if (stop_frame_sp && bp_loc_sp) {
20420b57cec5SDimitry Andric         bool ret_val = true;
20430b57cec5SDimitry Andric         {
20440b57cec5SDimitry Andric           Locker py_lock(python_interpreter, Locker::AcquireLock |
20450b57cec5SDimitry Andric                                                  Locker::InitSession |
20460b57cec5SDimitry Andric                                                  Locker::NoSTDIN);
2047480093f4SDimitry Andric           Expected<bool> maybe_ret_val =
204806c3fb27SDimitry Andric               SWIGBridge::LLDBSwigPythonBreakpointCallbackFunction(
20490b57cec5SDimitry Andric                   python_function_name,
20500b57cec5SDimitry Andric                   python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
20510eae32dcSDimitry Andric                   bp_loc_sp, bp_option_data->m_extra_args);
2052480093f4SDimitry Andric 
2053480093f4SDimitry Andric           if (!maybe_ret_val) {
2054480093f4SDimitry Andric 
2055480093f4SDimitry Andric             llvm::handleAllErrors(
2056480093f4SDimitry Andric                 maybe_ret_val.takeError(),
2057480093f4SDimitry Andric                 [&](PythonException &E) {
2058480093f4SDimitry Andric                   debugger.GetErrorStream() << E.ReadBacktrace();
2059480093f4SDimitry Andric                 },
2060480093f4SDimitry Andric                 [&](const llvm::ErrorInfoBase &E) {
2061480093f4SDimitry Andric                   debugger.GetErrorStream() << E.message();
2062480093f4SDimitry Andric                 });
2063480093f4SDimitry Andric 
2064480093f4SDimitry Andric           } else {
2065480093f4SDimitry Andric             ret_val = maybe_ret_val.get();
2066480093f4SDimitry Andric           }
20670b57cec5SDimitry Andric         }
20680b57cec5SDimitry Andric         return ret_val;
20690b57cec5SDimitry Andric       }
20700b57cec5SDimitry Andric     }
20710b57cec5SDimitry Andric   }
20720b57cec5SDimitry Andric   // We currently always true so we stop in case anything goes wrong when
20730b57cec5SDimitry Andric   // trying to call the script function
20740b57cec5SDimitry Andric   return true;
20750b57cec5SDimitry Andric }
20760b57cec5SDimitry Andric 
WatchpointCallbackFunction(void * baton,StoppointCallbackContext * context,user_id_t watch_id)20770b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
20780b57cec5SDimitry Andric     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
20790b57cec5SDimitry Andric   WatchpointOptions::CommandData *wp_option_data =
20800b57cec5SDimitry Andric       (WatchpointOptions::CommandData *)baton;
20810b57cec5SDimitry Andric   const char *python_function_name = wp_option_data->script_source.c_str();
20820b57cec5SDimitry Andric 
20830b57cec5SDimitry Andric   if (!context)
20840b57cec5SDimitry Andric     return true;
20850b57cec5SDimitry Andric 
20860b57cec5SDimitry Andric   ExecutionContext exe_ctx(context->exe_ctx_ref);
20870b57cec5SDimitry Andric   Target *target = exe_ctx.GetTargetPtr();
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric   if (!target)
20900b57cec5SDimitry Andric     return true;
20910b57cec5SDimitry Andric 
20920b57cec5SDimitry Andric   Debugger &debugger = target->GetDebugger();
20930b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
2094e8d8bef9SDimitry Andric       GetPythonInterpreter(debugger);
20950b57cec5SDimitry Andric 
2096e8d8bef9SDimitry Andric   if (!python_interpreter)
20970b57cec5SDimitry Andric     return true;
20980b57cec5SDimitry Andric 
20990b57cec5SDimitry Andric   if (python_function_name && python_function_name[0]) {
21000b57cec5SDimitry Andric     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
21010b57cec5SDimitry Andric     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
21020b57cec5SDimitry Andric     if (wp_sp) {
21030b57cec5SDimitry Andric       if (stop_frame_sp && wp_sp) {
21040b57cec5SDimitry Andric         bool ret_val = true;
21050b57cec5SDimitry Andric         {
21060b57cec5SDimitry Andric           Locker py_lock(python_interpreter, Locker::AcquireLock |
21070b57cec5SDimitry Andric                                                  Locker::InitSession |
21080b57cec5SDimitry Andric                                                  Locker::NoSTDIN);
210906c3fb27SDimitry Andric           ret_val = SWIGBridge::LLDBSwigPythonWatchpointCallbackFunction(
21100b57cec5SDimitry Andric               python_function_name,
21110b57cec5SDimitry Andric               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
21120b57cec5SDimitry Andric               wp_sp);
21130b57cec5SDimitry Andric         }
21140b57cec5SDimitry Andric         return ret_val;
21150b57cec5SDimitry Andric       }
21160b57cec5SDimitry Andric     }
21170b57cec5SDimitry Andric   }
21180b57cec5SDimitry Andric   // We currently always true so we stop in case anything goes wrong when
21190b57cec5SDimitry Andric   // trying to call the script function
21200b57cec5SDimitry Andric   return true;
21210b57cec5SDimitry Andric }
21220b57cec5SDimitry Andric 
CalculateNumChildren(const StructuredData::ObjectSP & implementor_sp,uint32_t max)21230b57cec5SDimitry Andric size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
21240b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
21250b57cec5SDimitry Andric   if (!implementor_sp)
21260b57cec5SDimitry Andric     return 0;
21270b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
21280b57cec5SDimitry Andric   if (!generic)
21290b57cec5SDimitry Andric     return 0;
21304824e7fdSDimitry Andric   auto *implementor = static_cast<PyObject *>(generic->GetValue());
21310b57cec5SDimitry Andric   if (!implementor)
21320b57cec5SDimitry Andric     return 0;
21330b57cec5SDimitry Andric 
21340b57cec5SDimitry Andric   size_t ret_val = 0;
21350b57cec5SDimitry Andric 
21360b57cec5SDimitry Andric   {
21370b57cec5SDimitry Andric     Locker py_lock(this,
21380b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
213906c3fb27SDimitry Andric     ret_val = SWIGBridge::LLDBSwigPython_CalculateNumChildren(implementor, max);
21400b57cec5SDimitry Andric   }
21410b57cec5SDimitry Andric 
21420b57cec5SDimitry Andric   return ret_val;
21430b57cec5SDimitry Andric }
21440b57cec5SDimitry Andric 
GetChildAtIndex(const StructuredData::ObjectSP & implementor_sp,uint32_t idx)21450b57cec5SDimitry Andric lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
21460b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
21470b57cec5SDimitry Andric   if (!implementor_sp)
21480b57cec5SDimitry Andric     return lldb::ValueObjectSP();
21490b57cec5SDimitry Andric 
21500b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
21510b57cec5SDimitry Andric   if (!generic)
21520b57cec5SDimitry Andric     return lldb::ValueObjectSP();
21534824e7fdSDimitry Andric   auto *implementor = static_cast<PyObject *>(generic->GetValue());
21540b57cec5SDimitry Andric   if (!implementor)
21550b57cec5SDimitry Andric     return lldb::ValueObjectSP();
21560b57cec5SDimitry Andric 
21570b57cec5SDimitry Andric   lldb::ValueObjectSP ret_val;
21580b57cec5SDimitry Andric   {
21590b57cec5SDimitry Andric     Locker py_lock(this,
21600b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
216106c3fb27SDimitry Andric     PyObject *child_ptr =
216206c3fb27SDimitry Andric         SWIGBridge::LLDBSwigPython_GetChildAtIndex(implementor, idx);
21630b57cec5SDimitry Andric     if (child_ptr != nullptr && child_ptr != Py_None) {
21640b57cec5SDimitry Andric       lldb::SBValue *sb_value_ptr =
21650b57cec5SDimitry Andric           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
21660b57cec5SDimitry Andric       if (sb_value_ptr == nullptr)
21670b57cec5SDimitry Andric         Py_XDECREF(child_ptr);
21680b57cec5SDimitry Andric       else
216906c3fb27SDimitry Andric         ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
217006c3fb27SDimitry Andric             sb_value_ptr);
21710b57cec5SDimitry Andric     } else {
21720b57cec5SDimitry Andric       Py_XDECREF(child_ptr);
21730b57cec5SDimitry Andric     }
21740b57cec5SDimitry Andric   }
21750b57cec5SDimitry Andric 
21760b57cec5SDimitry Andric   return ret_val;
21770b57cec5SDimitry Andric }
21780b57cec5SDimitry Andric 
GetIndexOfChildWithName(const StructuredData::ObjectSP & implementor_sp,const char * child_name)21790b57cec5SDimitry Andric int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
21800b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
21810b57cec5SDimitry Andric   if (!implementor_sp)
21820b57cec5SDimitry Andric     return UINT32_MAX;
21830b57cec5SDimitry Andric 
21840b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
21850b57cec5SDimitry Andric   if (!generic)
21860b57cec5SDimitry Andric     return UINT32_MAX;
21874824e7fdSDimitry Andric   auto *implementor = static_cast<PyObject *>(generic->GetValue());
21880b57cec5SDimitry Andric   if (!implementor)
21890b57cec5SDimitry Andric     return UINT32_MAX;
21900b57cec5SDimitry Andric 
21910b57cec5SDimitry Andric   int ret_val = UINT32_MAX;
21920b57cec5SDimitry Andric 
21930b57cec5SDimitry Andric   {
21940b57cec5SDimitry Andric     Locker py_lock(this,
21950b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
219606c3fb27SDimitry Andric     ret_val = SWIGBridge::LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
21970b57cec5SDimitry Andric   }
21980b57cec5SDimitry Andric 
21990b57cec5SDimitry Andric   return ret_val;
22000b57cec5SDimitry Andric }
22010b57cec5SDimitry Andric 
UpdateSynthProviderInstance(const StructuredData::ObjectSP & implementor_sp)22020b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
22030b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp) {
22040b57cec5SDimitry Andric   bool ret_val = false;
22050b57cec5SDimitry Andric 
22060b57cec5SDimitry Andric   if (!implementor_sp)
22070b57cec5SDimitry Andric     return ret_val;
22080b57cec5SDimitry Andric 
22090b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
22100b57cec5SDimitry Andric   if (!generic)
22110b57cec5SDimitry Andric     return ret_val;
22124824e7fdSDimitry Andric   auto *implementor = static_cast<PyObject *>(generic->GetValue());
22130b57cec5SDimitry Andric   if (!implementor)
22140b57cec5SDimitry Andric     return ret_val;
22150b57cec5SDimitry Andric 
22160b57cec5SDimitry Andric   {
22170b57cec5SDimitry Andric     Locker py_lock(this,
22180b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
221906c3fb27SDimitry Andric     ret_val =
222006c3fb27SDimitry Andric         SWIGBridge::LLDBSwigPython_UpdateSynthProviderInstance(implementor);
22210b57cec5SDimitry Andric   }
22220b57cec5SDimitry Andric 
22230b57cec5SDimitry Andric   return ret_val;
22240b57cec5SDimitry Andric }
22250b57cec5SDimitry Andric 
MightHaveChildrenSynthProviderInstance(const StructuredData::ObjectSP & implementor_sp)22260b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
22270b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp) {
22280b57cec5SDimitry Andric   bool ret_val = false;
22290b57cec5SDimitry Andric 
22300b57cec5SDimitry Andric   if (!implementor_sp)
22310b57cec5SDimitry Andric     return ret_val;
22320b57cec5SDimitry Andric 
22330b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
22340b57cec5SDimitry Andric   if (!generic)
22350b57cec5SDimitry Andric     return ret_val;
22364824e7fdSDimitry Andric   auto *implementor = static_cast<PyObject *>(generic->GetValue());
22370b57cec5SDimitry Andric   if (!implementor)
22380b57cec5SDimitry Andric     return ret_val;
22390b57cec5SDimitry Andric 
22400b57cec5SDimitry Andric   {
22410b57cec5SDimitry Andric     Locker py_lock(this,
22420b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
224306c3fb27SDimitry Andric     ret_val = SWIGBridge::LLDBSwigPython_MightHaveChildrenSynthProviderInstance(
224406c3fb27SDimitry Andric         implementor);
22450b57cec5SDimitry Andric   }
22460b57cec5SDimitry Andric 
22470b57cec5SDimitry Andric   return ret_val;
22480b57cec5SDimitry Andric }
22490b57cec5SDimitry Andric 
GetSyntheticValue(const StructuredData::ObjectSP & implementor_sp)22500b57cec5SDimitry Andric lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
22510b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp) {
22520b57cec5SDimitry Andric   lldb::ValueObjectSP ret_val(nullptr);
22530b57cec5SDimitry Andric 
22540b57cec5SDimitry Andric   if (!implementor_sp)
22550b57cec5SDimitry Andric     return ret_val;
22560b57cec5SDimitry Andric 
22570b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
22580b57cec5SDimitry Andric   if (!generic)
22590b57cec5SDimitry Andric     return ret_val;
22604824e7fdSDimitry Andric   auto *implementor = static_cast<PyObject *>(generic->GetValue());
22610b57cec5SDimitry Andric   if (!implementor)
22620b57cec5SDimitry Andric     return ret_val;
22630b57cec5SDimitry Andric 
22640b57cec5SDimitry Andric   {
22650b57cec5SDimitry Andric     Locker py_lock(this,
22660b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
22674824e7fdSDimitry Andric     PyObject *child_ptr =
226806c3fb27SDimitry Andric         SWIGBridge::LLDBSwigPython_GetValueSynthProviderInstance(implementor);
22690b57cec5SDimitry Andric     if (child_ptr != nullptr && child_ptr != Py_None) {
22700b57cec5SDimitry Andric       lldb::SBValue *sb_value_ptr =
22710b57cec5SDimitry Andric           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
22720b57cec5SDimitry Andric       if (sb_value_ptr == nullptr)
22730b57cec5SDimitry Andric         Py_XDECREF(child_ptr);
22740b57cec5SDimitry Andric       else
227506c3fb27SDimitry Andric         ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
227606c3fb27SDimitry Andric             sb_value_ptr);
22770b57cec5SDimitry Andric     } else {
22780b57cec5SDimitry Andric       Py_XDECREF(child_ptr);
22790b57cec5SDimitry Andric     }
22800b57cec5SDimitry Andric   }
22810b57cec5SDimitry Andric 
22820b57cec5SDimitry Andric   return ret_val;
22830b57cec5SDimitry Andric }
22840b57cec5SDimitry Andric 
GetSyntheticTypeName(const StructuredData::ObjectSP & implementor_sp)22850b57cec5SDimitry Andric ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
22860b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp) {
22870b57cec5SDimitry Andric   Locker py_lock(this,
22880b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
22890b57cec5SDimitry Andric 
2290bdd1243dSDimitry Andric   if (!implementor_sp)
2291bdd1243dSDimitry Andric     return {};
2292bdd1243dSDimitry Andric 
2293bdd1243dSDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2294bdd1243dSDimitry Andric   if (!generic)
2295bdd1243dSDimitry Andric     return {};
2296bdd1243dSDimitry Andric 
2297bdd1243dSDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
2298bdd1243dSDimitry Andric                            (PyObject *)generic->GetValue());
2299bdd1243dSDimitry Andric   if (!implementor.IsAllocated())
2300bdd1243dSDimitry Andric     return {};
2301bdd1243dSDimitry Andric 
2302bdd1243dSDimitry Andric   llvm::Expected<PythonObject> expected_py_return =
2303bdd1243dSDimitry Andric       implementor.CallMethod("get_type_name");
2304bdd1243dSDimitry Andric 
2305bdd1243dSDimitry Andric   if (!expected_py_return) {
2306bdd1243dSDimitry Andric     llvm::consumeError(expected_py_return.takeError());
2307bdd1243dSDimitry Andric     return {};
2308bdd1243dSDimitry Andric   }
2309bdd1243dSDimitry Andric 
2310bdd1243dSDimitry Andric   PythonObject py_return = std::move(expected_py_return.get());
23115f757f3fSDimitry Andric   if (!py_return.IsAllocated() || !PythonString::Check(py_return.get()))
23125f757f3fSDimitry Andric     return {};
23130b57cec5SDimitry Andric 
23145f757f3fSDimitry Andric   PythonString type_name(PyRefType::Borrowed, py_return.get());
23155f757f3fSDimitry Andric   return ConstString(type_name.GetString());
23160b57cec5SDimitry Andric }
23170b57cec5SDimitry Andric 
RunScriptFormatKeyword(const char * impl_function,Process * process,std::string & output,Status & error)23180b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
23190b57cec5SDimitry Andric     const char *impl_function, Process *process, std::string &output,
23200b57cec5SDimitry Andric     Status &error) {
23210b57cec5SDimitry Andric   bool ret_val;
23220b57cec5SDimitry Andric   if (!process) {
23230b57cec5SDimitry Andric     error.SetErrorString("no process");
23240b57cec5SDimitry Andric     return false;
23250b57cec5SDimitry Andric   }
23260b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
23270b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
23280b57cec5SDimitry Andric     return false;
23290b57cec5SDimitry Andric   }
23300b57cec5SDimitry Andric 
23310b57cec5SDimitry Andric   {
23320b57cec5SDimitry Andric     Locker py_lock(this,
23330b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
233406c3fb27SDimitry Andric     ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordProcess(
23354824e7fdSDimitry Andric         impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
23364824e7fdSDimitry Andric         output);
23370b57cec5SDimitry Andric     if (!ret_val)
23380b57cec5SDimitry Andric       error.SetErrorString("python script evaluation failed");
23390b57cec5SDimitry Andric   }
23400b57cec5SDimitry Andric   return ret_val;
23410b57cec5SDimitry Andric }
23420b57cec5SDimitry Andric 
RunScriptFormatKeyword(const char * impl_function,Thread * thread,std::string & output,Status & error)23430b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
23440b57cec5SDimitry Andric     const char *impl_function, Thread *thread, std::string &output,
23450b57cec5SDimitry Andric     Status &error) {
23460b57cec5SDimitry Andric   if (!thread) {
23470b57cec5SDimitry Andric     error.SetErrorString("no thread");
23480b57cec5SDimitry Andric     return false;
23490b57cec5SDimitry Andric   }
23500b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
23510b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
23520b57cec5SDimitry Andric     return false;
23530b57cec5SDimitry Andric   }
23540b57cec5SDimitry Andric 
23550b57cec5SDimitry Andric   Locker py_lock(this,
23560b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
235706c3fb27SDimitry Andric   if (std::optional<std::string> result =
235806c3fb27SDimitry Andric           SWIGBridge::LLDBSWIGPythonRunScriptKeywordThread(
23590eae32dcSDimitry Andric               impl_function, m_dictionary_name.c_str(),
23600eae32dcSDimitry Andric               thread->shared_from_this())) {
23610eae32dcSDimitry Andric     output = std::move(*result);
23620eae32dcSDimitry Andric     return true;
23630b57cec5SDimitry Andric   }
23640eae32dcSDimitry Andric   error.SetErrorString("python script evaluation failed");
23650eae32dcSDimitry Andric   return false;
23660b57cec5SDimitry Andric }
23670b57cec5SDimitry Andric 
RunScriptFormatKeyword(const char * impl_function,Target * target,std::string & output,Status & error)23680b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
23690b57cec5SDimitry Andric     const char *impl_function, Target *target, std::string &output,
23700b57cec5SDimitry Andric     Status &error) {
23710b57cec5SDimitry Andric   bool ret_val;
23720b57cec5SDimitry Andric   if (!target) {
23730b57cec5SDimitry Andric     error.SetErrorString("no thread");
23740b57cec5SDimitry Andric     return false;
23750b57cec5SDimitry Andric   }
23760b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
23770b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
23780b57cec5SDimitry Andric     return false;
23790b57cec5SDimitry Andric   }
23800b57cec5SDimitry Andric 
23810b57cec5SDimitry Andric   {
23820b57cec5SDimitry Andric     TargetSP target_sp(target->shared_from_this());
23830b57cec5SDimitry Andric     Locker py_lock(this,
23840b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
238506c3fb27SDimitry Andric     ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordTarget(
23860b57cec5SDimitry Andric         impl_function, m_dictionary_name.c_str(), target_sp, output);
23870b57cec5SDimitry Andric     if (!ret_val)
23880b57cec5SDimitry Andric       error.SetErrorString("python script evaluation failed");
23890b57cec5SDimitry Andric   }
23900b57cec5SDimitry Andric   return ret_val;
23910b57cec5SDimitry Andric }
23920b57cec5SDimitry Andric 
RunScriptFormatKeyword(const char * impl_function,StackFrame * frame,std::string & output,Status & error)23930b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
23940b57cec5SDimitry Andric     const char *impl_function, StackFrame *frame, std::string &output,
23950b57cec5SDimitry Andric     Status &error) {
23960b57cec5SDimitry Andric   if (!frame) {
23970b57cec5SDimitry Andric     error.SetErrorString("no frame");
23980b57cec5SDimitry Andric     return false;
23990b57cec5SDimitry Andric   }
24000b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
24010b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
24020b57cec5SDimitry Andric     return false;
24030b57cec5SDimitry Andric   }
24040b57cec5SDimitry Andric 
24050b57cec5SDimitry Andric   Locker py_lock(this,
24060b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
240706c3fb27SDimitry Andric   if (std::optional<std::string> result =
240806c3fb27SDimitry Andric           SWIGBridge::LLDBSWIGPythonRunScriptKeywordFrame(
24090eae32dcSDimitry Andric               impl_function, m_dictionary_name.c_str(),
24100eae32dcSDimitry Andric               frame->shared_from_this())) {
24110eae32dcSDimitry Andric     output = std::move(*result);
24120eae32dcSDimitry Andric     return true;
24130b57cec5SDimitry Andric   }
24140eae32dcSDimitry Andric   error.SetErrorString("python script evaluation failed");
24150eae32dcSDimitry Andric   return false;
24160b57cec5SDimitry Andric }
24170b57cec5SDimitry Andric 
RunScriptFormatKeyword(const char * impl_function,ValueObject * value,std::string & output,Status & error)24180b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
24190b57cec5SDimitry Andric     const char *impl_function, ValueObject *value, std::string &output,
24200b57cec5SDimitry Andric     Status &error) {
24210b57cec5SDimitry Andric   bool ret_val;
24220b57cec5SDimitry Andric   if (!value) {
24230b57cec5SDimitry Andric     error.SetErrorString("no value");
24240b57cec5SDimitry Andric     return false;
24250b57cec5SDimitry Andric   }
24260b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
24270b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
24280b57cec5SDimitry Andric     return false;
24290b57cec5SDimitry Andric   }
24300b57cec5SDimitry Andric 
24310b57cec5SDimitry Andric   {
24320b57cec5SDimitry Andric     Locker py_lock(this,
24330b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
243406c3fb27SDimitry Andric     ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordValue(
24354824e7fdSDimitry Andric         impl_function, m_dictionary_name.c_str(), value->GetSP(), output);
24360b57cec5SDimitry Andric     if (!ret_val)
24370b57cec5SDimitry Andric       error.SetErrorString("python script evaluation failed");
24380b57cec5SDimitry Andric   }
24390b57cec5SDimitry Andric   return ret_val;
24400b57cec5SDimitry Andric }
24410b57cec5SDimitry Andric 
replace_all(std::string & str,const std::string & oldStr,const std::string & newStr)24420b57cec5SDimitry Andric uint64_t replace_all(std::string &str, const std::string &oldStr,
24430b57cec5SDimitry Andric                      const std::string &newStr) {
24440b57cec5SDimitry Andric   size_t pos = 0;
24450b57cec5SDimitry Andric   uint64_t matches = 0;
24460b57cec5SDimitry Andric   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
24470b57cec5SDimitry Andric     matches++;
24480b57cec5SDimitry Andric     str.replace(pos, oldStr.length(), newStr);
24490b57cec5SDimitry Andric     pos += newStr.length();
24500b57cec5SDimitry Andric   }
24510b57cec5SDimitry Andric   return matches;
24520b57cec5SDimitry Andric }
24530b57cec5SDimitry Andric 
LoadScriptingModule(const char * pathname,const LoadScriptOptions & options,lldb_private::Status & error,StructuredData::ObjectSP * module_sp,FileSpec extra_search_dir)24540b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2455fe6060f1SDimitry Andric     const char *pathname, const LoadScriptOptions &options,
2456fe6060f1SDimitry Andric     lldb_private::Status &error, StructuredData::ObjectSP *module_sp,
2457fe6060f1SDimitry Andric     FileSpec extra_search_dir) {
2458e8d8bef9SDimitry Andric   namespace fs = llvm::sys::fs;
2459e8d8bef9SDimitry Andric   namespace path = llvm::sys::path;
2460e8d8bef9SDimitry Andric 
2461fe6060f1SDimitry Andric   ExecuteScriptOptions exc_options = ExecuteScriptOptions()
2462fe6060f1SDimitry Andric                                          .SetEnableIO(!options.GetSilent())
2463fe6060f1SDimitry Andric                                          .SetSetLLDBGlobals(false);
2464fe6060f1SDimitry Andric 
24650b57cec5SDimitry Andric   if (!pathname || !pathname[0]) {
2466fcaf7f86SDimitry Andric     error.SetErrorString("empty path");
24670b57cec5SDimitry Andric     return false;
24680b57cec5SDimitry Andric   }
24690b57cec5SDimitry Andric 
2470fe6060f1SDimitry Andric   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2471fe6060f1SDimitry Andric       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2472fe6060f1SDimitry Andric           exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2473fe6060f1SDimitry Andric 
2474fe6060f1SDimitry Andric   if (!io_redirect_or_error) {
2475fe6060f1SDimitry Andric     error = io_redirect_or_error.takeError();
2476fe6060f1SDimitry Andric     return false;
2477fe6060f1SDimitry Andric   }
2478fe6060f1SDimitry Andric 
2479fe6060f1SDimitry Andric   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
24800b57cec5SDimitry Andric 
24810b57cec5SDimitry Andric   // Before executing Python code, lock the GIL.
24820b57cec5SDimitry Andric   Locker py_lock(this,
24830b57cec5SDimitry Andric                  Locker::AcquireLock |
2484fe6060f1SDimitry Andric                      (options.GetInitSession() ? Locker::InitSession : 0) |
2485fe6060f1SDimitry Andric                      Locker::NoSTDIN,
24860b57cec5SDimitry Andric                  Locker::FreeAcquiredLock |
2487fe6060f1SDimitry Andric                      (options.GetInitSession() ? Locker::TearDownSession : 0),
2488fe6060f1SDimitry Andric                  io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2489fe6060f1SDimitry Andric                  io_redirect.GetErrorFile());
24900b57cec5SDimitry Andric 
2491fe6060f1SDimitry Andric   auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2492e8d8bef9SDimitry Andric     if (directory.empty()) {
2493e8d8bef9SDimitry Andric       return llvm::make_error<llvm::StringError>(
2494e8d8bef9SDimitry Andric           "invalid directory name", llvm::inconvertibleErrorCode());
24950b57cec5SDimitry Andric     }
24960b57cec5SDimitry Andric 
24970b57cec5SDimitry Andric     replace_all(directory, "\\", "\\\\");
24980b57cec5SDimitry Andric     replace_all(directory, "'", "\\'");
24990b57cec5SDimitry Andric 
2500e8d8bef9SDimitry Andric     // Make sure that Python has "directory" in the search path.
25010b57cec5SDimitry Andric     StreamString command_stream;
25020b57cec5SDimitry Andric     command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
25030b57cec5SDimitry Andric                           "sys.path.insert(1,'%s');\n\n",
25040b57cec5SDimitry Andric                           directory.c_str(), directory.c_str());
25050b57cec5SDimitry Andric     bool syspath_retval =
2506fe6060f1SDimitry Andric         ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
25070b57cec5SDimitry Andric     if (!syspath_retval) {
2508e8d8bef9SDimitry Andric       return llvm::make_error<llvm::StringError>(
2509e8d8bef9SDimitry Andric           "Python sys.path handling failed", llvm::inconvertibleErrorCode());
25100b57cec5SDimitry Andric     }
25110b57cec5SDimitry Andric 
2512e8d8bef9SDimitry Andric     return llvm::Error::success();
2513e8d8bef9SDimitry Andric   };
2514e8d8bef9SDimitry Andric 
2515e8d8bef9SDimitry Andric   std::string module_name(pathname);
2516fe6060f1SDimitry Andric   bool possible_package = false;
2517e8d8bef9SDimitry Andric 
2518e8d8bef9SDimitry Andric   if (extra_search_dir) {
2519e8d8bef9SDimitry Andric     if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2520e8d8bef9SDimitry Andric       error = std::move(e);
2521e8d8bef9SDimitry Andric       return false;
25220b57cec5SDimitry Andric     }
25230b57cec5SDimitry Andric   } else {
2524e8d8bef9SDimitry Andric     FileSpec module_file(pathname);
2525e8d8bef9SDimitry Andric     FileSystem::Instance().Resolve(module_file);
2526e8d8bef9SDimitry Andric 
2527e8d8bef9SDimitry Andric     fs::file_status st;
2528e8d8bef9SDimitry Andric     std::error_code ec = status(module_file.GetPath(), st);
2529e8d8bef9SDimitry Andric 
2530e8d8bef9SDimitry Andric     if (ec || st.type() == fs::file_type::status_error ||
2531e8d8bef9SDimitry Andric         st.type() == fs::file_type::type_unknown ||
2532e8d8bef9SDimitry Andric         st.type() == fs::file_type::file_not_found) {
2533e8d8bef9SDimitry Andric       // if not a valid file of any sort, check if it might be a filename still
2534e8d8bef9SDimitry Andric       // dot can't be used but / and \ can, and if either is found, reject
2535e8d8bef9SDimitry Andric       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2536fcaf7f86SDimitry Andric         error.SetErrorStringWithFormatv("invalid pathname '{0}'", pathname);
2537e8d8bef9SDimitry Andric         return false;
2538e8d8bef9SDimitry Andric       }
2539e8d8bef9SDimitry Andric       // Not a filename, probably a package of some sort, let it go through.
2540fe6060f1SDimitry Andric       possible_package = true;
2541e8d8bef9SDimitry Andric     } else if (is_directory(st) || is_regular_file(st)) {
2542e8d8bef9SDimitry Andric       if (module_file.GetDirectory().IsEmpty()) {
2543fcaf7f86SDimitry Andric         error.SetErrorStringWithFormatv("invalid directory name '{0}'", pathname);
2544e8d8bef9SDimitry Andric         return false;
2545e8d8bef9SDimitry Andric       }
2546e8d8bef9SDimitry Andric       if (llvm::Error e =
2547e8d8bef9SDimitry Andric               ExtendSysPath(module_file.GetDirectory().GetCString())) {
2548e8d8bef9SDimitry Andric         error = std::move(e);
2549e8d8bef9SDimitry Andric         return false;
2550e8d8bef9SDimitry Andric       }
2551e8d8bef9SDimitry Andric       module_name = module_file.GetFilename().GetCString();
2552e8d8bef9SDimitry Andric     } else {
25530b57cec5SDimitry Andric       error.SetErrorString("no known way to import this module specification");
25540b57cec5SDimitry Andric       return false;
25550b57cec5SDimitry Andric     }
2556e8d8bef9SDimitry Andric   }
2557e8d8bef9SDimitry Andric 
2558e8d8bef9SDimitry Andric   // Strip .py or .pyc extension
2559e8d8bef9SDimitry Andric   llvm::StringRef extension = llvm::sys::path::extension(module_name);
2560e8d8bef9SDimitry Andric   if (!extension.empty()) {
2561e8d8bef9SDimitry Andric     if (extension == ".py")
2562e8d8bef9SDimitry Andric       module_name.resize(module_name.length() - 3);
2563e8d8bef9SDimitry Andric     else if (extension == ".pyc")
2564e8d8bef9SDimitry Andric       module_name.resize(module_name.length() - 4);
2565e8d8bef9SDimitry Andric   }
25660b57cec5SDimitry Andric 
2567fe6060f1SDimitry Andric   if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2568fe6060f1SDimitry Andric     error.SetErrorStringWithFormat(
2569fe6060f1SDimitry Andric         "Python does not allow dots in module names: %s", module_name.c_str());
2570fe6060f1SDimitry Andric     return false;
2571fe6060f1SDimitry Andric   }
2572fe6060f1SDimitry Andric 
2573fe6060f1SDimitry Andric   if (module_name.find('-') != llvm::StringRef::npos) {
2574fe6060f1SDimitry Andric     error.SetErrorStringWithFormat(
2575fe6060f1SDimitry Andric         "Python discourages dashes in module names: %s", module_name.c_str());
2576fe6060f1SDimitry Andric     return false;
2577fe6060f1SDimitry Andric   }
2578fe6060f1SDimitry Andric 
2579fe6060f1SDimitry Andric   // Check if the module is already imported.
2580e8d8bef9SDimitry Andric   StreamString command_stream;
25810b57cec5SDimitry Andric   command_stream.Clear();
2582e8d8bef9SDimitry Andric   command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
25830b57cec5SDimitry Andric   bool does_contain = false;
2584fe6060f1SDimitry Andric   // This call will succeed if the module was ever imported in any Debugger in
2585fe6060f1SDimitry Andric   // the lifetime of the process in which this LLDB framework is living.
2586fe6060f1SDimitry Andric   const bool does_contain_executed = ExecuteOneLineWithReturn(
25870b57cec5SDimitry Andric       command_stream.GetData(),
2588fe6060f1SDimitry Andric       ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options);
2589fe6060f1SDimitry Andric 
2590fe6060f1SDimitry Andric   const bool was_imported_globally = does_contain_executed && does_contain;
2591fe6060f1SDimitry Andric   const bool was_imported_locally =
2592fe6060f1SDimitry Andric       GetSessionDictionary()
2593e8d8bef9SDimitry Andric           .GetItemForKey(PythonString(module_name))
25940b57cec5SDimitry Andric           .IsAllocated();
25950b57cec5SDimitry Andric 
25960b57cec5SDimitry Andric   // now actually do the import
25970b57cec5SDimitry Andric   command_stream.Clear();
25980b57cec5SDimitry Andric 
2599fe6060f1SDimitry Andric   if (was_imported_globally || was_imported_locally) {
26000b57cec5SDimitry Andric     if (!was_imported_locally)
2601e8d8bef9SDimitry Andric       command_stream.Printf("import %s ; reload_module(%s)",
2602e8d8bef9SDimitry Andric                             module_name.c_str(), module_name.c_str());
26030b57cec5SDimitry Andric     else
2604e8d8bef9SDimitry Andric       command_stream.Printf("reload_module(%s)", module_name.c_str());
26050b57cec5SDimitry Andric   } else
2606e8d8bef9SDimitry Andric     command_stream.Printf("import %s", module_name.c_str());
26070b57cec5SDimitry Andric 
2608fe6060f1SDimitry Andric   error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
26090b57cec5SDimitry Andric   if (error.Fail())
26100b57cec5SDimitry Andric     return false;
26110b57cec5SDimitry Andric 
26120b57cec5SDimitry Andric   // if we are here, everything worked
26130b57cec5SDimitry Andric   // call __lldb_init_module(debugger,dict)
261406c3fb27SDimitry Andric   if (!SWIGBridge::LLDBSwigPythonCallModuleInit(
261506c3fb27SDimitry Andric           module_name.c_str(), m_dictionary_name.c_str(),
26160eae32dcSDimitry Andric           m_debugger.shared_from_this())) {
26170b57cec5SDimitry Andric     error.SetErrorString("calling __lldb_init_module failed");
26180b57cec5SDimitry Andric     return false;
26190b57cec5SDimitry Andric   }
26200b57cec5SDimitry Andric 
26210b57cec5SDimitry Andric   if (module_sp) {
26220b57cec5SDimitry Andric     // everything went just great, now set the module object
26230b57cec5SDimitry Andric     command_stream.Clear();
2624e8d8bef9SDimitry Andric     command_stream.Printf("%s", module_name.c_str());
26250b57cec5SDimitry Andric     void *module_pyobj = nullptr;
26260b57cec5SDimitry Andric     if (ExecuteOneLineWithReturn(
26270b57cec5SDimitry Andric             command_stream.GetData(),
2628fe6060f1SDimitry Andric             ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2629fe6060f1SDimitry Andric             exc_options) &&
26300b57cec5SDimitry Andric         module_pyobj)
263104eeddc0SDimitry Andric       *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
263204eeddc0SDimitry Andric           PyRefType::Owned, static_cast<PyObject *>(module_pyobj)));
26330b57cec5SDimitry Andric   }
26340b57cec5SDimitry Andric 
26350b57cec5SDimitry Andric   return true;
26360b57cec5SDimitry Andric }
26370b57cec5SDimitry Andric 
IsReservedWord(const char * word)26380b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
26390b57cec5SDimitry Andric   if (!word || !word[0])
26400b57cec5SDimitry Andric     return false;
26410b57cec5SDimitry Andric 
26420b57cec5SDimitry Andric   llvm::StringRef word_sr(word);
26430b57cec5SDimitry Andric 
26440b57cec5SDimitry Andric   // filter out a few characters that would just confuse us and that are
26450b57cec5SDimitry Andric   // clearly not keyword material anyway
26460b57cec5SDimitry Andric   if (word_sr.find('"') != llvm::StringRef::npos ||
26470b57cec5SDimitry Andric       word_sr.find('\'') != llvm::StringRef::npos)
26480b57cec5SDimitry Andric     return false;
26490b57cec5SDimitry Andric 
26500b57cec5SDimitry Andric   StreamString command_stream;
26510b57cec5SDimitry Andric   command_stream.Printf("keyword.iskeyword('%s')", word);
26520b57cec5SDimitry Andric   bool result;
26530b57cec5SDimitry Andric   ExecuteScriptOptions options;
26540b57cec5SDimitry Andric   options.SetEnableIO(false);
26550b57cec5SDimitry Andric   options.SetMaskoutErrors(true);
26560b57cec5SDimitry Andric   options.SetSetLLDBGlobals(false);
26570b57cec5SDimitry Andric   if (ExecuteOneLineWithReturn(command_stream.GetData(),
26580b57cec5SDimitry Andric                                ScriptInterpreter::eScriptReturnTypeBool,
26590b57cec5SDimitry Andric                                &result, options))
26600b57cec5SDimitry Andric     return result;
26610b57cec5SDimitry Andric   return false;
26620b57cec5SDimitry Andric }
26630b57cec5SDimitry Andric 
SynchronicityHandler(lldb::DebuggerSP debugger_sp,ScriptedCommandSynchronicity synchro)26640b57cec5SDimitry Andric ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
26650b57cec5SDimitry Andric     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
26660b57cec5SDimitry Andric     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
26670b57cec5SDimitry Andric       m_old_asynch(debugger_sp->GetAsyncExecution()) {
26680b57cec5SDimitry Andric   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
26690b57cec5SDimitry Andric     m_debugger_sp->SetAsyncExecution(false);
26700b57cec5SDimitry Andric   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
26710b57cec5SDimitry Andric     m_debugger_sp->SetAsyncExecution(true);
26720b57cec5SDimitry Andric }
26730b57cec5SDimitry Andric 
~SynchronicityHandler()26740b57cec5SDimitry Andric ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
26750b57cec5SDimitry Andric   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
26760b57cec5SDimitry Andric     m_debugger_sp->SetAsyncExecution(m_old_asynch);
26770b57cec5SDimitry Andric }
26780b57cec5SDimitry Andric 
RunScriptBasedCommand(const char * impl_function,llvm::StringRef args,ScriptedCommandSynchronicity synchronicity,lldb_private::CommandReturnObject & cmd_retobj,Status & error,const lldb_private::ExecutionContext & exe_ctx)26790b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
26800b57cec5SDimitry Andric     const char *impl_function, llvm::StringRef args,
26810b57cec5SDimitry Andric     ScriptedCommandSynchronicity synchronicity,
26820b57cec5SDimitry Andric     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
26830b57cec5SDimitry Andric     const lldb_private::ExecutionContext &exe_ctx) {
26840b57cec5SDimitry Andric   if (!impl_function) {
26850b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
26860b57cec5SDimitry Andric     return false;
26870b57cec5SDimitry Andric   }
26880b57cec5SDimitry Andric 
26890b57cec5SDimitry Andric   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
26900b57cec5SDimitry Andric   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
26910b57cec5SDimitry Andric 
26920b57cec5SDimitry Andric   if (!debugger_sp.get()) {
26930b57cec5SDimitry Andric     error.SetErrorString("invalid Debugger pointer");
26940b57cec5SDimitry Andric     return false;
26950b57cec5SDimitry Andric   }
26960b57cec5SDimitry Andric 
26970b57cec5SDimitry Andric   bool ret_val = false;
26980b57cec5SDimitry Andric 
26990b57cec5SDimitry Andric   std::string err_msg;
27000b57cec5SDimitry Andric 
27010b57cec5SDimitry Andric   {
27020b57cec5SDimitry Andric     Locker py_lock(this,
27030b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession |
27040b57cec5SDimitry Andric                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
27050b57cec5SDimitry Andric                    Locker::FreeLock | Locker::TearDownSession);
27060b57cec5SDimitry Andric 
27070b57cec5SDimitry Andric     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
27080b57cec5SDimitry Andric 
27090b57cec5SDimitry Andric     std::string args_str = args.str();
271006c3fb27SDimitry Andric     ret_val = SWIGBridge::LLDBSwigPythonCallCommand(
27110b57cec5SDimitry Andric         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
27120b57cec5SDimitry Andric         cmd_retobj, exe_ctx_ref_sp);
27130b57cec5SDimitry Andric   }
27140b57cec5SDimitry Andric 
27150b57cec5SDimitry Andric   if (!ret_val)
27160b57cec5SDimitry Andric     error.SetErrorString("unable to execute script function");
2717bdd1243dSDimitry Andric   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2718bdd1243dSDimitry Andric     return false;
27190b57cec5SDimitry Andric 
2720bdd1243dSDimitry Andric   error.Clear();
27210b57cec5SDimitry Andric   return ret_val;
27220b57cec5SDimitry Andric }
27230b57cec5SDimitry Andric 
RunScriptBasedCommand(StructuredData::GenericSP impl_obj_sp,llvm::StringRef args,ScriptedCommandSynchronicity synchronicity,lldb_private::CommandReturnObject & cmd_retobj,Status & error,const lldb_private::ExecutionContext & exe_ctx)27240b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
27250b57cec5SDimitry Andric     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
27260b57cec5SDimitry Andric     ScriptedCommandSynchronicity synchronicity,
27270b57cec5SDimitry Andric     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
27280b57cec5SDimitry Andric     const lldb_private::ExecutionContext &exe_ctx) {
27290b57cec5SDimitry Andric   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
27300b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
27310b57cec5SDimitry Andric     return false;
27320b57cec5SDimitry Andric   }
27330b57cec5SDimitry Andric 
27340b57cec5SDimitry Andric   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
27350b57cec5SDimitry Andric   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
27360b57cec5SDimitry Andric 
27370b57cec5SDimitry Andric   if (!debugger_sp.get()) {
27380b57cec5SDimitry Andric     error.SetErrorString("invalid Debugger pointer");
27390b57cec5SDimitry Andric     return false;
27400b57cec5SDimitry Andric   }
27410b57cec5SDimitry Andric 
27420b57cec5SDimitry Andric   bool ret_val = false;
27430b57cec5SDimitry Andric 
27440b57cec5SDimitry Andric   std::string err_msg;
27450b57cec5SDimitry Andric 
27460b57cec5SDimitry Andric   {
27470b57cec5SDimitry Andric     Locker py_lock(this,
27480b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession |
27490b57cec5SDimitry Andric                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
27500b57cec5SDimitry Andric                    Locker::FreeLock | Locker::TearDownSession);
27510b57cec5SDimitry Andric 
27520b57cec5SDimitry Andric     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
27530b57cec5SDimitry Andric 
27540b57cec5SDimitry Andric     std::string args_str = args.str();
275506c3fb27SDimitry Andric     ret_val = SWIGBridge::LLDBSwigPythonCallCommandObject(
27564824e7fdSDimitry Andric         static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
27574824e7fdSDimitry Andric         args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
27580b57cec5SDimitry Andric   }
27590b57cec5SDimitry Andric 
27600b57cec5SDimitry Andric   if (!ret_val)
27610b57cec5SDimitry Andric     error.SetErrorString("unable to execute script function");
2762bdd1243dSDimitry Andric   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2763bdd1243dSDimitry Andric     return false;
27640b57cec5SDimitry Andric 
2765bdd1243dSDimitry Andric   error.Clear();
27660b57cec5SDimitry Andric   return ret_val;
27670b57cec5SDimitry Andric }
27680b57cec5SDimitry Andric 
27695ffd83dbSDimitry Andric /// In Python, a special attribute __doc__ contains the docstring for an object
27705ffd83dbSDimitry Andric /// (function, method, class, ...) if any is defined Otherwise, the attribute's
27715ffd83dbSDimitry Andric /// value is None.
GetDocumentationForItem(const char * item,std::string & dest)27720b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
27730b57cec5SDimitry Andric                                                           std::string &dest) {
27740b57cec5SDimitry Andric   dest.clear();
27755ffd83dbSDimitry Andric 
27760b57cec5SDimitry Andric   if (!item || !*item)
27770b57cec5SDimitry Andric     return false;
27785ffd83dbSDimitry Andric 
27790b57cec5SDimitry Andric   std::string command(item);
27800b57cec5SDimitry Andric   command += ".__doc__";
27810b57cec5SDimitry Andric 
27825ffd83dbSDimitry Andric   // Python is going to point this to valid data if ExecuteOneLineWithReturn
27835ffd83dbSDimitry Andric   // returns successfully.
27845ffd83dbSDimitry Andric   char *result_ptr = nullptr;
27850b57cec5SDimitry Andric 
27860b57cec5SDimitry Andric   if (ExecuteOneLineWithReturn(
27875ffd83dbSDimitry Andric           command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
27880b57cec5SDimitry Andric           &result_ptr,
2789fe6060f1SDimitry Andric           ExecuteScriptOptions().SetEnableIO(false))) {
27900b57cec5SDimitry Andric     if (result_ptr)
27910b57cec5SDimitry Andric       dest.assign(result_ptr);
27920b57cec5SDimitry Andric     return true;
27930b57cec5SDimitry Andric   }
27945ffd83dbSDimitry Andric 
27955ffd83dbSDimitry Andric   StreamString str_stream;
27965ffd83dbSDimitry Andric   str_stream << "Function " << item
27975ffd83dbSDimitry Andric              << " was not found. Containing module might be missing.";
27985ffd83dbSDimitry Andric   dest = std::string(str_stream.GetString());
27995ffd83dbSDimitry Andric 
28005ffd83dbSDimitry Andric   return false;
28010b57cec5SDimitry Andric }
28020b57cec5SDimitry Andric 
GetShortHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp,std::string & dest)28030b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
28040b57cec5SDimitry Andric     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
28050b57cec5SDimitry Andric   dest.clear();
28060b57cec5SDimitry Andric 
28070b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
28080b57cec5SDimitry Andric 
28090b57cec5SDimitry Andric   if (!cmd_obj_sp)
28100b57cec5SDimitry Andric     return false;
28110b57cec5SDimitry Andric 
28120b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
28130b57cec5SDimitry Andric                            (PyObject *)cmd_obj_sp->GetValue());
28140b57cec5SDimitry Andric 
28150b57cec5SDimitry Andric   if (!implementor.IsAllocated())
28160b57cec5SDimitry Andric     return false;
28170b57cec5SDimitry Andric 
2818bdd1243dSDimitry Andric   llvm::Expected<PythonObject> expected_py_return =
2819bdd1243dSDimitry Andric       implementor.CallMethod("get_short_help");
28200b57cec5SDimitry Andric 
2821bdd1243dSDimitry Andric   if (!expected_py_return) {
2822bdd1243dSDimitry Andric     llvm::consumeError(expected_py_return.takeError());
28230b57cec5SDimitry Andric     return false;
28240b57cec5SDimitry Andric   }
28250b57cec5SDimitry Andric 
2826bdd1243dSDimitry Andric   PythonObject py_return = std::move(expected_py_return.get());
28270b57cec5SDimitry Andric 
28280b57cec5SDimitry Andric   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
28290b57cec5SDimitry Andric     PythonString py_string(PyRefType::Borrowed, py_return.get());
28300b57cec5SDimitry Andric     llvm::StringRef return_data(py_string.GetString());
28310b57cec5SDimitry Andric     dest.assign(return_data.data(), return_data.size());
28325ffd83dbSDimitry Andric     return true;
28330b57cec5SDimitry Andric   }
28345ffd83dbSDimitry Andric 
28355ffd83dbSDimitry Andric   return false;
28360b57cec5SDimitry Andric }
28370b57cec5SDimitry Andric 
GetFlagsForCommandObject(StructuredData::GenericSP cmd_obj_sp)28380b57cec5SDimitry Andric uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
28390b57cec5SDimitry Andric     StructuredData::GenericSP cmd_obj_sp) {
28400b57cec5SDimitry Andric   uint32_t result = 0;
28410b57cec5SDimitry Andric 
28420b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
28430b57cec5SDimitry Andric 
28440b57cec5SDimitry Andric   static char callee_name[] = "get_flags";
28450b57cec5SDimitry Andric 
28460b57cec5SDimitry Andric   if (!cmd_obj_sp)
28470b57cec5SDimitry Andric     return result;
28480b57cec5SDimitry Andric 
28490b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
28500b57cec5SDimitry Andric                            (PyObject *)cmd_obj_sp->GetValue());
28510b57cec5SDimitry Andric 
28520b57cec5SDimitry Andric   if (!implementor.IsAllocated())
28530b57cec5SDimitry Andric     return result;
28540b57cec5SDimitry Andric 
28550b57cec5SDimitry Andric   PythonObject pmeth(PyRefType::Owned,
28560b57cec5SDimitry Andric                      PyObject_GetAttrString(implementor.get(), callee_name));
28570b57cec5SDimitry Andric 
28580b57cec5SDimitry Andric   if (PyErr_Occurred())
28590b57cec5SDimitry Andric     PyErr_Clear();
28600b57cec5SDimitry Andric 
28610b57cec5SDimitry Andric   if (!pmeth.IsAllocated())
28620b57cec5SDimitry Andric     return result;
28630b57cec5SDimitry Andric 
28640b57cec5SDimitry Andric   if (PyCallable_Check(pmeth.get()) == 0) {
28650b57cec5SDimitry Andric     if (PyErr_Occurred())
28660b57cec5SDimitry Andric       PyErr_Clear();
28670b57cec5SDimitry Andric     return result;
28680b57cec5SDimitry Andric   }
28690b57cec5SDimitry Andric 
28700b57cec5SDimitry Andric   if (PyErr_Occurred())
28710b57cec5SDimitry Andric     PyErr_Clear();
28720b57cec5SDimitry Andric 
28735ffd83dbSDimitry Andric   long long py_return = unwrapOrSetPythonException(
28745ffd83dbSDimitry Andric       As<long long>(implementor.CallMethod(callee_name)));
28750b57cec5SDimitry Andric 
28760b57cec5SDimitry Andric   // if it fails, print the error but otherwise go on
28770b57cec5SDimitry Andric   if (PyErr_Occurred()) {
28780b57cec5SDimitry Andric     PyErr_Print();
28790b57cec5SDimitry Andric     PyErr_Clear();
28805ffd83dbSDimitry Andric   } else {
28815ffd83dbSDimitry Andric     result = py_return;
28820b57cec5SDimitry Andric   }
28830b57cec5SDimitry Andric 
28840b57cec5SDimitry Andric   return result;
28850b57cec5SDimitry Andric }
28860b57cec5SDimitry Andric 
GetLongHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp,std::string & dest)28870b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
28880b57cec5SDimitry Andric     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
28890b57cec5SDimitry Andric   dest.clear();
28900b57cec5SDimitry Andric 
28910b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
28920b57cec5SDimitry Andric 
28930b57cec5SDimitry Andric   if (!cmd_obj_sp)
28940b57cec5SDimitry Andric     return false;
28950b57cec5SDimitry Andric 
28960b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
28970b57cec5SDimitry Andric                            (PyObject *)cmd_obj_sp->GetValue());
28980b57cec5SDimitry Andric 
28990b57cec5SDimitry Andric   if (!implementor.IsAllocated())
29000b57cec5SDimitry Andric     return false;
29010b57cec5SDimitry Andric 
2902bdd1243dSDimitry Andric   llvm::Expected<PythonObject> expected_py_return =
2903bdd1243dSDimitry Andric       implementor.CallMethod("get_long_help");
29040b57cec5SDimitry Andric 
2905bdd1243dSDimitry Andric   if (!expected_py_return) {
2906bdd1243dSDimitry Andric     llvm::consumeError(expected_py_return.takeError());
29070b57cec5SDimitry Andric     return false;
29080b57cec5SDimitry Andric   }
29090b57cec5SDimitry Andric 
2910bdd1243dSDimitry Andric   PythonObject py_return = std::move(expected_py_return.get());
29110b57cec5SDimitry Andric 
2912bdd1243dSDimitry Andric   bool got_string = false;
29130b57cec5SDimitry Andric   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
29140b57cec5SDimitry Andric     PythonString str(PyRefType::Borrowed, py_return.get());
29150b57cec5SDimitry Andric     llvm::StringRef str_data(str.GetString());
29160b57cec5SDimitry Andric     dest.assign(str_data.data(), str_data.size());
29170b57cec5SDimitry Andric     got_string = true;
29180b57cec5SDimitry Andric   }
29190b57cec5SDimitry Andric 
29200b57cec5SDimitry Andric   return got_string;
29210b57cec5SDimitry Andric }
29220b57cec5SDimitry Andric 
29230b57cec5SDimitry Andric std::unique_ptr<ScriptInterpreterLocker>
AcquireInterpreterLock()29240b57cec5SDimitry Andric ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
29250b57cec5SDimitry Andric   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
29260b57cec5SDimitry Andric       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
29270b57cec5SDimitry Andric       Locker::FreeLock | Locker::TearDownSession));
29280b57cec5SDimitry Andric   return py_lock;
29290b57cec5SDimitry Andric }
29300b57cec5SDimitry Andric 
Initialize()293104eeddc0SDimitry Andric void ScriptInterpreterPythonImpl::Initialize() {
2932e8d8bef9SDimitry Andric   LLDB_SCOPED_TIMER();
29330b57cec5SDimitry Andric 
29340b57cec5SDimitry Andric   // RAII-based initialization which correctly handles multiple-initialization,
29350b57cec5SDimitry Andric   // version- specific differences among Python 2 and Python 3, and saving and
29360b57cec5SDimitry Andric   // restoring various other pieces of state that can get mucked with during
29370b57cec5SDimitry Andric   // initialization.
29380b57cec5SDimitry Andric   InitializePythonRAII initialize_guard;
29390b57cec5SDimitry Andric 
29400b57cec5SDimitry Andric   LLDBSwigPyInit();
29410b57cec5SDimitry Andric 
29420b57cec5SDimitry Andric   // Update the path python uses to search for modules to include the current
29430b57cec5SDimitry Andric   // directory.
29440b57cec5SDimitry Andric 
29450b57cec5SDimitry Andric   PyRun_SimpleString("import sys");
29460b57cec5SDimitry Andric   AddToSysPath(AddLocation::End, ".");
29470b57cec5SDimitry Andric 
29480b57cec5SDimitry Andric   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
29490b57cec5SDimitry Andric   // that use a backslash as the path separator, this will result in executing
29500b57cec5SDimitry Andric   // python code containing paths with unescaped backslashes.  But Python also
29510b57cec5SDimitry Andric   // accepts forward slashes, so to make life easier we just use that.
29520b57cec5SDimitry Andric   if (FileSpec file_spec = GetPythonDir())
29530b57cec5SDimitry Andric     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
29540b57cec5SDimitry Andric   if (FileSpec file_spec = HostInfo::GetShlibDir())
29550b57cec5SDimitry Andric     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
29560b57cec5SDimitry Andric 
29570b57cec5SDimitry Andric   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
29580b57cec5SDimitry Andric                      "lldb.embedded_interpreter; from "
29590b57cec5SDimitry Andric                      "lldb.embedded_interpreter import run_python_interpreter; "
29600b57cec5SDimitry Andric                      "from lldb.embedded_interpreter import run_one_line");
296104eeddc0SDimitry Andric 
296204eeddc0SDimitry Andric #if LLDB_USE_PYTHON_SET_INTERRUPT
296304eeddc0SDimitry Andric   // Python will not just overwrite its internal SIGINT handler but also the
296404eeddc0SDimitry Andric   // one from the process. Backup the current SIGINT handler to prevent that
296504eeddc0SDimitry Andric   // Python deletes it.
296604eeddc0SDimitry Andric   RestoreSignalHandlerScope save_sigint(SIGINT);
296704eeddc0SDimitry Andric 
296804eeddc0SDimitry Andric   // Setup a default SIGINT signal handler that works the same way as the
296904eeddc0SDimitry Andric   // normal Python REPL signal handler which raises a KeyboardInterrupt.
297004eeddc0SDimitry Andric   // Also make sure to not pollute the user's REPL with the signal module nor
297104eeddc0SDimitry Andric   // our utility function.
297204eeddc0SDimitry Andric   PyRun_SimpleString("def lldb_setup_sigint_handler():\n"
297304eeddc0SDimitry Andric                      "  import signal;\n"
297404eeddc0SDimitry Andric                      "  def signal_handler(sig, frame):\n"
297504eeddc0SDimitry Andric                      "    raise KeyboardInterrupt()\n"
297604eeddc0SDimitry Andric                      "  signal.signal(signal.SIGINT, signal_handler);\n"
297704eeddc0SDimitry Andric                      "lldb_setup_sigint_handler();\n"
297804eeddc0SDimitry Andric                      "del lldb_setup_sigint_handler\n");
297904eeddc0SDimitry Andric #endif
29800b57cec5SDimitry Andric }
29810b57cec5SDimitry Andric 
AddToSysPath(AddLocation location,std::string path)29820b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
29830b57cec5SDimitry Andric                                                std::string path) {
29840b57cec5SDimitry Andric   std::string path_copy;
29850b57cec5SDimitry Andric 
29860b57cec5SDimitry Andric   std::string statement;
29870b57cec5SDimitry Andric   if (location == AddLocation::Beginning) {
29880b57cec5SDimitry Andric     statement.assign("sys.path.insert(0,\"");
29890b57cec5SDimitry Andric     statement.append(path);
29900b57cec5SDimitry Andric     statement.append("\")");
29910b57cec5SDimitry Andric   } else {
29920b57cec5SDimitry Andric     statement.assign("sys.path.append(\"");
29930b57cec5SDimitry Andric     statement.append(path);
29940b57cec5SDimitry Andric     statement.append("\")");
29950b57cec5SDimitry Andric   }
29960b57cec5SDimitry Andric   PyRun_SimpleString(statement.c_str());
29970b57cec5SDimitry Andric }
29980b57cec5SDimitry Andric 
29990b57cec5SDimitry Andric // We are intentionally NOT calling Py_Finalize here (this would be the logical
30000b57cec5SDimitry Andric // place to call it).  Calling Py_Finalize here causes test suite runs to seg
30010b57cec5SDimitry Andric // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
30020b57cec5SDimitry Andric // be called 'at_exit'.  When the test suite Python harness finishes up, it
30030b57cec5SDimitry Andric // calls Py_Finalize, which calls all the 'at_exit' registered functions.
30040b57cec5SDimitry Andric // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
30050b57cec5SDimitry Andric // which calls ScriptInterpreter::Terminate, which calls
30060b57cec5SDimitry Andric // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
30070b57cec5SDimitry Andric // end up with Py_Finalize being called from within Py_Finalize, which results
30080b57cec5SDimitry Andric // in a seg fault. Since this function only gets called when lldb is shutting
30090b57cec5SDimitry Andric // down and going away anyway, the fact that we don't actually call Py_Finalize
30100b57cec5SDimitry Andric // should not cause any problems (everything should shut down/go away anyway
30110b57cec5SDimitry Andric // when the process exits).
30120b57cec5SDimitry Andric //
30130b57cec5SDimitry Andric // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
30140b57cec5SDimitry Andric 
3015480093f4SDimitry Andric #endif
3016