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"
20*0fca6ea1SDimitry Andric #include "Interfaces/ScriptedThreadPlanPythonInterface.h"
215f757f3fSDimitry Andric #include "Interfaces/ScriptedThreadPythonInterface.h"
220b57cec5SDimitry Andric #include "PythonDataObjects.h"
23c14a5a88SDimitry Andric #include "PythonReadline.h"
24fe6060f1SDimitry Andric #include "SWIGPythonBridge.h"
250b57cec5SDimitry Andric #include "ScriptInterpreterPythonImpl.h"
26fe6060f1SDimitry Andric 
27fe6060f1SDimitry Andric #include "lldb/API/SBError.h"
28*0fca6ea1SDimitry Andric #include "lldb/API/SBExecutionContext.h"
290b57cec5SDimitry Andric #include "lldb/API/SBFrame.h"
300b57cec5SDimitry Andric #include "lldb/API/SBValue.h"
310b57cec5SDimitry Andric #include "lldb/Breakpoint/StoppointCallbackContext.h"
320b57cec5SDimitry Andric #include "lldb/Breakpoint/WatchpointOptions.h"
330b57cec5SDimitry Andric #include "lldb/Core/Debugger.h"
340b57cec5SDimitry Andric #include "lldb/Core/PluginManager.h"
35bdd1243dSDimitry Andric #include "lldb/Core/ThreadedCommunication.h"
360b57cec5SDimitry Andric #include "lldb/Core/ValueObject.h"
370b57cec5SDimitry Andric #include "lldb/DataFormatters/TypeSummary.h"
380b57cec5SDimitry Andric #include "lldb/Host/FileSystem.h"
390b57cec5SDimitry Andric #include "lldb/Host/HostInfo.h"
400b57cec5SDimitry Andric #include "lldb/Host/Pipe.h"
410b57cec5SDimitry Andric #include "lldb/Interpreter/CommandInterpreter.h"
420b57cec5SDimitry Andric #include "lldb/Interpreter/CommandReturnObject.h"
430b57cec5SDimitry Andric #include "lldb/Target/Thread.h"
440b57cec5SDimitry Andric #include "lldb/Target/ThreadPlan.h"
4504eeddc0SDimitry Andric #include "lldb/Utility/Instrumentation.h"
4681ad6265SDimitry Andric #include "lldb/Utility/LLDBLog.h"
470b57cec5SDimitry Andric #include "lldb/Utility/Timer.h"
480b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
490b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
505ffd83dbSDimitry Andric #include "llvm/Support/Error.h"
510b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
529dba64beSDimitry Andric #include "llvm/Support/FormatAdapters.h"
530b57cec5SDimitry Andric 
54fe6060f1SDimitry Andric #include <cstdio>
55fe6060f1SDimitry Andric #include <cstdlib>
560b57cec5SDimitry Andric #include <memory>
570b57cec5SDimitry Andric #include <mutex>
58bdd1243dSDimitry Andric #include <optional>
590b57cec5SDimitry Andric #include <string>
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric using namespace lldb;
620b57cec5SDimitry Andric using namespace lldb_private;
639dba64beSDimitry Andric using namespace lldb_private::python;
649dba64beSDimitry Andric using llvm::Expected;
650b57cec5SDimitry Andric 
665ffd83dbSDimitry Andric LLDB_PLUGIN_DEFINE(ScriptInterpreterPython)
675ffd83dbSDimitry Andric 
680b57cec5SDimitry Andric // Defined in the SWIG source file
690b57cec5SDimitry Andric extern "C" PyObject *PyInit__lldb(void);
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric #define LLDBSwigPyInit PyInit__lldb
720b57cec5SDimitry Andric 
7304eeddc0SDimitry Andric #if defined(_WIN32)
7404eeddc0SDimitry Andric // Don't mess with the signal handlers on Windows.
7504eeddc0SDimitry Andric #define LLDB_USE_PYTHON_SET_INTERRUPT 0
7604eeddc0SDimitry Andric #else
7704eeddc0SDimitry Andric // PyErr_SetInterrupt was introduced in 3.2.
7804eeddc0SDimitry Andric #define LLDB_USE_PYTHON_SET_INTERRUPT                                          \
7904eeddc0SDimitry Andric   (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
8004eeddc0SDimitry Andric #endif
810b57cec5SDimitry Andric 
82e8d8bef9SDimitry Andric static ScriptInterpreterPythonImpl *GetPythonInterpreter(Debugger &debugger) {
83e8d8bef9SDimitry Andric   ScriptInterpreter *script_interpreter =
84e8d8bef9SDimitry Andric       debugger.GetScriptInterpreter(true, lldb::eScriptLanguagePython);
85e8d8bef9SDimitry Andric   return static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
86e8d8bef9SDimitry Andric }
87e8d8bef9SDimitry Andric 
880b57cec5SDimitry Andric namespace {
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric // Initializing Python is not a straightforward process.  We cannot control
910b57cec5SDimitry Andric // what external code may have done before getting to this point in LLDB,
920b57cec5SDimitry Andric // including potentially having already initialized Python, so we need to do a
930b57cec5SDimitry Andric // lot of work to ensure that the existing state of the system is maintained
940b57cec5SDimitry Andric // across our initialization.  We do this by using an RAII pattern where we
950b57cec5SDimitry Andric // save off initial state at the beginning, and restore it at the end
960b57cec5SDimitry Andric struct InitializePythonRAII {
970b57cec5SDimitry Andric public:
98fe6060f1SDimitry Andric   InitializePythonRAII() {
990b57cec5SDimitry Andric     InitializePythonHome();
1000b57cec5SDimitry Andric 
101*0fca6ea1SDimitry Andric     // The table of built-in modules can only be extended before Python is
102*0fca6ea1SDimitry Andric     // initialized.
103*0fca6ea1SDimitry Andric     if (!Py_IsInitialized()) {
104c14a5a88SDimitry Andric #ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
105c14a5a88SDimitry Andric       // Python's readline is incompatible with libedit being linked into lldb.
106c14a5a88SDimitry Andric       // Provide a patched version local to the embedded interpreter.
107c14a5a88SDimitry Andric       bool ReadlinePatched = false;
108bdd1243dSDimitry Andric       for (auto *p = PyImport_Inittab; p->name != nullptr; p++) {
109c14a5a88SDimitry Andric         if (strcmp(p->name, "readline") == 0) {
110c14a5a88SDimitry Andric           p->initfunc = initlldb_readline;
111c14a5a88SDimitry Andric           break;
112c14a5a88SDimitry Andric         }
113c14a5a88SDimitry Andric       }
114c14a5a88SDimitry Andric       if (!ReadlinePatched) {
115c14a5a88SDimitry Andric         PyImport_AppendInittab("readline", initlldb_readline);
116c14a5a88SDimitry Andric         ReadlinePatched = true;
117c14a5a88SDimitry Andric       }
118c14a5a88SDimitry Andric #endif
119c14a5a88SDimitry Andric 
1200b57cec5SDimitry Andric       // Register _lldb as a built-in module.
1210b57cec5SDimitry Andric       PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
122*0fca6ea1SDimitry Andric     }
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
1250b57cec5SDimitry Andric // calling `Py_Initialize` and `PyEval_InitThreads`.  < 3.2 requires that you
1260b57cec5SDimitry Andric // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
1270b57cec5SDimitry Andric #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
1280b57cec5SDimitry Andric     Py_InitializeEx(0);
1290b57cec5SDimitry Andric     InitializeThreadsPrivate();
1300b57cec5SDimitry Andric #else
1310b57cec5SDimitry Andric     InitializeThreadsPrivate();
1320b57cec5SDimitry Andric     Py_InitializeEx(0);
1330b57cec5SDimitry Andric #endif
1340b57cec5SDimitry Andric   }
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric   ~InitializePythonRAII() {
1370b57cec5SDimitry Andric     if (m_was_already_initialized) {
13881ad6265SDimitry Andric       Log *log = GetLog(LLDBLog::Script);
1390b57cec5SDimitry Andric       LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
1400b57cec5SDimitry Andric                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
1410b57cec5SDimitry Andric       PyGILState_Release(m_gil_state);
1420b57cec5SDimitry Andric     } else {
1430b57cec5SDimitry Andric       // We initialized the threads in this function, just unlock the GIL.
1440b57cec5SDimitry Andric       PyEval_SaveThread();
1450b57cec5SDimitry Andric     }
1460b57cec5SDimitry Andric   }
1470b57cec5SDimitry Andric 
1480b57cec5SDimitry Andric private:
1490b57cec5SDimitry Andric   void InitializePythonHome() {
1505ffd83dbSDimitry Andric #if LLDB_EMBED_PYTHON_HOME
1515ffd83dbSDimitry Andric     typedef wchar_t *str_type;
1525ffd83dbSDimitry Andric     static str_type g_python_home = []() -> str_type {
1535ffd83dbSDimitry Andric       const char *lldb_python_home = LLDB_PYTHON_HOME;
1545ffd83dbSDimitry Andric       const char *absolute_python_home = nullptr;
1555ffd83dbSDimitry Andric       llvm::SmallString<64> path;
1565ffd83dbSDimitry Andric       if (llvm::sys::path::is_absolute(lldb_python_home)) {
1575ffd83dbSDimitry Andric         absolute_python_home = lldb_python_home;
1585ffd83dbSDimitry Andric       } else {
1595ffd83dbSDimitry Andric         FileSpec spec = HostInfo::GetShlibDir();
1605ffd83dbSDimitry Andric         if (!spec)
1615ffd83dbSDimitry Andric           return nullptr;
1625ffd83dbSDimitry Andric         spec.GetPath(path);
1635ffd83dbSDimitry Andric         llvm::sys::path::append(path, lldb_python_home);
1645ffd83dbSDimitry Andric         absolute_python_home = path.c_str();
1655ffd83dbSDimitry Andric       }
1660b57cec5SDimitry Andric       size_t size = 0;
1675ffd83dbSDimitry Andric       return Py_DecodeLocale(absolute_python_home, &size);
1685ffd83dbSDimitry Andric     }();
1695ffd83dbSDimitry Andric     if (g_python_home != nullptr) {
1700b57cec5SDimitry Andric       Py_SetPythonHome(g_python_home);
1715ffd83dbSDimitry Andric     }
1720b57cec5SDimitry Andric #endif
1730b57cec5SDimitry Andric   }
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric   void InitializeThreadsPrivate() {
1760b57cec5SDimitry Andric // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself,
1770b57cec5SDimitry Andric // so there is no way to determine whether the embedded interpreter
1780b57cec5SDimitry Andric // was already initialized by some external code. `PyEval_ThreadsInitialized`
1790b57cec5SDimitry Andric // would always return `true` and `PyGILState_Ensure/Release` flow would be
1800b57cec5SDimitry Andric // executed instead of unlocking GIL with `PyEval_SaveThread`. When
1810b57cec5SDimitry Andric // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock.
1820b57cec5SDimitry Andric #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3)
1830b57cec5SDimitry Andric     // The only case we should go further and acquire the GIL: it is unlocked.
1840b57cec5SDimitry Andric     if (PyGILState_Check())
1850b57cec5SDimitry Andric       return;
1860b57cec5SDimitry Andric #endif
1870b57cec5SDimitry Andric 
1885f757f3fSDimitry Andric // `PyEval_ThreadsInitialized` was deprecated in Python 3.9 and removed in
1895f757f3fSDimitry Andric // Python 3.13. It has been returning `true` always since Python 3.7.
1905f757f3fSDimitry Andric #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 9) || (PY_MAJOR_VERSION < 3)
1910b57cec5SDimitry Andric     if (PyEval_ThreadsInitialized()) {
1925f757f3fSDimitry Andric #else
1935f757f3fSDimitry Andric     if (true) {
1945f757f3fSDimitry Andric #endif
19581ad6265SDimitry Andric       Log *log = GetLog(LLDBLog::Script);
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric       m_was_already_initialized = true;
1980b57cec5SDimitry Andric       m_gil_state = PyGILState_Ensure();
1990b57cec5SDimitry Andric       LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n",
2000b57cec5SDimitry Andric                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
2015f757f3fSDimitry Andric 
2025f757f3fSDimitry Andric // `PyEval_InitThreads` was deprecated in Python 3.9 and removed in
2035f757f3fSDimitry Andric // Python 3.13.
2045f757f3fSDimitry Andric #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 9) || (PY_MAJOR_VERSION < 3)
2050b57cec5SDimitry Andric       return;
2060b57cec5SDimitry Andric     }
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric     // InitThreads acquires the GIL if it hasn't been called before.
2090b57cec5SDimitry Andric     PyEval_InitThreads();
2105f757f3fSDimitry Andric #else
2115f757f3fSDimitry Andric     }
2125f757f3fSDimitry Andric #endif
2130b57cec5SDimitry Andric   }
2140b57cec5SDimitry Andric 
215fe6060f1SDimitry Andric   PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
216fe6060f1SDimitry Andric   bool m_was_already_initialized = false;
2170b57cec5SDimitry Andric };
21804eeddc0SDimitry Andric 
21904eeddc0SDimitry Andric #if LLDB_USE_PYTHON_SET_INTERRUPT
22004eeddc0SDimitry Andric /// Saves the current signal handler for the specified signal and restores
22104eeddc0SDimitry Andric /// it at the end of the current scope.
22204eeddc0SDimitry Andric struct RestoreSignalHandlerScope {
22304eeddc0SDimitry Andric   /// The signal handler.
22404eeddc0SDimitry Andric   struct sigaction m_prev_handler;
22504eeddc0SDimitry Andric   int m_signal_code;
22604eeddc0SDimitry Andric   RestoreSignalHandlerScope(int signal_code) : m_signal_code(signal_code) {
22704eeddc0SDimitry Andric     // Initialize sigaction to their default state.
22804eeddc0SDimitry Andric     std::memset(&m_prev_handler, 0, sizeof(m_prev_handler));
22904eeddc0SDimitry Andric     // Don't install a new handler, just read back the old one.
23004eeddc0SDimitry Andric     struct sigaction *new_handler = nullptr;
23104eeddc0SDimitry Andric     int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler);
23204eeddc0SDimitry Andric     lldbassert(signal_err == 0 && "sigaction failed to read handler");
23304eeddc0SDimitry Andric   }
23404eeddc0SDimitry Andric   ~RestoreSignalHandlerScope() {
23504eeddc0SDimitry Andric     int signal_err = ::sigaction(m_signal_code, &m_prev_handler, nullptr);
23604eeddc0SDimitry Andric     lldbassert(signal_err == 0 && "sigaction failed to restore old handler");
23704eeddc0SDimitry Andric   }
23804eeddc0SDimitry Andric };
23904eeddc0SDimitry Andric #endif
2400b57cec5SDimitry Andric } // namespace
2410b57cec5SDimitry Andric 
2420b57cec5SDimitry Andric void ScriptInterpreterPython::ComputePythonDirForApple(
2430b57cec5SDimitry Andric     llvm::SmallVectorImpl<char> &path) {
2440b57cec5SDimitry Andric   auto style = llvm::sys::path::Style::posix;
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric   llvm::StringRef path_ref(path.begin(), path.size());
2470b57cec5SDimitry Andric   auto rbegin = llvm::sys::path::rbegin(path_ref, style);
2480b57cec5SDimitry Andric   auto rend = llvm::sys::path::rend(path_ref);
2490b57cec5SDimitry Andric   auto framework = std::find(rbegin, rend, "LLDB.framework");
2500b57cec5SDimitry Andric   if (framework == rend) {
2519dba64beSDimitry Andric     ComputePythonDir(path);
2520b57cec5SDimitry Andric     return;
2530b57cec5SDimitry Andric   }
2540b57cec5SDimitry Andric   path.resize(framework - rend);
2550b57cec5SDimitry Andric   llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
2560b57cec5SDimitry Andric }
2570b57cec5SDimitry Andric 
2589dba64beSDimitry Andric void ScriptInterpreterPython::ComputePythonDir(
2590b57cec5SDimitry Andric     llvm::SmallVectorImpl<char> &path) {
2600b57cec5SDimitry Andric   // Build the path by backing out of the lib dir, then building with whatever
2610b57cec5SDimitry Andric   // the real python interpreter uses.  (e.g. lib for most, lib64 on RHEL
2629dba64beSDimitry Andric   // x86_64, or bin on Windows).
2639dba64beSDimitry Andric   llvm::sys::path::remove_filename(path);
2649dba64beSDimitry Andric   llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
2650b57cec5SDimitry Andric 
2669dba64beSDimitry Andric #if defined(_WIN32)
267bdd1243dSDimitry Andric   // This will be injected directly through FileSpec.SetDirectory(),
2680b57cec5SDimitry Andric   // so we need to normalize manually.
2690b57cec5SDimitry Andric   std::replace(path.begin(), path.end(), '\\', '/');
2709dba64beSDimitry Andric #endif
2710b57cec5SDimitry Andric }
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric FileSpec ScriptInterpreterPython::GetPythonDir() {
2740b57cec5SDimitry Andric   static FileSpec g_spec = []() {
2750b57cec5SDimitry Andric     FileSpec spec = HostInfo::GetShlibDir();
2760b57cec5SDimitry Andric     if (!spec)
2770b57cec5SDimitry Andric       return FileSpec();
2780b57cec5SDimitry Andric     llvm::SmallString<64> path;
2790b57cec5SDimitry Andric     spec.GetPath(path);
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric #if defined(__APPLE__)
2820b57cec5SDimitry Andric     ComputePythonDirForApple(path);
2830b57cec5SDimitry Andric #else
2849dba64beSDimitry Andric     ComputePythonDir(path);
2850b57cec5SDimitry Andric #endif
286bdd1243dSDimitry Andric     spec.SetDirectory(path);
2870b57cec5SDimitry Andric     return spec;
2880b57cec5SDimitry Andric   }();
2890b57cec5SDimitry Andric   return g_spec;
2900b57cec5SDimitry Andric }
2910b57cec5SDimitry Andric 
292349cc55cSDimitry Andric static const char GetInterpreterInfoScript[] = R"(
293349cc55cSDimitry Andric import os
294349cc55cSDimitry Andric import sys
295349cc55cSDimitry Andric 
296349cc55cSDimitry Andric def main(lldb_python_dir, python_exe_relative_path):
297349cc55cSDimitry Andric   info = {
298349cc55cSDimitry Andric     "lldb-pythonpath": lldb_python_dir,
299349cc55cSDimitry Andric     "language": "python",
300349cc55cSDimitry Andric     "prefix": sys.prefix,
301349cc55cSDimitry Andric     "executable": os.path.join(sys.prefix, python_exe_relative_path)
302349cc55cSDimitry Andric   }
303349cc55cSDimitry Andric   return info
304349cc55cSDimitry Andric )";
305349cc55cSDimitry Andric 
306349cc55cSDimitry Andric static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH;
307349cc55cSDimitry Andric 
308349cc55cSDimitry Andric StructuredData::DictionarySP ScriptInterpreterPython::GetInterpreterInfo() {
309349cc55cSDimitry Andric   GIL gil;
310349cc55cSDimitry Andric   FileSpec python_dir_spec = GetPythonDir();
311349cc55cSDimitry Andric   if (!python_dir_spec)
312349cc55cSDimitry Andric     return nullptr;
313349cc55cSDimitry Andric   PythonScript get_info(GetInterpreterInfoScript);
314349cc55cSDimitry Andric   auto info_json = unwrapIgnoringErrors(
315349cc55cSDimitry Andric       As<PythonDictionary>(get_info(PythonString(python_dir_spec.GetPath()),
316349cc55cSDimitry Andric                                     PythonString(python_exe_relative_path))));
317349cc55cSDimitry Andric   if (!info_json)
318349cc55cSDimitry Andric     return nullptr;
319349cc55cSDimitry Andric   return info_json.CreateStructuredDictionary();
320349cc55cSDimitry Andric }
321349cc55cSDimitry Andric 
322fe6060f1SDimitry Andric void ScriptInterpreterPython::SharedLibraryDirectoryHelper(
323fe6060f1SDimitry Andric     FileSpec &this_file) {
324fe6060f1SDimitry Andric   // When we're loaded from python, this_file will point to the file inside the
325fe6060f1SDimitry Andric   // python package directory. Replace it with the one in the lib directory.
326fe6060f1SDimitry Andric #ifdef _WIN32
327fe6060f1SDimitry Andric   // On windows, we need to manually back out of the python tree, and go into
328fe6060f1SDimitry Andric   // the bin directory. This is pretty much the inverse of what ComputePythonDir
329fe6060f1SDimitry Andric   // does.
33006c3fb27SDimitry Andric   if (this_file.GetFileNameExtension() == ".pyd") {
331fe6060f1SDimitry Andric     this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd
332fe6060f1SDimitry Andric     this_file.RemoveLastPathComponent(); // lldb
333fe6060f1SDimitry Andric     llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
334fe6060f1SDimitry Andric     for (auto it = llvm::sys::path::begin(libdir),
335fe6060f1SDimitry Andric               end = llvm::sys::path::end(libdir);
336fe6060f1SDimitry Andric          it != end; ++it)
337fe6060f1SDimitry Andric       this_file.RemoveLastPathComponent();
338fe6060f1SDimitry Andric     this_file.AppendPathComponent("bin");
339fe6060f1SDimitry Andric     this_file.AppendPathComponent("liblldb.dll");
340fe6060f1SDimitry Andric   }
341fe6060f1SDimitry Andric #else
342fe6060f1SDimitry Andric   // The python file is a symlink, so we can find the real library by resolving
343fe6060f1SDimitry Andric   // it. We can do this unconditionally.
344fe6060f1SDimitry Andric   FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
345fe6060f1SDimitry Andric #endif
346fe6060f1SDimitry Andric }
347fe6060f1SDimitry Andric 
348349cc55cSDimitry Andric llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() {
3490b57cec5SDimitry Andric   return "Embedded Python interpreter";
3500b57cec5SDimitry Andric }
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric void ScriptInterpreterPython::Initialize() {
3530b57cec5SDimitry Andric   static llvm::once_flag g_once_flag;
3540b57cec5SDimitry Andric   llvm::call_once(g_once_flag, []() {
3550b57cec5SDimitry Andric     PluginManager::RegisterPlugin(GetPluginNameStatic(),
3560b57cec5SDimitry Andric                                   GetPluginDescriptionStatic(),
3570b57cec5SDimitry Andric                                   lldb::eScriptLanguagePython,
3580b57cec5SDimitry Andric                                   ScriptInterpreterPythonImpl::CreateInstance);
35904eeddc0SDimitry Andric     ScriptInterpreterPythonImpl::Initialize();
3600b57cec5SDimitry Andric   });
3610b57cec5SDimitry Andric }
3620b57cec5SDimitry Andric 
3630b57cec5SDimitry Andric void ScriptInterpreterPython::Terminate() {}
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric ScriptInterpreterPythonImpl::Locker::Locker(
3660b57cec5SDimitry Andric     ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
3679dba64beSDimitry Andric     uint16_t on_leave, FileSP in, FileSP out, FileSP err)
3680b57cec5SDimitry Andric     : ScriptInterpreterLocker(),
3690b57cec5SDimitry Andric       m_teardown_session((on_leave & TearDownSession) == TearDownSession),
3700b57cec5SDimitry Andric       m_python_interpreter(py_interpreter) {
3710b57cec5SDimitry Andric   DoAcquireLock();
3720b57cec5SDimitry Andric   if ((on_entry & InitSession) == InitSession) {
3730b57cec5SDimitry Andric     if (!DoInitSession(on_entry, in, out, err)) {
3740b57cec5SDimitry Andric       // Don't teardown the session if we didn't init it.
3750b57cec5SDimitry Andric       m_teardown_session = false;
3760b57cec5SDimitry Andric     }
3770b57cec5SDimitry Andric   }
3780b57cec5SDimitry Andric }
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
38181ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Script);
3820b57cec5SDimitry Andric   m_GILState = PyGILState_Ensure();
3830b57cec5SDimitry Andric   LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked",
3840b57cec5SDimitry Andric             m_GILState == PyGILState_UNLOCKED ? "un" : "");
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric   // we need to save the thread state when we first start the command because
3870b57cec5SDimitry Andric   // we might decide to interrupt it while some action is taking place outside
3880b57cec5SDimitry Andric   // of Python (e.g. printing to screen, waiting for the network, ...) in that
3890b57cec5SDimitry Andric   // case, _PyThreadState_Current will be NULL - and we would be unable to set
3900b57cec5SDimitry Andric   // the asynchronous exception - not a desirable situation
3910b57cec5SDimitry Andric   m_python_interpreter->SetThreadState(PyThreadState_Get());
3920b57cec5SDimitry Andric   m_python_interpreter->IncrementLockCount();
3930b57cec5SDimitry Andric   return true;
3940b57cec5SDimitry Andric }
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
3979dba64beSDimitry Andric                                                         FileSP in, FileSP out,
3989dba64beSDimitry Andric                                                         FileSP err) {
3990b57cec5SDimitry Andric   if (!m_python_interpreter)
4000b57cec5SDimitry Andric     return false;
4010b57cec5SDimitry Andric   return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
4020b57cec5SDimitry Andric }
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
40581ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Script);
4060b57cec5SDimitry Andric   LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
4070b57cec5SDimitry Andric             m_GILState == PyGILState_UNLOCKED ? "un" : "");
4080b57cec5SDimitry Andric   PyGILState_Release(m_GILState);
4090b57cec5SDimitry Andric   m_python_interpreter->DecrementLockCount();
4100b57cec5SDimitry Andric   return true;
4110b57cec5SDimitry Andric }
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
4140b57cec5SDimitry Andric   if (!m_python_interpreter)
4150b57cec5SDimitry Andric     return false;
4160b57cec5SDimitry Andric   m_python_interpreter->LeaveSession();
4170b57cec5SDimitry Andric   return true;
4180b57cec5SDimitry Andric }
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric ScriptInterpreterPythonImpl::Locker::~Locker() {
4210b57cec5SDimitry Andric   if (m_teardown_session)
4220b57cec5SDimitry Andric     DoTearDownSession();
4230b57cec5SDimitry Andric   DoFreeLock();
4240b57cec5SDimitry Andric }
4250b57cec5SDimitry Andric 
4260b57cec5SDimitry Andric ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger)
4270b57cec5SDimitry Andric     : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
4280b57cec5SDimitry Andric       m_saved_stderr(), m_main_module(),
4290b57cec5SDimitry Andric       m_session_dict(PyInitialValue::Invalid),
4300b57cec5SDimitry Andric       m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(),
4310b57cec5SDimitry Andric       m_run_one_line_str_global(),
43206c3fb27SDimitry Andric       m_dictionary_name(m_debugger.GetInstanceName()),
4339dba64beSDimitry Andric       m_active_io_handler(eIOHandlerNone), m_session_is_active(false),
4345ffd83dbSDimitry Andric       m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
4359dba64beSDimitry Andric       m_command_thread_state(nullptr) {
436fe6060f1SDimitry Andric 
4370b57cec5SDimitry Andric   m_dictionary_name.append("_dict");
4380b57cec5SDimitry Andric   StreamString run_string;
4390b57cec5SDimitry Andric   run_string.Printf("%s = dict()", m_dictionary_name.c_str());
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric   Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock);
4420b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric   run_string.Clear();
4450b57cec5SDimitry Andric   run_string.Printf(
4460b57cec5SDimitry Andric       "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
4470b57cec5SDimitry Andric       m_dictionary_name.c_str());
4480b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric   // Reloading modules requires a different syntax in Python 2 and Python 3.
4510b57cec5SDimitry Andric   // This provides a consistent syntax no matter what version of Python.
4520b57cec5SDimitry Andric   run_string.Clear();
453bdd1243dSDimitry Andric   run_string.Printf("run_one_line (%s, 'from importlib import reload as reload_module')",
4540b57cec5SDimitry Andric                     m_dictionary_name.c_str());
4550b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric   // WARNING: temporary code that loads Cocoa formatters - this should be done
4580b57cec5SDimitry Andric   // on a per-platform basis rather than loading the whole set and letting the
4590b57cec5SDimitry Andric   // individual formatter classes exploit APIs to check whether they can/cannot
4600b57cec5SDimitry Andric   // do their task
4610b57cec5SDimitry Andric   run_string.Clear();
4620b57cec5SDimitry Andric   run_string.Printf(
46306c3fb27SDimitry Andric       "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp')",
4640b57cec5SDimitry Andric       m_dictionary_name.c_str());
4650b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
4660b57cec5SDimitry Andric   run_string.Clear();
4670b57cec5SDimitry Andric 
4680b57cec5SDimitry Andric   run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
4690b57cec5SDimitry Andric                     "lldb.embedded_interpreter import run_python_interpreter; "
4700b57cec5SDimitry Andric                     "from lldb.embedded_interpreter import run_one_line')",
4710b57cec5SDimitry Andric                     m_dictionary_name.c_str());
4720b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
4730b57cec5SDimitry Andric   run_string.Clear();
4740b57cec5SDimitry Andric 
4750b57cec5SDimitry Andric   run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
47606c3fb27SDimitry Andric                     "')",
4770b57cec5SDimitry Andric                     m_dictionary_name.c_str(), m_debugger.GetID());
4780b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
4790b57cec5SDimitry Andric }
4800b57cec5SDimitry Andric 
4810b57cec5SDimitry Andric ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
4820b57cec5SDimitry Andric   // the session dictionary may hold objects with complex state which means
4830b57cec5SDimitry Andric   // that they may need to be torn down with some level of smarts and that, in
4840b57cec5SDimitry Andric   // turn, requires a valid thread state force Python to procure itself such a
4850b57cec5SDimitry Andric   // thread state, nuke the session dictionary and then release it for others
4860b57cec5SDimitry Andric   // to use and proceed with the rest of the shutdown
4870b57cec5SDimitry Andric   auto gil_state = PyGILState_Ensure();
4880b57cec5SDimitry Andric   m_session_dict.Reset();
4890b57cec5SDimitry Andric   PyGILState_Release(gil_state);
4900b57cec5SDimitry Andric }
4910b57cec5SDimitry Andric 
4920b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler,
4930b57cec5SDimitry Andric                                                      bool interactive) {
4940b57cec5SDimitry Andric   const char *instructions = nullptr;
4950b57cec5SDimitry Andric 
4960b57cec5SDimitry Andric   switch (m_active_io_handler) {
4970b57cec5SDimitry Andric   case eIOHandlerNone:
4980b57cec5SDimitry Andric     break;
4990b57cec5SDimitry Andric   case eIOHandlerBreakpoint:
5000b57cec5SDimitry Andric     instructions = R"(Enter your Python command(s). Type 'DONE' to end.
5010b57cec5SDimitry Andric def function (frame, bp_loc, internal_dict):
5020b57cec5SDimitry Andric     """frame: the lldb.SBFrame for the location at which you stopped
5030b57cec5SDimitry Andric        bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
5040b57cec5SDimitry Andric        internal_dict: an LLDB support object not to be used"""
5050b57cec5SDimitry Andric )";
5060b57cec5SDimitry Andric     break;
5070b57cec5SDimitry Andric   case eIOHandlerWatchpoint:
5080b57cec5SDimitry Andric     instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
5090b57cec5SDimitry Andric     break;
5100b57cec5SDimitry Andric   }
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric   if (instructions) {
5139dba64beSDimitry Andric     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
5140b57cec5SDimitry Andric     if (output_sp && interactive) {
5150b57cec5SDimitry Andric       output_sp->PutCString(instructions);
5160b57cec5SDimitry Andric       output_sp->Flush();
5170b57cec5SDimitry Andric     }
5180b57cec5SDimitry Andric   }
5190b57cec5SDimitry Andric }
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler,
5220b57cec5SDimitry Andric                                                          std::string &data) {
5230b57cec5SDimitry Andric   io_handler.SetIsDone(true);
5240b57cec5SDimitry Andric   bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
5250b57cec5SDimitry Andric 
5260b57cec5SDimitry Andric   switch (m_active_io_handler) {
5270b57cec5SDimitry Andric   case eIOHandlerNone:
5280b57cec5SDimitry Andric     break;
5290b57cec5SDimitry Andric   case eIOHandlerBreakpoint: {
530fe6060f1SDimitry Andric     std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
531fe6060f1SDimitry Andric         (std::vector<std::reference_wrapper<BreakpointOptions>> *)
532fe6060f1SDimitry Andric             io_handler.GetUserData();
533fe6060f1SDimitry Andric     for (BreakpointOptions &bp_options : *bp_options_vec) {
5340b57cec5SDimitry Andric 
5359dba64beSDimitry Andric       auto data_up = std::make_unique<CommandDataPython>();
5360b57cec5SDimitry Andric       if (!data_up)
5370b57cec5SDimitry Andric         break;
5380b57cec5SDimitry Andric       data_up->user_source.SplitIntoLines(data);
5390b57cec5SDimitry Andric 
5400b57cec5SDimitry Andric       if (GenerateBreakpointCommandCallbackData(data_up->user_source,
541480093f4SDimitry Andric                                                 data_up->script_source,
54206c3fb27SDimitry Andric                                                 /*has_extra_args=*/false,
54306c3fb27SDimitry Andric                                                 /*is_callback=*/false)
5440b57cec5SDimitry Andric               .Success()) {
5450b57cec5SDimitry Andric         auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
5460b57cec5SDimitry Andric             std::move(data_up));
547fe6060f1SDimitry Andric         bp_options.SetCallback(
5480b57cec5SDimitry Andric             ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
5490b57cec5SDimitry Andric       } else if (!batch_mode) {
5509dba64beSDimitry Andric         StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
5510b57cec5SDimitry Andric         if (error_sp) {
5520b57cec5SDimitry Andric           error_sp->Printf("Warning: No command attached to breakpoint.\n");
5530b57cec5SDimitry Andric           error_sp->Flush();
5540b57cec5SDimitry Andric         }
5550b57cec5SDimitry Andric       }
5560b57cec5SDimitry Andric     }
5570b57cec5SDimitry Andric     m_active_io_handler = eIOHandlerNone;
5580b57cec5SDimitry Andric   } break;
5590b57cec5SDimitry Andric   case eIOHandlerWatchpoint: {
5600b57cec5SDimitry Andric     WatchpointOptions *wp_options =
5610b57cec5SDimitry Andric         (WatchpointOptions *)io_handler.GetUserData();
5629dba64beSDimitry Andric     auto data_up = std::make_unique<WatchpointOptions::CommandData>();
5630b57cec5SDimitry Andric     data_up->user_source.SplitIntoLines(data);
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric     if (GenerateWatchpointCommandCallbackData(data_up->user_source,
56606c3fb27SDimitry Andric                                               data_up->script_source,
56706c3fb27SDimitry Andric                                               /*is_callback=*/false)) {
5680b57cec5SDimitry Andric       auto baton_sp =
5690b57cec5SDimitry Andric           std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
5700b57cec5SDimitry Andric       wp_options->SetCallback(
5710b57cec5SDimitry Andric           ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
5720b57cec5SDimitry Andric     } else if (!batch_mode) {
5739dba64beSDimitry Andric       StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
5740b57cec5SDimitry Andric       if (error_sp) {
5750b57cec5SDimitry Andric         error_sp->Printf("Warning: No command attached to breakpoint.\n");
5760b57cec5SDimitry Andric         error_sp->Flush();
5770b57cec5SDimitry Andric       }
5780b57cec5SDimitry Andric     }
5790b57cec5SDimitry Andric     m_active_io_handler = eIOHandlerNone;
5800b57cec5SDimitry Andric   } break;
5810b57cec5SDimitry Andric   }
5820b57cec5SDimitry Andric }
5830b57cec5SDimitry Andric 
5840b57cec5SDimitry Andric lldb::ScriptInterpreterSP
5850b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) {
5860b57cec5SDimitry Andric   return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
5870b57cec5SDimitry Andric }
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::LeaveSession() {
59081ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Script);
5910b57cec5SDimitry Andric   if (log)
5920b57cec5SDimitry Andric     log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
5930b57cec5SDimitry Andric 
5949dba64beSDimitry Andric   // Unset the LLDB global variables.
5959dba64beSDimitry Andric   PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
5969dba64beSDimitry Andric                      "= None; lldb.thread = None; lldb.frame = None");
5979dba64beSDimitry Andric 
5980b57cec5SDimitry Andric   // checking that we have a valid thread state - since we use our own
5990b57cec5SDimitry Andric   // threading and locking in some (rare) cases during cleanup Python may end
6000b57cec5SDimitry Andric   // up believing we have no thread state and PyImport_AddModule will crash if
6010b57cec5SDimitry Andric   // that is the case - since that seems to only happen when destroying the
6020b57cec5SDimitry Andric   // SBDebugger, we can make do without clearing up stdout and stderr
6030b57cec5SDimitry Andric   if (PyThreadState_GetDict()) {
6040b57cec5SDimitry Andric     PythonDictionary &sys_module_dict = GetSysModuleDictionary();
6050b57cec5SDimitry Andric     if (sys_module_dict.IsValid()) {
6060b57cec5SDimitry Andric       if (m_saved_stdin.IsValid()) {
6070b57cec5SDimitry Andric         sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
6080b57cec5SDimitry Andric         m_saved_stdin.Reset();
6090b57cec5SDimitry Andric       }
6100b57cec5SDimitry Andric       if (m_saved_stdout.IsValid()) {
6110b57cec5SDimitry Andric         sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
6120b57cec5SDimitry Andric         m_saved_stdout.Reset();
6130b57cec5SDimitry Andric       }
6140b57cec5SDimitry Andric       if (m_saved_stderr.IsValid()) {
6150b57cec5SDimitry Andric         sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
6160b57cec5SDimitry Andric         m_saved_stderr.Reset();
6170b57cec5SDimitry Andric       }
6180b57cec5SDimitry Andric     }
6190b57cec5SDimitry Andric   }
6200b57cec5SDimitry Andric 
6210b57cec5SDimitry Andric   m_session_is_active = false;
6220b57cec5SDimitry Andric }
6230b57cec5SDimitry Andric 
6249dba64beSDimitry Andric bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp,
6259dba64beSDimitry Andric                                                const char *py_name,
6269dba64beSDimitry Andric                                                PythonObject &save_file,
6270b57cec5SDimitry Andric                                                const char *mode) {
6289dba64beSDimitry Andric   if (!file_sp || !*file_sp) {
6299dba64beSDimitry Andric     save_file.Reset();
6309dba64beSDimitry Andric     return false;
6319dba64beSDimitry Andric   }
6329dba64beSDimitry Andric   File &file = *file_sp;
6339dba64beSDimitry Andric 
6340b57cec5SDimitry Andric   // Flush the file before giving it to python to avoid interleaved output.
6350b57cec5SDimitry Andric   file.Flush();
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
6380b57cec5SDimitry Andric 
6399dba64beSDimitry Andric   auto new_file = PythonFile::FromFile(file, mode);
6409dba64beSDimitry Andric   if (!new_file) {
6419dba64beSDimitry Andric     llvm::consumeError(new_file.takeError());
6420b57cec5SDimitry Andric     return false;
6430b57cec5SDimitry Andric   }
6440b57cec5SDimitry Andric 
6459dba64beSDimitry Andric   save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
6469dba64beSDimitry Andric 
6479dba64beSDimitry Andric   sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
6489dba64beSDimitry Andric   return true;
6499dba64beSDimitry Andric }
6509dba64beSDimitry Andric 
6510b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
6529dba64beSDimitry Andric                                                FileSP in_sp, FileSP out_sp,
6539dba64beSDimitry Andric                                                FileSP err_sp) {
6540b57cec5SDimitry Andric   // If we have already entered the session, without having officially 'left'
6550b57cec5SDimitry Andric   // it, then there is no need to 'enter' it again.
65681ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Script);
6570b57cec5SDimitry Andric   if (m_session_is_active) {
6589dba64beSDimitry Andric     LLDB_LOGF(
6599dba64beSDimitry Andric         log,
6600b57cec5SDimitry Andric         "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
6610b57cec5SDimitry Andric         ") session is already active, returning without doing anything",
6620b57cec5SDimitry Andric         on_entry_flags);
6630b57cec5SDimitry Andric     return false;
6640b57cec5SDimitry Andric   }
6650b57cec5SDimitry Andric 
6669dba64beSDimitry Andric   LLDB_LOGF(
6679dba64beSDimitry Andric       log,
6689dba64beSDimitry Andric       "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
6690b57cec5SDimitry Andric       on_entry_flags);
6700b57cec5SDimitry Andric 
6710b57cec5SDimitry Andric   m_session_is_active = true;
6720b57cec5SDimitry Andric 
6730b57cec5SDimitry Andric   StreamString run_string;
6740b57cec5SDimitry Andric 
6750b57cec5SDimitry Andric   if (on_entry_flags & Locker::InitGlobals) {
6760b57cec5SDimitry Andric     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
6770b57cec5SDimitry Andric                       m_dictionary_name.c_str(), m_debugger.GetID());
6780b57cec5SDimitry Andric     run_string.Printf(
6790b57cec5SDimitry Andric         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
6800b57cec5SDimitry Andric         m_debugger.GetID());
6810b57cec5SDimitry Andric     run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
6820b57cec5SDimitry Andric     run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
6830b57cec5SDimitry Andric     run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
6840b57cec5SDimitry Andric     run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
6850b57cec5SDimitry Andric     run_string.PutCString("')");
6860b57cec5SDimitry Andric   } else {
6870b57cec5SDimitry Andric     // If we aren't initing the globals, we should still always set the
6880b57cec5SDimitry Andric     // debugger (since that is always unique.)
6890b57cec5SDimitry Andric     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
6900b57cec5SDimitry Andric                       m_dictionary_name.c_str(), m_debugger.GetID());
6910b57cec5SDimitry Andric     run_string.Printf(
6920b57cec5SDimitry Andric         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
6930b57cec5SDimitry Andric         m_debugger.GetID());
6940b57cec5SDimitry Andric     run_string.PutCString("')");
6950b57cec5SDimitry Andric   }
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
6980b57cec5SDimitry Andric   run_string.Clear();
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
7010b57cec5SDimitry Andric   if (sys_module_dict.IsValid()) {
7029dba64beSDimitry Andric     lldb::FileSP top_in_sp;
7039dba64beSDimitry Andric     lldb::StreamFileSP top_out_sp, top_err_sp;
7049dba64beSDimitry Andric     if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
7059dba64beSDimitry Andric       m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
7069dba64beSDimitry Andric                                                  top_err_sp);
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric     if (on_entry_flags & Locker::NoSTDIN) {
7090b57cec5SDimitry Andric       m_saved_stdin.Reset();
7100b57cec5SDimitry Andric     } else {
7119dba64beSDimitry Andric       if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
7129dba64beSDimitry Andric         if (top_in_sp)
7139dba64beSDimitry Andric           SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
7140b57cec5SDimitry Andric       }
7150b57cec5SDimitry Andric     }
7160b57cec5SDimitry Andric 
7179dba64beSDimitry Andric     if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
7189dba64beSDimitry Andric       if (top_out_sp)
7199dba64beSDimitry Andric         SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w");
7200b57cec5SDimitry Andric     }
7210b57cec5SDimitry Andric 
7229dba64beSDimitry Andric     if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
7239dba64beSDimitry Andric       if (top_err_sp)
7249dba64beSDimitry Andric         SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w");
7250b57cec5SDimitry Andric     }
7260b57cec5SDimitry Andric   }
7270b57cec5SDimitry Andric 
7280b57cec5SDimitry Andric   if (PyErr_Occurred())
7290b57cec5SDimitry Andric     PyErr_Clear();
7300b57cec5SDimitry Andric 
7310b57cec5SDimitry Andric   return true;
7320b57cec5SDimitry Andric }
7330b57cec5SDimitry Andric 
7349dba64beSDimitry Andric PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
7350b57cec5SDimitry Andric   if (!m_main_module.IsValid())
7369dba64beSDimitry Andric     m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__"));
7370b57cec5SDimitry Andric   return m_main_module;
7380b57cec5SDimitry Andric }
7390b57cec5SDimitry Andric 
7400b57cec5SDimitry Andric PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
7410b57cec5SDimitry Andric   if (m_session_dict.IsValid())
7420b57cec5SDimitry Andric     return m_session_dict;
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric   PythonObject &main_module = GetMainModule();
7450b57cec5SDimitry Andric   if (!main_module.IsValid())
7460b57cec5SDimitry Andric     return m_session_dict;
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric   PythonDictionary main_dict(PyRefType::Borrowed,
7490b57cec5SDimitry Andric                              PyModule_GetDict(main_module.get()));
7500b57cec5SDimitry Andric   if (!main_dict.IsValid())
7510b57cec5SDimitry Andric     return m_session_dict;
7520b57cec5SDimitry Andric 
7539dba64beSDimitry Andric   m_session_dict = unwrapIgnoringErrors(
7549dba64beSDimitry Andric       As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
7550b57cec5SDimitry Andric   return m_session_dict;
7560b57cec5SDimitry Andric }
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
7590b57cec5SDimitry Andric   if (m_sys_module_dict.IsValid())
7600b57cec5SDimitry Andric     return m_sys_module_dict;
7619dba64beSDimitry Andric   PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys"));
7629dba64beSDimitry Andric   m_sys_module_dict = sys_module.GetDictionary();
7630b57cec5SDimitry Andric   return m_sys_module_dict;
7640b57cec5SDimitry Andric }
7650b57cec5SDimitry Andric 
766480093f4SDimitry Andric llvm::Expected<unsigned>
767480093f4SDimitry Andric ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
768480093f4SDimitry Andric     const llvm::StringRef &callable_name) {
769480093f4SDimitry Andric   if (callable_name.empty()) {
770480093f4SDimitry Andric     return llvm::createStringError(
771480093f4SDimitry Andric         llvm::inconvertibleErrorCode(),
772480093f4SDimitry Andric         "called with empty callable name.");
773480093f4SDimitry Andric   }
774480093f4SDimitry Andric   Locker py_lock(this, Locker::AcquireLock |
775480093f4SDimitry Andric                  Locker::InitSession |
776480093f4SDimitry Andric                  Locker::NoSTDIN);
777480093f4SDimitry Andric   auto dict = PythonModule::MainModule()
778480093f4SDimitry Andric       .ResolveName<PythonDictionary>(m_dictionary_name);
779480093f4SDimitry Andric   auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
780480093f4SDimitry Andric       callable_name, dict);
781480093f4SDimitry Andric   if (!pfunc.IsAllocated()) {
782480093f4SDimitry Andric     return llvm::createStringError(
783480093f4SDimitry Andric         llvm::inconvertibleErrorCode(),
784480093f4SDimitry Andric         "can't find callable: %s", callable_name.str().c_str());
785480093f4SDimitry Andric   }
786480093f4SDimitry Andric   llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
787480093f4SDimitry Andric   if (!arg_info)
788480093f4SDimitry Andric     return arg_info.takeError();
789480093f4SDimitry Andric   return arg_info.get().max_positional_args;
790480093f4SDimitry Andric }
791480093f4SDimitry Andric 
7920b57cec5SDimitry Andric static std::string GenerateUniqueName(const char *base_name_wanted,
7930b57cec5SDimitry Andric                                       uint32_t &functions_counter,
7940b57cec5SDimitry Andric                                       const void *name_token = nullptr) {
7950b57cec5SDimitry Andric   StreamString sstr;
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric   if (!base_name_wanted)
7980b57cec5SDimitry Andric     return std::string();
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric   if (!name_token)
8010b57cec5SDimitry Andric     sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
8020b57cec5SDimitry Andric   else
8030b57cec5SDimitry Andric     sstr.Printf("%s_%p", base_name_wanted, name_token);
8040b57cec5SDimitry Andric 
8055ffd83dbSDimitry Andric   return std::string(sstr.GetString());
8060b57cec5SDimitry Andric }
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
8090b57cec5SDimitry Andric   if (m_run_one_line_function.IsValid())
8100b57cec5SDimitry Andric     return true;
8110b57cec5SDimitry Andric 
8120b57cec5SDimitry Andric   PythonObject module(PyRefType::Borrowed,
8130b57cec5SDimitry Andric                       PyImport_AddModule("lldb.embedded_interpreter"));
8140b57cec5SDimitry Andric   if (!module.IsValid())
8150b57cec5SDimitry Andric     return false;
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric   PythonDictionary module_dict(PyRefType::Borrowed,
8180b57cec5SDimitry Andric                                PyModule_GetDict(module.get()));
8190b57cec5SDimitry Andric   if (!module_dict.IsValid())
8200b57cec5SDimitry Andric     return false;
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric   m_run_one_line_function =
8230b57cec5SDimitry Andric       module_dict.GetItemForKey(PythonString("run_one_line"));
8240b57cec5SDimitry Andric   m_run_one_line_str_global =
8250b57cec5SDimitry Andric       module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
8260b57cec5SDimitry Andric   return m_run_one_line_function.IsValid();
8270b57cec5SDimitry Andric }
8280b57cec5SDimitry Andric 
8290b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ExecuteOneLine(
8300b57cec5SDimitry Andric     llvm::StringRef command, CommandReturnObject *result,
8310b57cec5SDimitry Andric     const ExecuteScriptOptions &options) {
8320b57cec5SDimitry Andric   std::string command_str = command.str();
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric   if (!m_valid_session)
8350b57cec5SDimitry Andric     return false;
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric   if (!command.empty()) {
8380b57cec5SDimitry Andric     // We want to call run_one_line, passing in the dictionary and the command
8390b57cec5SDimitry Andric     // string.  We cannot do this through PyRun_SimpleString here because the
8400b57cec5SDimitry Andric     // command string may contain escaped characters, and putting it inside
8410b57cec5SDimitry Andric     // another string to pass to PyRun_SimpleString messes up the escaping.  So
8420b57cec5SDimitry Andric     // we use the following more complicated method to pass the command string
8430b57cec5SDimitry Andric     // directly down to Python.
8445ffd83dbSDimitry Andric     llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
8455ffd83dbSDimitry Andric         io_redirect_or_error = ScriptInterpreterIORedirect::Create(
8465ffd83dbSDimitry Andric             options.GetEnableIO(), m_debugger, result);
8475ffd83dbSDimitry Andric     if (!io_redirect_or_error) {
8485ffd83dbSDimitry Andric       if (result)
8495ffd83dbSDimitry Andric         result->AppendErrorWithFormatv(
8505ffd83dbSDimitry Andric             "failed to redirect I/O: {0}\n",
8515ffd83dbSDimitry Andric             llvm::fmt_consume(io_redirect_or_error.takeError()));
8525ffd83dbSDimitry Andric       else
8535ffd83dbSDimitry Andric         llvm::consumeError(io_redirect_or_error.takeError());
8549dba64beSDimitry Andric       return false;
8559dba64beSDimitry Andric     }
8565ffd83dbSDimitry Andric 
8575ffd83dbSDimitry Andric     ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric     bool success = false;
8600b57cec5SDimitry Andric     {
8610b57cec5SDimitry Andric       // WARNING!  It's imperative that this RAII scope be as tight as
8620b57cec5SDimitry Andric       // possible. In particular, the scope must end *before* we try to join
8630b57cec5SDimitry Andric       // the read thread.  The reason for this is that a pre-requisite for
8640b57cec5SDimitry Andric       // joining the read thread is that we close the write handle (to break
8650b57cec5SDimitry Andric       // the pipe and cause it to wake up and exit).  But acquiring the GIL as
8660b57cec5SDimitry Andric       // below will redirect Python's stdio to use this same handle.  If we
8670b57cec5SDimitry Andric       // close the handle while Python is still using it, bad things will
8680b57cec5SDimitry Andric       // happen.
8690b57cec5SDimitry Andric       Locker locker(
8700b57cec5SDimitry Andric           this,
8710b57cec5SDimitry Andric           Locker::AcquireLock | Locker::InitSession |
8720b57cec5SDimitry Andric               (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
8730b57cec5SDimitry Andric               ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
8745ffd83dbSDimitry Andric           Locker::FreeAcquiredLock | Locker::TearDownSession,
8755ffd83dbSDimitry Andric           io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
8765ffd83dbSDimitry Andric           io_redirect.GetErrorFile());
8770b57cec5SDimitry Andric 
8780b57cec5SDimitry Andric       // Find the correct script interpreter dictionary in the main module.
8790b57cec5SDimitry Andric       PythonDictionary &session_dict = GetSessionDictionary();
8800b57cec5SDimitry Andric       if (session_dict.IsValid()) {
8810b57cec5SDimitry Andric         if (GetEmbeddedInterpreterModuleObjects()) {
8820b57cec5SDimitry Andric           if (PyCallable_Check(m_run_one_line_function.get())) {
8830b57cec5SDimitry Andric             PythonObject pargs(
8840b57cec5SDimitry Andric                 PyRefType::Owned,
8850b57cec5SDimitry Andric                 Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
8860b57cec5SDimitry Andric             if (pargs.IsValid()) {
8870b57cec5SDimitry Andric               PythonObject return_value(
8880b57cec5SDimitry Andric                   PyRefType::Owned,
8890b57cec5SDimitry Andric                   PyObject_CallObject(m_run_one_line_function.get(),
8900b57cec5SDimitry Andric                                       pargs.get()));
8910b57cec5SDimitry Andric               if (return_value.IsValid())
8920b57cec5SDimitry Andric                 success = true;
8930b57cec5SDimitry Andric               else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
8940b57cec5SDimitry Andric                 PyErr_Print();
8950b57cec5SDimitry Andric                 PyErr_Clear();
8960b57cec5SDimitry Andric               }
8970b57cec5SDimitry Andric             }
8980b57cec5SDimitry Andric           }
8990b57cec5SDimitry Andric         }
9000b57cec5SDimitry Andric       }
9010b57cec5SDimitry Andric 
9025ffd83dbSDimitry Andric       io_redirect.Flush();
9030b57cec5SDimitry Andric     }
9040b57cec5SDimitry Andric 
9050b57cec5SDimitry Andric     if (success)
9060b57cec5SDimitry Andric       return true;
9070b57cec5SDimitry Andric 
9080b57cec5SDimitry Andric     // The one-liner failed.  Append the error message.
9090b57cec5SDimitry Andric     if (result) {
9100b57cec5SDimitry Andric       result->AppendErrorWithFormat(
9110b57cec5SDimitry Andric           "python failed attempting to evaluate '%s'\n", command_str.c_str());
9120b57cec5SDimitry Andric     }
9130b57cec5SDimitry Andric     return false;
9140b57cec5SDimitry Andric   }
9150b57cec5SDimitry Andric 
9160b57cec5SDimitry Andric   if (result)
9170b57cec5SDimitry Andric     result->AppendError("empty command passed to python\n");
9180b57cec5SDimitry Andric   return false;
9190b57cec5SDimitry Andric }
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
922e8d8bef9SDimitry Andric   LLDB_SCOPED_TIMER();
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric   Debugger &debugger = m_debugger;
9250b57cec5SDimitry Andric 
9260b57cec5SDimitry Andric   // At the moment, the only time the debugger does not have an input file
9270b57cec5SDimitry Andric   // handle is when this is called directly from Python, in which case it is
9280b57cec5SDimitry Andric   // both dangerous and unnecessary (not to mention confusing) to try to embed
9290b57cec5SDimitry Andric   // a running interpreter loop inside the already running Python interpreter
9300b57cec5SDimitry Andric   // loop, so we won't do it.
9310b57cec5SDimitry Andric 
9329dba64beSDimitry Andric   if (!debugger.GetInputFile().IsValid())
9330b57cec5SDimitry Andric     return;
9340b57cec5SDimitry Andric 
9350b57cec5SDimitry Andric   IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
9360b57cec5SDimitry Andric   if (io_handler_sp) {
9375ffd83dbSDimitry Andric     debugger.RunIOHandlerAsync(io_handler_sp);
9380b57cec5SDimitry Andric   }
9390b57cec5SDimitry Andric }
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Interrupt() {
94204eeddc0SDimitry Andric #if LLDB_USE_PYTHON_SET_INTERRUPT
94304eeddc0SDimitry Andric   // If the interpreter isn't evaluating any Python at the moment then return
94404eeddc0SDimitry Andric   // false to signal that this function didn't handle the interrupt and the
94504eeddc0SDimitry Andric   // next component should try handling it.
94604eeddc0SDimitry Andric   if (!IsExecutingPython())
94704eeddc0SDimitry Andric     return false;
94804eeddc0SDimitry Andric 
94904eeddc0SDimitry Andric   // Tell Python that it should pretend to have received a SIGINT.
95004eeddc0SDimitry Andric   PyErr_SetInterrupt();
95104eeddc0SDimitry Andric   // PyErr_SetInterrupt has no way to return an error so we can only pretend the
95204eeddc0SDimitry Andric   // signal got successfully handled and return true.
95304eeddc0SDimitry Andric   // Python 3.10 introduces PyErr_SetInterruptEx that could return an error, but
95404eeddc0SDimitry Andric   // the error handling is limited to checking the arguments which would be
95504eeddc0SDimitry Andric   // just our (hardcoded) input signal code SIGINT, so that's not useful at all.
95604eeddc0SDimitry Andric   return true;
95704eeddc0SDimitry Andric #else
95881ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Script);
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric   if (IsExecutingPython()) {
9610b57cec5SDimitry Andric     PyThreadState *state = PyThreadState_GET();
9620b57cec5SDimitry Andric     if (!state)
9630b57cec5SDimitry Andric       state = GetThreadState();
9640b57cec5SDimitry Andric     if (state) {
9650b57cec5SDimitry Andric       long tid = state->thread_id;
9660b57cec5SDimitry Andric       PyThreadState_Swap(state);
9670b57cec5SDimitry Andric       int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
9689dba64beSDimitry Andric       LLDB_LOGF(log,
9699dba64beSDimitry Andric                 "ScriptInterpreterPythonImpl::Interrupt() sending "
9700b57cec5SDimitry Andric                 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
9710b57cec5SDimitry Andric                 tid, num_threads);
9720b57cec5SDimitry Andric       return true;
9730b57cec5SDimitry Andric     }
9740b57cec5SDimitry Andric   }
9759dba64beSDimitry Andric   LLDB_LOGF(log,
9760b57cec5SDimitry Andric             "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
9770b57cec5SDimitry Andric             "can't interrupt");
9780b57cec5SDimitry Andric   return false;
97904eeddc0SDimitry Andric #endif
9800b57cec5SDimitry Andric }
9819dba64beSDimitry Andric 
9820b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
9830b57cec5SDimitry Andric     llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
9840b57cec5SDimitry Andric     void *ret_value, const ExecuteScriptOptions &options) {
9850b57cec5SDimitry Andric 
986fe6060f1SDimitry Andric   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
987fe6060f1SDimitry Andric       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
988fe6060f1SDimitry Andric           options.GetEnableIO(), m_debugger, /*result=*/nullptr);
989fe6060f1SDimitry Andric 
990fe6060f1SDimitry Andric   if (!io_redirect_or_error) {
991fe6060f1SDimitry Andric     llvm::consumeError(io_redirect_or_error.takeError());
992fe6060f1SDimitry Andric     return false;
993fe6060f1SDimitry Andric   }
994fe6060f1SDimitry Andric 
995fe6060f1SDimitry Andric   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
996fe6060f1SDimitry Andric 
9970b57cec5SDimitry Andric   Locker locker(this,
9980b57cec5SDimitry Andric                 Locker::AcquireLock | Locker::InitSession |
9990b57cec5SDimitry Andric                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
10000b57cec5SDimitry Andric                     Locker::NoSTDIN,
1001fe6060f1SDimitry Andric                 Locker::FreeAcquiredLock | Locker::TearDownSession,
1002fe6060f1SDimitry Andric                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1003fe6060f1SDimitry Andric                 io_redirect.GetErrorFile());
10040b57cec5SDimitry Andric 
10059dba64beSDimitry Andric   PythonModule &main_module = GetMainModule();
10069dba64beSDimitry Andric   PythonDictionary globals = main_module.GetDictionary();
10070b57cec5SDimitry Andric 
10080b57cec5SDimitry Andric   PythonDictionary locals = GetSessionDictionary();
10099dba64beSDimitry Andric   if (!locals.IsValid())
10109dba64beSDimitry Andric     locals = unwrapIgnoringErrors(
10119dba64beSDimitry Andric         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
10120b57cec5SDimitry Andric   if (!locals.IsValid())
10130b57cec5SDimitry Andric     locals = globals;
10140b57cec5SDimitry Andric 
10159dba64beSDimitry Andric   Expected<PythonObject> maybe_py_return =
10169dba64beSDimitry Andric       runStringOneLine(in_string, globals, locals);
10170b57cec5SDimitry Andric 
10189dba64beSDimitry Andric   if (!maybe_py_return) {
10199dba64beSDimitry Andric     llvm::handleAllErrors(
10209dba64beSDimitry Andric         maybe_py_return.takeError(),
10219dba64beSDimitry Andric         [&](PythonException &E) {
10229dba64beSDimitry Andric           E.Restore();
10239dba64beSDimitry Andric           if (options.GetMaskoutErrors()) {
10249dba64beSDimitry Andric             if (E.Matches(PyExc_SyntaxError)) {
10259dba64beSDimitry Andric               PyErr_Print();
10260b57cec5SDimitry Andric             }
10279dba64beSDimitry Andric             PyErr_Clear();
10289dba64beSDimitry Andric           }
10299dba64beSDimitry Andric         },
10309dba64beSDimitry Andric         [](const llvm::ErrorInfoBase &E) {});
10319dba64beSDimitry Andric     return false;
10320b57cec5SDimitry Andric   }
10330b57cec5SDimitry Andric 
10349dba64beSDimitry Andric   PythonObject py_return = std::move(maybe_py_return.get());
10359dba64beSDimitry Andric   assert(py_return.IsValid());
10369dba64beSDimitry Andric 
10370b57cec5SDimitry Andric   switch (return_type) {
10380b57cec5SDimitry Andric   case eScriptReturnTypeCharPtr: // "char *"
10390b57cec5SDimitry Andric   {
10400b57cec5SDimitry Andric     const char format[3] = "s#";
10419dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
10420b57cec5SDimitry Andric   }
10430b57cec5SDimitry Andric   case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
10440b57cec5SDimitry Andric                                        // Py_None
10450b57cec5SDimitry Andric   {
10460b57cec5SDimitry Andric     const char format[3] = "z";
10479dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
10480b57cec5SDimitry Andric   }
10490b57cec5SDimitry Andric   case eScriptReturnTypeBool: {
10500b57cec5SDimitry Andric     const char format[2] = "b";
10519dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
10520b57cec5SDimitry Andric   }
10530b57cec5SDimitry Andric   case eScriptReturnTypeShortInt: {
10540b57cec5SDimitry Andric     const char format[2] = "h";
10559dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (short *)ret_value);
10560b57cec5SDimitry Andric   }
10570b57cec5SDimitry Andric   case eScriptReturnTypeShortIntUnsigned: {
10580b57cec5SDimitry Andric     const char format[2] = "H";
10599dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
10600b57cec5SDimitry Andric   }
10610b57cec5SDimitry Andric   case eScriptReturnTypeInt: {
10620b57cec5SDimitry Andric     const char format[2] = "i";
10639dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (int *)ret_value);
10640b57cec5SDimitry Andric   }
10650b57cec5SDimitry Andric   case eScriptReturnTypeIntUnsigned: {
10660b57cec5SDimitry Andric     const char format[2] = "I";
10679dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
10680b57cec5SDimitry Andric   }
10690b57cec5SDimitry Andric   case eScriptReturnTypeLongInt: {
10700b57cec5SDimitry Andric     const char format[2] = "l";
10719dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (long *)ret_value);
10720b57cec5SDimitry Andric   }
10730b57cec5SDimitry Andric   case eScriptReturnTypeLongIntUnsigned: {
10740b57cec5SDimitry Andric     const char format[2] = "k";
10759dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
10760b57cec5SDimitry Andric   }
10770b57cec5SDimitry Andric   case eScriptReturnTypeLongLong: {
10780b57cec5SDimitry Andric     const char format[2] = "L";
10799dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
10800b57cec5SDimitry Andric   }
10810b57cec5SDimitry Andric   case eScriptReturnTypeLongLongUnsigned: {
10820b57cec5SDimitry Andric     const char format[2] = "K";
10839dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format,
10849dba64beSDimitry Andric                        (unsigned long long *)ret_value);
10850b57cec5SDimitry Andric   }
10860b57cec5SDimitry Andric   case eScriptReturnTypeFloat: {
10870b57cec5SDimitry Andric     const char format[2] = "f";
10889dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (float *)ret_value);
10890b57cec5SDimitry Andric   }
10900b57cec5SDimitry Andric   case eScriptReturnTypeDouble: {
10910b57cec5SDimitry Andric     const char format[2] = "d";
10929dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (double *)ret_value);
10930b57cec5SDimitry Andric   }
10940b57cec5SDimitry Andric   case eScriptReturnTypeChar: {
10950b57cec5SDimitry Andric     const char format[2] = "c";
10969dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (char *)ret_value);
10970b57cec5SDimitry Andric   }
10980b57cec5SDimitry Andric   case eScriptReturnTypeOpaqueObject: {
10999dba64beSDimitry Andric     *((PyObject **)ret_value) = py_return.release();
11009dba64beSDimitry Andric     return true;
11010b57cec5SDimitry Andric   }
11020b57cec5SDimitry Andric   }
1103480093f4SDimitry Andric   llvm_unreachable("Fully covered switch!");
11040b57cec5SDimitry Andric }
11050b57cec5SDimitry Andric 
11060b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
11070b57cec5SDimitry Andric     const char *in_string, const ExecuteScriptOptions &options) {
11089dba64beSDimitry Andric 
11099dba64beSDimitry Andric   if (in_string == nullptr)
11109dba64beSDimitry Andric     return Status();
11110b57cec5SDimitry Andric 
1112fe6060f1SDimitry Andric   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1113fe6060f1SDimitry Andric       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1114fe6060f1SDimitry Andric           options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1115fe6060f1SDimitry Andric 
1116fe6060f1SDimitry Andric   if (!io_redirect_or_error)
1117fe6060f1SDimitry Andric     return Status(io_redirect_or_error.takeError());
1118fe6060f1SDimitry Andric 
1119fe6060f1SDimitry Andric   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1120fe6060f1SDimitry Andric 
11210b57cec5SDimitry Andric   Locker locker(this,
11220b57cec5SDimitry Andric                 Locker::AcquireLock | Locker::InitSession |
11230b57cec5SDimitry Andric                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
11240b57cec5SDimitry Andric                     Locker::NoSTDIN,
1125fe6060f1SDimitry Andric                 Locker::FreeAcquiredLock | Locker::TearDownSession,
1126fe6060f1SDimitry Andric                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1127fe6060f1SDimitry Andric                 io_redirect.GetErrorFile());
11280b57cec5SDimitry Andric 
11299dba64beSDimitry Andric   PythonModule &main_module = GetMainModule();
11309dba64beSDimitry Andric   PythonDictionary globals = main_module.GetDictionary();
11310b57cec5SDimitry Andric 
11320b57cec5SDimitry Andric   PythonDictionary locals = GetSessionDictionary();
11330b57cec5SDimitry Andric   if (!locals.IsValid())
11349dba64beSDimitry Andric     locals = unwrapIgnoringErrors(
11359dba64beSDimitry Andric         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
11360b57cec5SDimitry Andric   if (!locals.IsValid())
11370b57cec5SDimitry Andric     locals = globals;
11380b57cec5SDimitry Andric 
11399dba64beSDimitry Andric   Expected<PythonObject> return_value =
11409dba64beSDimitry Andric       runStringMultiLine(in_string, globals, locals);
11410b57cec5SDimitry Andric 
11429dba64beSDimitry Andric   if (!return_value) {
11439dba64beSDimitry Andric     llvm::Error error =
11449dba64beSDimitry Andric         llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
11459dba64beSDimitry Andric           llvm::Error error = llvm::createStringError(
11469dba64beSDimitry Andric               llvm::inconvertibleErrorCode(), E.ReadBacktrace());
11479dba64beSDimitry Andric           if (!options.GetMaskoutErrors())
11489dba64beSDimitry Andric             E.Restore();
11490b57cec5SDimitry Andric           return error;
11509dba64beSDimitry Andric         });
11519dba64beSDimitry Andric     return Status(std::move(error));
11529dba64beSDimitry Andric   }
11539dba64beSDimitry Andric 
11549dba64beSDimitry Andric   return Status();
11550b57cec5SDimitry Andric }
11560b57cec5SDimitry Andric 
11570b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1158fe6060f1SDimitry Andric     std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
11590b57cec5SDimitry Andric     CommandReturnObject &result) {
11600b57cec5SDimitry Andric   m_active_io_handler = eIOHandlerBreakpoint;
11610b57cec5SDimitry Andric   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1162480093f4SDimitry Andric       "    ", *this, &bp_options_vec);
11630b57cec5SDimitry Andric }
11640b57cec5SDimitry Andric 
11650b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
11660b57cec5SDimitry Andric     WatchpointOptions *wp_options, CommandReturnObject &result) {
11670b57cec5SDimitry Andric   m_active_io_handler = eIOHandlerWatchpoint;
11680b57cec5SDimitry Andric   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1169480093f4SDimitry Andric       "    ", *this, wp_options);
11700b57cec5SDimitry Andric }
11710b57cec5SDimitry Andric 
1172480093f4SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1173fe6060f1SDimitry Andric     BreakpointOptions &bp_options, const char *function_name,
1174480093f4SDimitry Andric     StructuredData::ObjectSP extra_args_sp) {
1175480093f4SDimitry Andric   Status error;
11760b57cec5SDimitry Andric   // For now just cons up a oneliner that calls the provided function.
117706c3fb27SDimitry Andric   std::string function_signature = function_name;
1178480093f4SDimitry Andric 
1179480093f4SDimitry Andric   llvm::Expected<unsigned> maybe_args =
1180480093f4SDimitry Andric       GetMaxPositionalArgumentsForCallable(function_name);
1181480093f4SDimitry Andric   if (!maybe_args) {
1182480093f4SDimitry Andric     error.SetErrorStringWithFormat(
1183480093f4SDimitry Andric         "could not get num args: %s",
1184480093f4SDimitry Andric         llvm::toString(maybe_args.takeError()).c_str());
1185480093f4SDimitry Andric     return error;
1186480093f4SDimitry Andric   }
1187480093f4SDimitry Andric   size_t max_args = *maybe_args;
1188480093f4SDimitry Andric 
1189480093f4SDimitry Andric   bool uses_extra_args = false;
1190480093f4SDimitry Andric   if (max_args >= 4) {
1191480093f4SDimitry Andric     uses_extra_args = true;
119206c3fb27SDimitry Andric     function_signature += "(frame, bp_loc, extra_args, internal_dict)";
1193480093f4SDimitry Andric   } else if (max_args >= 3) {
1194480093f4SDimitry Andric     if (extra_args_sp) {
1195480093f4SDimitry Andric       error.SetErrorString("cannot pass extra_args to a three argument callback"
1196480093f4SDimitry Andric                           );
1197480093f4SDimitry Andric       return error;
1198480093f4SDimitry Andric     }
1199480093f4SDimitry Andric     uses_extra_args = false;
120006c3fb27SDimitry Andric     function_signature += "(frame, bp_loc, internal_dict)";
1201480093f4SDimitry Andric   } else {
1202480093f4SDimitry Andric     error.SetErrorStringWithFormat("expected 3 or 4 argument "
1203480093f4SDimitry Andric                                    "function, %s can only take %zu",
1204480093f4SDimitry Andric                                    function_name, max_args);
1205480093f4SDimitry Andric     return error;
1206480093f4SDimitry Andric   }
1207480093f4SDimitry Andric 
120806c3fb27SDimitry Andric   SetBreakpointCommandCallback(bp_options, function_signature.c_str(),
120906c3fb27SDimitry Andric                                extra_args_sp, uses_extra_args,
121006c3fb27SDimitry Andric                                /*is_callback=*/true);
1211480093f4SDimitry Andric   return error;
12120b57cec5SDimitry Andric }
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1215fe6060f1SDimitry Andric     BreakpointOptions &bp_options,
12160b57cec5SDimitry Andric     std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
12170b57cec5SDimitry Andric   Status error;
12180b57cec5SDimitry Andric   error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1219480093f4SDimitry Andric                                                 cmd_data_up->script_source,
122006c3fb27SDimitry Andric                                                 /*has_extra_args=*/false,
122106c3fb27SDimitry Andric                                                 /*is_callback=*/false);
12220b57cec5SDimitry Andric   if (error.Fail()) {
12230b57cec5SDimitry Andric     return error;
12240b57cec5SDimitry Andric   }
12250b57cec5SDimitry Andric   auto baton_sp =
12260b57cec5SDimitry Andric       std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1227fe6060f1SDimitry Andric   bp_options.SetCallback(
12280b57cec5SDimitry Andric       ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
12290b57cec5SDimitry Andric   return error;
12300b57cec5SDimitry Andric }
12310b57cec5SDimitry Andric 
12320b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
123306c3fb27SDimitry Andric     BreakpointOptions &bp_options, const char *command_body_text,
123406c3fb27SDimitry Andric     bool is_callback) {
123506c3fb27SDimitry Andric   return SetBreakpointCommandCallback(bp_options, command_body_text, {},
123606c3fb27SDimitry Andric                                       /*uses_extra_args=*/false, is_callback);
1237480093f4SDimitry Andric }
12380b57cec5SDimitry Andric 
1239480093f4SDimitry Andric // Set a Python one-liner as the callback for the breakpoint.
1240480093f4SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1241fe6060f1SDimitry Andric     BreakpointOptions &bp_options, const char *command_body_text,
124206c3fb27SDimitry Andric     StructuredData::ObjectSP extra_args_sp, bool uses_extra_args,
124306c3fb27SDimitry Andric     bool is_callback) {
1244480093f4SDimitry Andric   auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
12450b57cec5SDimitry Andric   // Split the command_body_text into lines, and pass that to
12460b57cec5SDimitry Andric   // GenerateBreakpointCommandCallbackData.  That will wrap the body in an
12470b57cec5SDimitry Andric   // auto-generated function, and return the function name in script_source.
12480b57cec5SDimitry Andric   // That is what the callback will actually invoke.
12490b57cec5SDimitry Andric 
12500b57cec5SDimitry Andric   data_up->user_source.SplitIntoLines(command_body_text);
125106c3fb27SDimitry Andric   Status error = GenerateBreakpointCommandCallbackData(
125206c3fb27SDimitry Andric       data_up->user_source, data_up->script_source, uses_extra_args,
125306c3fb27SDimitry Andric       is_callback);
12540b57cec5SDimitry Andric   if (error.Success()) {
12550b57cec5SDimitry Andric     auto baton_sp =
12560b57cec5SDimitry Andric         std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1257fe6060f1SDimitry Andric     bp_options.SetCallback(
12580b57cec5SDimitry Andric         ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
12590b57cec5SDimitry Andric     return error;
12605ffd83dbSDimitry Andric   }
12610b57cec5SDimitry Andric   return error;
12620b57cec5SDimitry Andric }
12630b57cec5SDimitry Andric 
12640b57cec5SDimitry Andric // Set a Python one-liner as the callback for the watchpoint.
12650b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
126606c3fb27SDimitry Andric     WatchpointOptions *wp_options, const char *user_input,
126706c3fb27SDimitry Andric     bool is_callback) {
12689dba64beSDimitry Andric   auto data_up = std::make_unique<WatchpointOptions::CommandData>();
12690b57cec5SDimitry Andric 
12700b57cec5SDimitry Andric   // It's necessary to set both user_source and script_source to the oneliner.
12710b57cec5SDimitry Andric   // The former is used to generate callback description (as in watchpoint
12720b57cec5SDimitry Andric   // command list) while the latter is used for Python to interpret during the
12730b57cec5SDimitry Andric   // actual callback.
12740b57cec5SDimitry Andric 
127506c3fb27SDimitry Andric   data_up->user_source.AppendString(user_input);
127606c3fb27SDimitry Andric   data_up->script_source.assign(user_input);
12770b57cec5SDimitry Andric 
127806c3fb27SDimitry Andric   if (GenerateWatchpointCommandCallbackData(
127906c3fb27SDimitry Andric           data_up->user_source, data_up->script_source, is_callback)) {
12800b57cec5SDimitry Andric     auto baton_sp =
12810b57cec5SDimitry Andric         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
12820b57cec5SDimitry Andric     wp_options->SetCallback(
12830b57cec5SDimitry Andric         ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
12840b57cec5SDimitry Andric   }
12850b57cec5SDimitry Andric }
12860b57cec5SDimitry Andric 
12870b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
12880b57cec5SDimitry Andric     StringList &function_def) {
12890b57cec5SDimitry Andric   // Convert StringList to one long, newline delimited, const char *.
12900b57cec5SDimitry Andric   std::string function_def_string(function_def.CopyList());
12910b57cec5SDimitry Andric 
12920b57cec5SDimitry Andric   Status error = ExecuteMultipleLines(
12930b57cec5SDimitry Andric       function_def_string.c_str(),
1294fe6060f1SDimitry Andric       ExecuteScriptOptions().SetEnableIO(false));
12950b57cec5SDimitry Andric   return error;
12960b57cec5SDimitry Andric }
12970b57cec5SDimitry Andric 
12980b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature,
129906c3fb27SDimitry Andric                                                      const StringList &input,
130006c3fb27SDimitry Andric                                                      bool is_callback) {
13010b57cec5SDimitry Andric   Status error;
13020b57cec5SDimitry Andric   int num_lines = input.GetSize();
13030b57cec5SDimitry Andric   if (num_lines == 0) {
13040b57cec5SDimitry Andric     error.SetErrorString("No input data.");
13050b57cec5SDimitry Andric     return error;
13060b57cec5SDimitry Andric   }
13070b57cec5SDimitry Andric 
13080b57cec5SDimitry Andric   if (!signature || *signature == 0) {
13090b57cec5SDimitry Andric     error.SetErrorString("No output function name.");
13100b57cec5SDimitry Andric     return error;
13110b57cec5SDimitry Andric   }
13120b57cec5SDimitry Andric 
13130b57cec5SDimitry Andric   StreamString sstr;
13140b57cec5SDimitry Andric   StringList auto_generated_function;
13150b57cec5SDimitry Andric   auto_generated_function.AppendString(signature);
13160b57cec5SDimitry Andric   auto_generated_function.AppendString(
13170b57cec5SDimitry Andric       "    global_dict = globals()"); // Grab the global dictionary
13180b57cec5SDimitry Andric   auto_generated_function.AppendString(
13190b57cec5SDimitry Andric       "    new_keys = internal_dict.keys()"); // Make a list of keys in the
13200b57cec5SDimitry Andric                                               // session dict
13210b57cec5SDimitry Andric   auto_generated_function.AppendString(
13220b57cec5SDimitry Andric       "    old_keys = global_dict.keys()"); // Save list of keys in global dict
13230b57cec5SDimitry Andric   auto_generated_function.AppendString(
13240b57cec5SDimitry Andric       "    global_dict.update(internal_dict)"); // Add the session dictionary
132506c3fb27SDimitry Andric                                                 // to the global dictionary.
13260b57cec5SDimitry Andric 
132706c3fb27SDimitry Andric   if (is_callback) {
132806c3fb27SDimitry Andric     // If the user input is a callback to a python function, make sure the input
132906c3fb27SDimitry Andric     // is only 1 line, otherwise appending the user input would break the
133006c3fb27SDimitry Andric     // generated wrapped function
133106c3fb27SDimitry Andric     if (num_lines == 1) {
133206c3fb27SDimitry Andric       sstr.Clear();
133306c3fb27SDimitry Andric       sstr.Printf("    __return_val = %s", input.GetStringAtIndex(0));
133406c3fb27SDimitry Andric       auto_generated_function.AppendString(sstr.GetData());
133506c3fb27SDimitry Andric     } else {
133606c3fb27SDimitry Andric       return Status("ScriptInterpreterPythonImpl::GenerateFunction(is_callback="
133706c3fb27SDimitry Andric                     "true) = ERROR: python function is multiline.");
133806c3fb27SDimitry Andric     }
133906c3fb27SDimitry Andric   } else {
134006c3fb27SDimitry Andric     auto_generated_function.AppendString(
134106c3fb27SDimitry Andric         "    __return_val = None"); // Initialize user callback return value.
134206c3fb27SDimitry Andric     auto_generated_function.AppendString(
134306c3fb27SDimitry Andric         "    def __user_code():"); // Create a nested function that will wrap
134406c3fb27SDimitry Andric                                    // the user input. This is necessary to
134506c3fb27SDimitry Andric                                    // capture the return value of the user input
134606c3fb27SDimitry Andric                                    // and prevent early returns.
13470b57cec5SDimitry Andric     for (int i = 0; i < num_lines; ++i) {
13480b57cec5SDimitry Andric       sstr.Clear();
13490b57cec5SDimitry Andric       sstr.Printf("      %s", input.GetStringAtIndex(i));
13500b57cec5SDimitry Andric       auto_generated_function.AppendString(sstr.GetData());
13510b57cec5SDimitry Andric     }
13520b57cec5SDimitry Andric     auto_generated_function.AppendString(
135306c3fb27SDimitry Andric         "    __return_val = __user_code()"); //  Call user code and capture
135406c3fb27SDimitry Andric                                              //  return value
135506c3fb27SDimitry Andric   }
135606c3fb27SDimitry Andric   auto_generated_function.AppendString(
13570b57cec5SDimitry Andric       "    for key in new_keys:"); // Iterate over all the keys from session
13580b57cec5SDimitry Andric                                    // dict
13590b57cec5SDimitry Andric   auto_generated_function.AppendString(
13600b57cec5SDimitry Andric       "        internal_dict[key] = global_dict[key]"); // Update session dict
13610b57cec5SDimitry Andric                                                         // values
13620b57cec5SDimitry Andric   auto_generated_function.AppendString(
13630b57cec5SDimitry Andric       "        if key not in old_keys:"); // If key was not originally in
13640b57cec5SDimitry Andric                                           // global dict
13650b57cec5SDimitry Andric   auto_generated_function.AppendString(
13660b57cec5SDimitry Andric       "            del global_dict[key]"); //  ...then remove key/value from
13670b57cec5SDimitry Andric                                            //  global dict
136806c3fb27SDimitry Andric   auto_generated_function.AppendString(
136906c3fb27SDimitry Andric       "    return __return_val"); //  Return the user callback return value.
13700b57cec5SDimitry Andric 
13710b57cec5SDimitry Andric   // Verify that the results are valid Python.
13720b57cec5SDimitry Andric   error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
13730b57cec5SDimitry Andric 
13740b57cec5SDimitry Andric   return error;
13750b57cec5SDimitry Andric }
13760b57cec5SDimitry Andric 
13770b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
13780b57cec5SDimitry Andric     StringList &user_input, std::string &output, const void *name_token) {
13790b57cec5SDimitry Andric   static uint32_t num_created_functions = 0;
13800b57cec5SDimitry Andric   user_input.RemoveBlankLines();
13810b57cec5SDimitry Andric   StreamString sstr;
13820b57cec5SDimitry Andric 
13830b57cec5SDimitry Andric   // Check to see if we have any data; if not, just return.
13840b57cec5SDimitry Andric   if (user_input.GetSize() == 0)
13850b57cec5SDimitry Andric     return false;
13860b57cec5SDimitry Andric 
13870b57cec5SDimitry Andric   // Take what the user wrote, wrap it all up inside one big auto-generated
13880b57cec5SDimitry Andric   // Python function, passing in the ValueObject as parameter to the function.
13890b57cec5SDimitry Andric 
13900b57cec5SDimitry Andric   std::string auto_generated_function_name(
13910b57cec5SDimitry Andric       GenerateUniqueName("lldb_autogen_python_type_print_func",
13920b57cec5SDimitry Andric                          num_created_functions, name_token));
13930b57cec5SDimitry Andric   sstr.Printf("def %s (valobj, internal_dict):",
13940b57cec5SDimitry Andric               auto_generated_function_name.c_str());
13950b57cec5SDimitry Andric 
139606c3fb27SDimitry Andric   if (!GenerateFunction(sstr.GetData(), user_input, /*is_callback=*/false)
139706c3fb27SDimitry Andric            .Success())
13980b57cec5SDimitry Andric     return false;
13990b57cec5SDimitry Andric 
14000b57cec5SDimitry Andric   // Store the name of the auto-generated function to be called.
14010b57cec5SDimitry Andric   output.assign(auto_generated_function_name);
14020b57cec5SDimitry Andric   return true;
14030b57cec5SDimitry Andric }
14040b57cec5SDimitry Andric 
14050b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
14060b57cec5SDimitry Andric     StringList &user_input, std::string &output) {
14070b57cec5SDimitry Andric   static uint32_t num_created_functions = 0;
14080b57cec5SDimitry Andric   user_input.RemoveBlankLines();
14090b57cec5SDimitry Andric   StreamString sstr;
14100b57cec5SDimitry Andric 
14110b57cec5SDimitry Andric   // Check to see if we have any data; if not, just return.
14120b57cec5SDimitry Andric   if (user_input.GetSize() == 0)
14130b57cec5SDimitry Andric     return false;
14140b57cec5SDimitry Andric 
14150b57cec5SDimitry Andric   std::string auto_generated_function_name(GenerateUniqueName(
14160b57cec5SDimitry Andric       "lldb_autogen_python_cmd_alias_func", num_created_functions));
14170b57cec5SDimitry Andric 
1418bdd1243dSDimitry Andric   sstr.Printf("def %s (debugger, args, exe_ctx, result, internal_dict):",
14190b57cec5SDimitry Andric               auto_generated_function_name.c_str());
14200b57cec5SDimitry Andric 
1421*0fca6ea1SDimitry Andric   if (!GenerateFunction(sstr.GetData(), user_input, /*is_callback=*/false)
142206c3fb27SDimitry Andric            .Success())
14230b57cec5SDimitry Andric     return false;
14240b57cec5SDimitry Andric 
14250b57cec5SDimitry Andric   // Store the name of the auto-generated function to be called.
14260b57cec5SDimitry Andric   output.assign(auto_generated_function_name);
14270b57cec5SDimitry Andric   return true;
14280b57cec5SDimitry Andric }
14290b57cec5SDimitry Andric 
14300b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
14310b57cec5SDimitry Andric     StringList &user_input, std::string &output, const void *name_token) {
14320b57cec5SDimitry Andric   static uint32_t num_created_classes = 0;
14330b57cec5SDimitry Andric   user_input.RemoveBlankLines();
14340b57cec5SDimitry Andric   int num_lines = user_input.GetSize();
14350b57cec5SDimitry Andric   StreamString sstr;
14360b57cec5SDimitry Andric 
14370b57cec5SDimitry Andric   // Check to see if we have any data; if not, just return.
14380b57cec5SDimitry Andric   if (user_input.GetSize() == 0)
14390b57cec5SDimitry Andric     return false;
14400b57cec5SDimitry Andric 
14410b57cec5SDimitry Andric   // Wrap all user input into a Python class
14420b57cec5SDimitry Andric 
14430b57cec5SDimitry Andric   std::string auto_generated_class_name(GenerateUniqueName(
14440b57cec5SDimitry Andric       "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
14450b57cec5SDimitry Andric 
14460b57cec5SDimitry Andric   StringList auto_generated_class;
14470b57cec5SDimitry Andric 
14480b57cec5SDimitry Andric   // Create the function name & definition string.
14490b57cec5SDimitry Andric 
14500b57cec5SDimitry Andric   sstr.Printf("class %s:", auto_generated_class_name.c_str());
14510b57cec5SDimitry Andric   auto_generated_class.AppendString(sstr.GetString());
14520b57cec5SDimitry Andric 
14530b57cec5SDimitry Andric   // Wrap everything up inside the class, increasing the indentation. we don't
14540b57cec5SDimitry Andric   // need to play any fancy indentation tricks here because there is no
14550b57cec5SDimitry Andric   // surrounding code whose indentation we need to honor
14560b57cec5SDimitry Andric   for (int i = 0; i < num_lines; ++i) {
14570b57cec5SDimitry Andric     sstr.Clear();
14580b57cec5SDimitry Andric     sstr.Printf("     %s", user_input.GetStringAtIndex(i));
14590b57cec5SDimitry Andric     auto_generated_class.AppendString(sstr.GetString());
14600b57cec5SDimitry Andric   }
14610b57cec5SDimitry Andric 
14620b57cec5SDimitry Andric   // Verify that the results are valid Python. (even though the method is
14630b57cec5SDimitry Andric   // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
14640b57cec5SDimitry Andric   // (TODO: rename that method to ExportDefinitionToInterpreter)
14650b57cec5SDimitry Andric   if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
14660b57cec5SDimitry Andric     return false;
14670b57cec5SDimitry Andric 
14680b57cec5SDimitry Andric   // Store the name of the auto-generated class
14690b57cec5SDimitry Andric 
14700b57cec5SDimitry Andric   output.assign(auto_generated_class_name);
14710b57cec5SDimitry Andric   return true;
14720b57cec5SDimitry Andric }
14730b57cec5SDimitry Andric 
14740b57cec5SDimitry Andric StructuredData::GenericSP
14750b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
14760b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
14770b57cec5SDimitry Andric     return StructuredData::GenericSP();
14780b57cec5SDimitry Andric 
147904eeddc0SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
148006c3fb27SDimitry Andric   PythonObject ret_val = SWIGBridge::LLDBSWIGPython_CreateFrameRecognizer(
148104eeddc0SDimitry Andric       class_name, m_dictionary_name.c_str());
14820b57cec5SDimitry Andric 
148304eeddc0SDimitry Andric   return StructuredData::GenericSP(
148404eeddc0SDimitry Andric       new StructuredPythonObject(std::move(ret_val)));
14850b57cec5SDimitry Andric }
14860b57cec5SDimitry Andric 
14870b57cec5SDimitry Andric lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
14880b57cec5SDimitry Andric     const StructuredData::ObjectSP &os_plugin_object_sp,
14890b57cec5SDimitry Andric     lldb::StackFrameSP frame_sp) {
14900b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
14910b57cec5SDimitry Andric 
14920b57cec5SDimitry Andric   if (!os_plugin_object_sp)
14930b57cec5SDimitry Andric     return ValueObjectListSP();
14940b57cec5SDimitry Andric 
14950b57cec5SDimitry Andric   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
14960b57cec5SDimitry Andric   if (!generic)
14970b57cec5SDimitry Andric     return nullptr;
14980b57cec5SDimitry Andric 
14990b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
15000b57cec5SDimitry Andric                            (PyObject *)generic->GetValue());
15010b57cec5SDimitry Andric 
15020b57cec5SDimitry Andric   if (!implementor.IsAllocated())
15030b57cec5SDimitry Andric     return ValueObjectListSP();
15040b57cec5SDimitry Andric 
150506c3fb27SDimitry Andric   PythonObject py_return(PyRefType::Owned,
150606c3fb27SDimitry Andric                          SWIGBridge::LLDBSwigPython_GetRecognizedArguments(
150706c3fb27SDimitry Andric                              implementor.get(), frame_sp));
15080b57cec5SDimitry Andric 
15090b57cec5SDimitry Andric   // if it fails, print the error but otherwise go on
15100b57cec5SDimitry Andric   if (PyErr_Occurred()) {
15110b57cec5SDimitry Andric     PyErr_Print();
15120b57cec5SDimitry Andric     PyErr_Clear();
15130b57cec5SDimitry Andric   }
15140b57cec5SDimitry Andric   if (py_return.get()) {
15150b57cec5SDimitry Andric     PythonList result_list(PyRefType::Borrowed, py_return.get());
15160b57cec5SDimitry Andric     ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
15170b57cec5SDimitry Andric     for (size_t i = 0; i < result_list.GetSize(); i++) {
15180b57cec5SDimitry Andric       PyObject *item = result_list.GetItemAtIndex(i).get();
15190b57cec5SDimitry Andric       lldb::SBValue *sb_value_ptr =
15200b57cec5SDimitry Andric           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
152106c3fb27SDimitry Andric       auto valobj_sp =
152206c3fb27SDimitry Andric           SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
15230b57cec5SDimitry Andric       if (valobj_sp)
15240b57cec5SDimitry Andric         result->Append(valobj_sp);
15250b57cec5SDimitry Andric     }
15260b57cec5SDimitry Andric     return result;
15270b57cec5SDimitry Andric   }
15280b57cec5SDimitry Andric   return ValueObjectListSP();
15290b57cec5SDimitry Andric }
15300b57cec5SDimitry Andric 
153106c3fb27SDimitry Andric ScriptedProcessInterfaceUP
153206c3fb27SDimitry Andric ScriptInterpreterPythonImpl::CreateScriptedProcessInterface() {
153306c3fb27SDimitry Andric   return std::make_unique<ScriptedProcessPythonInterface>(*this);
153406c3fb27SDimitry Andric }
153506c3fb27SDimitry Andric 
15365f757f3fSDimitry Andric ScriptedThreadInterfaceSP
15375f757f3fSDimitry Andric ScriptInterpreterPythonImpl::CreateScriptedThreadInterface() {
15385f757f3fSDimitry Andric   return std::make_shared<ScriptedThreadPythonInterface>(*this);
15395f757f3fSDimitry Andric }
15405f757f3fSDimitry Andric 
1541*0fca6ea1SDimitry Andric ScriptedThreadPlanInterfaceSP
1542*0fca6ea1SDimitry Andric ScriptInterpreterPythonImpl::CreateScriptedThreadPlanInterface() {
1543*0fca6ea1SDimitry Andric   return std::make_shared<ScriptedThreadPlanPythonInterface>(*this);
1544*0fca6ea1SDimitry Andric }
1545*0fca6ea1SDimitry Andric 
15465f757f3fSDimitry Andric OperatingSystemInterfaceSP
15475f757f3fSDimitry Andric ScriptInterpreterPythonImpl::CreateOperatingSystemInterface() {
15485f757f3fSDimitry Andric   return std::make_shared<OperatingSystemPythonInterface>(*this);
15495f757f3fSDimitry Andric }
15505f757f3fSDimitry Andric 
155106c3fb27SDimitry Andric StructuredData::ObjectSP
155206c3fb27SDimitry Andric ScriptInterpreterPythonImpl::CreateStructuredDataFromScriptObject(
155306c3fb27SDimitry Andric     ScriptObject obj) {
155406c3fb27SDimitry Andric   void *ptr = const_cast<void *>(obj.GetPointer());
155506c3fb27SDimitry Andric   PythonObject py_obj(PyRefType::Borrowed, static_cast<PyObject *>(ptr));
155606c3fb27SDimitry Andric   if (!py_obj.IsValid() || py_obj.IsNone())
155706c3fb27SDimitry Andric     return {};
155806c3fb27SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
155906c3fb27SDimitry Andric   return py_obj.CreateStructuredObject();
156006c3fb27SDimitry Andric }
156106c3fb27SDimitry Andric 
15620b57cec5SDimitry Andric StructuredData::GenericSP
15630b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
15640eae32dcSDimitry Andric     const char *class_name, const StructuredDataImpl &args_data,
15650b57cec5SDimitry Andric     lldb::BreakpointSP &bkpt_sp) {
15660b57cec5SDimitry Andric 
15670b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
15680b57cec5SDimitry Andric     return StructuredData::GenericSP();
15690b57cec5SDimitry Andric 
15700b57cec5SDimitry Andric   if (!bkpt_sp.get())
15710b57cec5SDimitry Andric     return StructuredData::GenericSP();
15720b57cec5SDimitry Andric 
15730b57cec5SDimitry Andric   Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
15740b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
1575e8d8bef9SDimitry Andric       GetPythonInterpreter(debugger);
15760b57cec5SDimitry Andric 
1577e8d8bef9SDimitry Andric   if (!python_interpreter)
15780b57cec5SDimitry Andric     return StructuredData::GenericSP();
15790b57cec5SDimitry Andric 
15800b57cec5SDimitry Andric   Locker py_lock(this,
15810b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
15820b57cec5SDimitry Andric 
158306c3fb27SDimitry Andric   PythonObject ret_val =
158406c3fb27SDimitry Andric       SWIGBridge::LLDBSwigPythonCreateScriptedBreakpointResolver(
15850b57cec5SDimitry Andric           class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
15860b57cec5SDimitry Andric           bkpt_sp);
15870b57cec5SDimitry Andric 
158804eeddc0SDimitry Andric   return StructuredData::GenericSP(
158904eeddc0SDimitry Andric       new StructuredPythonObject(std::move(ret_val)));
15900b57cec5SDimitry Andric }
15910b57cec5SDimitry Andric 
15920b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
15930b57cec5SDimitry Andric     StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
15940b57cec5SDimitry Andric   bool should_continue = false;
15950b57cec5SDimitry Andric 
15960b57cec5SDimitry Andric   if (implementor_sp) {
15970b57cec5SDimitry Andric     Locker py_lock(this,
15980b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
159906c3fb27SDimitry Andric     should_continue = SWIGBridge::LLDBSwigPythonCallBreakpointResolver(
16000b57cec5SDimitry Andric         implementor_sp->GetValue(), "__callback__", sym_ctx);
16010b57cec5SDimitry Andric     if (PyErr_Occurred()) {
16020b57cec5SDimitry Andric       PyErr_Print();
16030b57cec5SDimitry Andric       PyErr_Clear();
16040b57cec5SDimitry Andric     }
16050b57cec5SDimitry Andric   }
16060b57cec5SDimitry Andric   return should_continue;
16070b57cec5SDimitry Andric }
16080b57cec5SDimitry Andric 
16090b57cec5SDimitry Andric lldb::SearchDepth
16100b57cec5SDimitry Andric ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
16110b57cec5SDimitry Andric     StructuredData::GenericSP implementor_sp) {
16120b57cec5SDimitry Andric   int depth_as_int = lldb::eSearchDepthModule;
16130b57cec5SDimitry Andric   if (implementor_sp) {
16140b57cec5SDimitry Andric     Locker py_lock(this,
16150b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
161606c3fb27SDimitry Andric     depth_as_int = SWIGBridge::LLDBSwigPythonCallBreakpointResolver(
16170b57cec5SDimitry Andric         implementor_sp->GetValue(), "__get_depth__", nullptr);
16180b57cec5SDimitry Andric     if (PyErr_Occurred()) {
16190b57cec5SDimitry Andric       PyErr_Print();
16200b57cec5SDimitry Andric       PyErr_Clear();
16210b57cec5SDimitry Andric     }
16220b57cec5SDimitry Andric   }
16230b57cec5SDimitry Andric   if (depth_as_int == lldb::eSearchDepthInvalid)
16240b57cec5SDimitry Andric     return lldb::eSearchDepthModule;
16250b57cec5SDimitry Andric 
16260b57cec5SDimitry Andric   if (depth_as_int <= lldb::kLastSearchDepthKind)
16270b57cec5SDimitry Andric     return (lldb::SearchDepth)depth_as_int;
16280b57cec5SDimitry Andric   return lldb::eSearchDepthModule;
16290b57cec5SDimitry Andric }
16300b57cec5SDimitry Andric 
1631e8d8bef9SDimitry Andric StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
16320eae32dcSDimitry Andric     TargetSP target_sp, const char *class_name,
16330eae32dcSDimitry Andric     const StructuredDataImpl &args_data, Status &error) {
1634e8d8bef9SDimitry Andric 
1635e8d8bef9SDimitry Andric   if (!target_sp) {
1636e8d8bef9SDimitry Andric     error.SetErrorString("No target for scripted stop-hook.");
1637e8d8bef9SDimitry Andric     return StructuredData::GenericSP();
1638e8d8bef9SDimitry Andric   }
1639e8d8bef9SDimitry Andric 
1640e8d8bef9SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0') {
1641e8d8bef9SDimitry Andric     error.SetErrorString("No class name for scripted stop-hook.");
1642e8d8bef9SDimitry Andric     return StructuredData::GenericSP();
1643e8d8bef9SDimitry Andric   }
1644e8d8bef9SDimitry Andric 
1645e8d8bef9SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
1646e8d8bef9SDimitry Andric       GetPythonInterpreter(m_debugger);
1647e8d8bef9SDimitry Andric 
1648e8d8bef9SDimitry Andric   if (!python_interpreter) {
1649e8d8bef9SDimitry Andric     error.SetErrorString("No script interpreter for scripted stop-hook.");
1650e8d8bef9SDimitry Andric     return StructuredData::GenericSP();
1651e8d8bef9SDimitry Andric   }
1652e8d8bef9SDimitry Andric 
1653e8d8bef9SDimitry Andric   Locker py_lock(this,
1654e8d8bef9SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1655e8d8bef9SDimitry Andric 
165606c3fb27SDimitry Andric   PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateScriptedStopHook(
1657e8d8bef9SDimitry Andric       target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
1658e8d8bef9SDimitry Andric       args_data, error);
1659e8d8bef9SDimitry Andric 
166004eeddc0SDimitry Andric   return StructuredData::GenericSP(
166104eeddc0SDimitry Andric       new StructuredPythonObject(std::move(ret_val)));
1662e8d8bef9SDimitry Andric }
1663e8d8bef9SDimitry Andric 
1664e8d8bef9SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
1665e8d8bef9SDimitry Andric     StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
1666e8d8bef9SDimitry Andric     lldb::StreamSP stream_sp) {
1667e8d8bef9SDimitry Andric   assert(implementor_sp &&
1668e8d8bef9SDimitry Andric          "can't call a stop hook with an invalid implementor");
1669e8d8bef9SDimitry Andric   assert(stream_sp && "can't call a stop hook with an invalid stream");
1670e8d8bef9SDimitry Andric 
1671e8d8bef9SDimitry Andric   Locker py_lock(this,
1672e8d8bef9SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1673e8d8bef9SDimitry Andric 
1674e8d8bef9SDimitry Andric   lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
1675e8d8bef9SDimitry Andric 
167606c3fb27SDimitry Andric   bool ret_val = SWIGBridge::LLDBSwigPythonStopHookCallHandleStop(
1677e8d8bef9SDimitry Andric       implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
1678e8d8bef9SDimitry Andric   return ret_val;
1679e8d8bef9SDimitry Andric }
1680e8d8bef9SDimitry Andric 
16810b57cec5SDimitry Andric StructuredData::ObjectSP
16820b57cec5SDimitry Andric ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
16830b57cec5SDimitry Andric                                               lldb_private::Status &error) {
16840b57cec5SDimitry Andric   if (!FileSystem::Instance().Exists(file_spec)) {
16850b57cec5SDimitry Andric     error.SetErrorString("no such file");
16860b57cec5SDimitry Andric     return StructuredData::ObjectSP();
16870b57cec5SDimitry Andric   }
16880b57cec5SDimitry Andric 
16890b57cec5SDimitry Andric   StructuredData::ObjectSP module_sp;
16900b57cec5SDimitry Andric 
1691fe6060f1SDimitry Andric   LoadScriptOptions load_script_options =
1692fe6060f1SDimitry Andric       LoadScriptOptions().SetInitSession(true).SetSilent(false);
1693fe6060f1SDimitry Andric   if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1694fe6060f1SDimitry Andric                           error, &module_sp))
16950b57cec5SDimitry Andric     return module_sp;
16960b57cec5SDimitry Andric 
16970b57cec5SDimitry Andric   return StructuredData::ObjectSP();
16980b57cec5SDimitry Andric }
16990b57cec5SDimitry Andric 
17000b57cec5SDimitry Andric StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
17010b57cec5SDimitry Andric     StructuredData::ObjectSP plugin_module_sp, Target *target,
17020b57cec5SDimitry Andric     const char *setting_name, lldb_private::Status &error) {
17030b57cec5SDimitry Andric   if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
17040b57cec5SDimitry Andric     return StructuredData::DictionarySP();
17050b57cec5SDimitry Andric   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
17060b57cec5SDimitry Andric   if (!generic)
17070b57cec5SDimitry Andric     return StructuredData::DictionarySP();
17080b57cec5SDimitry Andric 
17090b57cec5SDimitry Andric   Locker py_lock(this,
17100b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
17110b57cec5SDimitry Andric   TargetSP target_sp(target->shared_from_this());
17120b57cec5SDimitry Andric 
171306c3fb27SDimitry Andric   auto setting = (PyObject *)SWIGBridge::LLDBSWIGPython_GetDynamicSetting(
17149dba64beSDimitry Andric       generic->GetValue(), setting_name, target_sp);
17159dba64beSDimitry Andric 
17169dba64beSDimitry Andric   if (!setting)
17179dba64beSDimitry Andric     return StructuredData::DictionarySP();
17189dba64beSDimitry Andric 
17199dba64beSDimitry Andric   PythonDictionary py_dict =
17209dba64beSDimitry Andric       unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
17219dba64beSDimitry Andric 
17229dba64beSDimitry Andric   if (!py_dict)
17239dba64beSDimitry Andric     return StructuredData::DictionarySP();
17249dba64beSDimitry Andric 
17250b57cec5SDimitry Andric   return py_dict.CreateStructuredDictionary();
17260b57cec5SDimitry Andric }
17270b57cec5SDimitry Andric 
17280b57cec5SDimitry Andric StructuredData::ObjectSP
17290b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
17300b57cec5SDimitry Andric     const char *class_name, lldb::ValueObjectSP valobj) {
17310b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
17320b57cec5SDimitry Andric     return StructuredData::ObjectSP();
17330b57cec5SDimitry Andric 
17340b57cec5SDimitry Andric   if (!valobj.get())
17350b57cec5SDimitry Andric     return StructuredData::ObjectSP();
17360b57cec5SDimitry Andric 
17370b57cec5SDimitry Andric   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
17380b57cec5SDimitry Andric   Target *target = exe_ctx.GetTargetPtr();
17390b57cec5SDimitry Andric 
17400b57cec5SDimitry Andric   if (!target)
17410b57cec5SDimitry Andric     return StructuredData::ObjectSP();
17420b57cec5SDimitry Andric 
17430b57cec5SDimitry Andric   Debugger &debugger = target->GetDebugger();
17440b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
1745e8d8bef9SDimitry Andric       GetPythonInterpreter(debugger);
17460b57cec5SDimitry Andric 
1747e8d8bef9SDimitry Andric   if (!python_interpreter)
17480b57cec5SDimitry Andric     return StructuredData::ObjectSP();
17490b57cec5SDimitry Andric 
17500b57cec5SDimitry Andric   Locker py_lock(this,
17510b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
175206c3fb27SDimitry Andric   PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateSyntheticProvider(
17530b57cec5SDimitry Andric       class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
17540b57cec5SDimitry Andric 
175504eeddc0SDimitry Andric   return StructuredData::ObjectSP(
175604eeddc0SDimitry Andric       new StructuredPythonObject(std::move(ret_val)));
17570b57cec5SDimitry Andric }
17580b57cec5SDimitry Andric 
17590b57cec5SDimitry Andric StructuredData::GenericSP
17600b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
17610b57cec5SDimitry Andric   DebuggerSP debugger_sp(m_debugger.shared_from_this());
17620b57cec5SDimitry Andric 
17630b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
17640b57cec5SDimitry Andric     return StructuredData::GenericSP();
17650b57cec5SDimitry Andric 
17660b57cec5SDimitry Andric   if (!debugger_sp.get())
17670b57cec5SDimitry Andric     return StructuredData::GenericSP();
17680b57cec5SDimitry Andric 
17690b57cec5SDimitry Andric   Locker py_lock(this,
17700b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
177106c3fb27SDimitry Andric   PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateCommandObject(
17720b57cec5SDimitry Andric       class_name, m_dictionary_name.c_str(), debugger_sp);
17730b57cec5SDimitry Andric 
177406c3fb27SDimitry Andric   if (ret_val.IsValid())
177504eeddc0SDimitry Andric     return StructuredData::GenericSP(
177604eeddc0SDimitry Andric         new StructuredPythonObject(std::move(ret_val)));
177706c3fb27SDimitry Andric   else
177806c3fb27SDimitry Andric     return {};
17790b57cec5SDimitry Andric }
17800b57cec5SDimitry Andric 
17810b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
17820b57cec5SDimitry Andric     const char *oneliner, std::string &output, const void *name_token) {
17830b57cec5SDimitry Andric   StringList input;
17840b57cec5SDimitry Andric   input.SplitIntoLines(oneliner, strlen(oneliner));
17850b57cec5SDimitry Andric   return GenerateTypeScriptFunction(input, output, name_token);
17860b57cec5SDimitry Andric }
17870b57cec5SDimitry Andric 
17880b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
17890b57cec5SDimitry Andric     const char *oneliner, std::string &output, const void *name_token) {
17900b57cec5SDimitry Andric   StringList input;
17910b57cec5SDimitry Andric   input.SplitIntoLines(oneliner, strlen(oneliner));
17920b57cec5SDimitry Andric   return GenerateTypeSynthClass(input, output, name_token);
17930b57cec5SDimitry Andric }
17940b57cec5SDimitry Andric 
17950b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
179606c3fb27SDimitry Andric     StringList &user_input, std::string &output, bool has_extra_args,
179706c3fb27SDimitry Andric     bool is_callback) {
17980b57cec5SDimitry Andric   static uint32_t num_created_functions = 0;
17990b57cec5SDimitry Andric   user_input.RemoveBlankLines();
18000b57cec5SDimitry Andric   StreamString sstr;
18010b57cec5SDimitry Andric   Status error;
18020b57cec5SDimitry Andric   if (user_input.GetSize() == 0) {
18030b57cec5SDimitry Andric     error.SetErrorString("No input data.");
18040b57cec5SDimitry Andric     return error;
18050b57cec5SDimitry Andric   }
18060b57cec5SDimitry Andric 
18070b57cec5SDimitry Andric   std::string auto_generated_function_name(GenerateUniqueName(
18080b57cec5SDimitry Andric       "lldb_autogen_python_bp_callback_func_", num_created_functions));
1809480093f4SDimitry Andric   if (has_extra_args)
1810480093f4SDimitry Andric     sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
1811480093f4SDimitry Andric                 auto_generated_function_name.c_str());
1812480093f4SDimitry Andric   else
18130b57cec5SDimitry Andric     sstr.Printf("def %s (frame, bp_loc, internal_dict):",
18140b57cec5SDimitry Andric                 auto_generated_function_name.c_str());
18150b57cec5SDimitry Andric 
181606c3fb27SDimitry Andric   error = GenerateFunction(sstr.GetData(), user_input, is_callback);
18170b57cec5SDimitry Andric   if (!error.Success())
18180b57cec5SDimitry Andric     return error;
18190b57cec5SDimitry Andric 
18200b57cec5SDimitry Andric   // Store the name of the auto-generated function to be called.
18210b57cec5SDimitry Andric   output.assign(auto_generated_function_name);
18220b57cec5SDimitry Andric   return error;
18230b57cec5SDimitry Andric }
18240b57cec5SDimitry Andric 
18250b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
182606c3fb27SDimitry Andric     StringList &user_input, std::string &output, bool is_callback) {
18270b57cec5SDimitry Andric   static uint32_t num_created_functions = 0;
18280b57cec5SDimitry Andric   user_input.RemoveBlankLines();
18290b57cec5SDimitry Andric   StreamString sstr;
18300b57cec5SDimitry Andric 
18310b57cec5SDimitry Andric   if (user_input.GetSize() == 0)
18320b57cec5SDimitry Andric     return false;
18330b57cec5SDimitry Andric 
18340b57cec5SDimitry Andric   std::string auto_generated_function_name(GenerateUniqueName(
18350b57cec5SDimitry Andric       "lldb_autogen_python_wp_callback_func_", num_created_functions));
18360b57cec5SDimitry Andric   sstr.Printf("def %s (frame, wp, internal_dict):",
18370b57cec5SDimitry Andric               auto_generated_function_name.c_str());
18380b57cec5SDimitry Andric 
183906c3fb27SDimitry Andric   if (!GenerateFunction(sstr.GetData(), user_input, is_callback).Success())
18400b57cec5SDimitry Andric     return false;
18410b57cec5SDimitry Andric 
18420b57cec5SDimitry Andric   // Store the name of the auto-generated function to be called.
18430b57cec5SDimitry Andric   output.assign(auto_generated_function_name);
18440b57cec5SDimitry Andric   return true;
18450b57cec5SDimitry Andric }
18460b57cec5SDimitry Andric 
18470b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetScriptedSummary(
18480b57cec5SDimitry Andric     const char *python_function_name, lldb::ValueObjectSP valobj,
18490b57cec5SDimitry Andric     StructuredData::ObjectSP &callee_wrapper_sp,
18500b57cec5SDimitry Andric     const TypeSummaryOptions &options, std::string &retval) {
18510b57cec5SDimitry Andric 
1852e8d8bef9SDimitry Andric   LLDB_SCOPED_TIMER();
18530b57cec5SDimitry Andric 
18540b57cec5SDimitry Andric   if (!valobj.get()) {
18550b57cec5SDimitry Andric     retval.assign("<no object>");
18560b57cec5SDimitry Andric     return false;
18570b57cec5SDimitry Andric   }
18580b57cec5SDimitry Andric 
18590b57cec5SDimitry Andric   void *old_callee = nullptr;
18600b57cec5SDimitry Andric   StructuredData::Generic *generic = nullptr;
18610b57cec5SDimitry Andric   if (callee_wrapper_sp) {
18620b57cec5SDimitry Andric     generic = callee_wrapper_sp->GetAsGeneric();
18630b57cec5SDimitry Andric     if (generic)
18640b57cec5SDimitry Andric       old_callee = generic->GetValue();
18650b57cec5SDimitry Andric   }
18660b57cec5SDimitry Andric   void *new_callee = old_callee;
18670b57cec5SDimitry Andric 
18680b57cec5SDimitry Andric   bool ret_val;
18690b57cec5SDimitry Andric   if (python_function_name && *python_function_name) {
18700b57cec5SDimitry Andric     {
18710b57cec5SDimitry Andric       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
18720b57cec5SDimitry Andric                                Locker::NoSTDIN);
18730b57cec5SDimitry Andric       {
18740b57cec5SDimitry Andric         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
18750b57cec5SDimitry Andric 
18760b57cec5SDimitry Andric         static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
18770b57cec5SDimitry Andric         Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
187806c3fb27SDimitry Andric         ret_val = SWIGBridge::LLDBSwigPythonCallTypeScript(
18790b57cec5SDimitry Andric             python_function_name, GetSessionDictionary().get(), valobj,
18800b57cec5SDimitry Andric             &new_callee, options_sp, retval);
18810b57cec5SDimitry Andric       }
18820b57cec5SDimitry Andric     }
18830b57cec5SDimitry Andric   } else {
18840b57cec5SDimitry Andric     retval.assign("<no function name>");
18850b57cec5SDimitry Andric     return false;
18860b57cec5SDimitry Andric   }
18870b57cec5SDimitry Andric 
188804eeddc0SDimitry Andric   if (new_callee && old_callee != new_callee) {
188904eeddc0SDimitry Andric     Locker py_lock(this,
189004eeddc0SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
189104eeddc0SDimitry Andric     callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
189204eeddc0SDimitry Andric         PythonObject(PyRefType::Borrowed, static_cast<PyObject *>(new_callee)));
189304eeddc0SDimitry Andric   }
18940b57cec5SDimitry Andric 
18950b57cec5SDimitry Andric   return ret_val;
18960b57cec5SDimitry Andric }
18970b57cec5SDimitry Andric 
1898bdd1243dSDimitry Andric bool ScriptInterpreterPythonImpl::FormatterCallbackFunction(
1899bdd1243dSDimitry Andric     const char *python_function_name, TypeImplSP type_impl_sp) {
1900bdd1243dSDimitry Andric   Locker py_lock(this,
1901bdd1243dSDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
190206c3fb27SDimitry Andric   return SWIGBridge::LLDBSwigPythonFormatterCallbackFunction(
1903bdd1243dSDimitry Andric       python_function_name, m_dictionary_name.c_str(), type_impl_sp);
1904bdd1243dSDimitry Andric }
1905bdd1243dSDimitry Andric 
19060b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
19070b57cec5SDimitry Andric     void *baton, StoppointCallbackContext *context, user_id_t break_id,
19080b57cec5SDimitry Andric     user_id_t break_loc_id) {
19090b57cec5SDimitry Andric   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
19100b57cec5SDimitry Andric   const char *python_function_name = bp_option_data->script_source.c_str();
19110b57cec5SDimitry Andric 
19120b57cec5SDimitry Andric   if (!context)
19130b57cec5SDimitry Andric     return true;
19140b57cec5SDimitry Andric 
19150b57cec5SDimitry Andric   ExecutionContext exe_ctx(context->exe_ctx_ref);
19160b57cec5SDimitry Andric   Target *target = exe_ctx.GetTargetPtr();
19170b57cec5SDimitry Andric 
19180b57cec5SDimitry Andric   if (!target)
19190b57cec5SDimitry Andric     return true;
19200b57cec5SDimitry Andric 
19210b57cec5SDimitry Andric   Debugger &debugger = target->GetDebugger();
19220b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
1923e8d8bef9SDimitry Andric       GetPythonInterpreter(debugger);
19240b57cec5SDimitry Andric 
1925e8d8bef9SDimitry Andric   if (!python_interpreter)
19260b57cec5SDimitry Andric     return true;
19270b57cec5SDimitry Andric 
19280b57cec5SDimitry Andric   if (python_function_name && python_function_name[0]) {
19290b57cec5SDimitry Andric     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
19300b57cec5SDimitry Andric     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
19310b57cec5SDimitry Andric     if (breakpoint_sp) {
19320b57cec5SDimitry Andric       const BreakpointLocationSP bp_loc_sp(
19330b57cec5SDimitry Andric           breakpoint_sp->FindLocationByID(break_loc_id));
19340b57cec5SDimitry Andric 
19350b57cec5SDimitry Andric       if (stop_frame_sp && bp_loc_sp) {
19360b57cec5SDimitry Andric         bool ret_val = true;
19370b57cec5SDimitry Andric         {
19380b57cec5SDimitry Andric           Locker py_lock(python_interpreter, Locker::AcquireLock |
19390b57cec5SDimitry Andric                                                  Locker::InitSession |
19400b57cec5SDimitry Andric                                                  Locker::NoSTDIN);
1941480093f4SDimitry Andric           Expected<bool> maybe_ret_val =
194206c3fb27SDimitry Andric               SWIGBridge::LLDBSwigPythonBreakpointCallbackFunction(
19430b57cec5SDimitry Andric                   python_function_name,
19440b57cec5SDimitry Andric                   python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
19450eae32dcSDimitry Andric                   bp_loc_sp, bp_option_data->m_extra_args);
1946480093f4SDimitry Andric 
1947480093f4SDimitry Andric           if (!maybe_ret_val) {
1948480093f4SDimitry Andric 
1949480093f4SDimitry Andric             llvm::handleAllErrors(
1950480093f4SDimitry Andric                 maybe_ret_val.takeError(),
1951480093f4SDimitry Andric                 [&](PythonException &E) {
1952480093f4SDimitry Andric                   debugger.GetErrorStream() << E.ReadBacktrace();
1953480093f4SDimitry Andric                 },
1954480093f4SDimitry Andric                 [&](const llvm::ErrorInfoBase &E) {
1955480093f4SDimitry Andric                   debugger.GetErrorStream() << E.message();
1956480093f4SDimitry Andric                 });
1957480093f4SDimitry Andric 
1958480093f4SDimitry Andric           } else {
1959480093f4SDimitry Andric             ret_val = maybe_ret_val.get();
1960480093f4SDimitry Andric           }
19610b57cec5SDimitry Andric         }
19620b57cec5SDimitry Andric         return ret_val;
19630b57cec5SDimitry Andric       }
19640b57cec5SDimitry Andric     }
19650b57cec5SDimitry Andric   }
19660b57cec5SDimitry Andric   // We currently always true so we stop in case anything goes wrong when
19670b57cec5SDimitry Andric   // trying to call the script function
19680b57cec5SDimitry Andric   return true;
19690b57cec5SDimitry Andric }
19700b57cec5SDimitry Andric 
19710b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
19720b57cec5SDimitry Andric     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
19730b57cec5SDimitry Andric   WatchpointOptions::CommandData *wp_option_data =
19740b57cec5SDimitry Andric       (WatchpointOptions::CommandData *)baton;
19750b57cec5SDimitry Andric   const char *python_function_name = wp_option_data->script_source.c_str();
19760b57cec5SDimitry Andric 
19770b57cec5SDimitry Andric   if (!context)
19780b57cec5SDimitry Andric     return true;
19790b57cec5SDimitry Andric 
19800b57cec5SDimitry Andric   ExecutionContext exe_ctx(context->exe_ctx_ref);
19810b57cec5SDimitry Andric   Target *target = exe_ctx.GetTargetPtr();
19820b57cec5SDimitry Andric 
19830b57cec5SDimitry Andric   if (!target)
19840b57cec5SDimitry Andric     return true;
19850b57cec5SDimitry Andric 
19860b57cec5SDimitry Andric   Debugger &debugger = target->GetDebugger();
19870b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
1988e8d8bef9SDimitry Andric       GetPythonInterpreter(debugger);
19890b57cec5SDimitry Andric 
1990e8d8bef9SDimitry Andric   if (!python_interpreter)
19910b57cec5SDimitry Andric     return true;
19920b57cec5SDimitry Andric 
19930b57cec5SDimitry Andric   if (python_function_name && python_function_name[0]) {
19940b57cec5SDimitry Andric     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
19950b57cec5SDimitry Andric     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
19960b57cec5SDimitry Andric     if (wp_sp) {
19970b57cec5SDimitry Andric       if (stop_frame_sp && wp_sp) {
19980b57cec5SDimitry Andric         bool ret_val = true;
19990b57cec5SDimitry Andric         {
20000b57cec5SDimitry Andric           Locker py_lock(python_interpreter, Locker::AcquireLock |
20010b57cec5SDimitry Andric                                                  Locker::InitSession |
20020b57cec5SDimitry Andric                                                  Locker::NoSTDIN);
200306c3fb27SDimitry Andric           ret_val = SWIGBridge::LLDBSwigPythonWatchpointCallbackFunction(
20040b57cec5SDimitry Andric               python_function_name,
20050b57cec5SDimitry Andric               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
20060b57cec5SDimitry Andric               wp_sp);
20070b57cec5SDimitry Andric         }
20080b57cec5SDimitry Andric         return ret_val;
20090b57cec5SDimitry Andric       }
20100b57cec5SDimitry Andric     }
20110b57cec5SDimitry Andric   }
20120b57cec5SDimitry Andric   // We currently always true so we stop in case anything goes wrong when
20130b57cec5SDimitry Andric   // trying to call the script function
20140b57cec5SDimitry Andric   return true;
20150b57cec5SDimitry Andric }
20160b57cec5SDimitry Andric 
20170b57cec5SDimitry Andric size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
20180b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
20190b57cec5SDimitry Andric   if (!implementor_sp)
20200b57cec5SDimitry Andric     return 0;
20210b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
20220b57cec5SDimitry Andric   if (!generic)
20230b57cec5SDimitry Andric     return 0;
20244824e7fdSDimitry Andric   auto *implementor = static_cast<PyObject *>(generic->GetValue());
20250b57cec5SDimitry Andric   if (!implementor)
20260b57cec5SDimitry Andric     return 0;
20270b57cec5SDimitry Andric 
20280b57cec5SDimitry Andric   size_t ret_val = 0;
20290b57cec5SDimitry Andric 
20300b57cec5SDimitry Andric   {
20310b57cec5SDimitry Andric     Locker py_lock(this,
20320b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
203306c3fb27SDimitry Andric     ret_val = SWIGBridge::LLDBSwigPython_CalculateNumChildren(implementor, max);
20340b57cec5SDimitry Andric   }
20350b57cec5SDimitry Andric 
20360b57cec5SDimitry Andric   return ret_val;
20370b57cec5SDimitry Andric }
20380b57cec5SDimitry Andric 
20390b57cec5SDimitry Andric lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
20400b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
20410b57cec5SDimitry Andric   if (!implementor_sp)
20420b57cec5SDimitry Andric     return lldb::ValueObjectSP();
20430b57cec5SDimitry Andric 
20440b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
20450b57cec5SDimitry Andric   if (!generic)
20460b57cec5SDimitry Andric     return lldb::ValueObjectSP();
20474824e7fdSDimitry Andric   auto *implementor = static_cast<PyObject *>(generic->GetValue());
20480b57cec5SDimitry Andric   if (!implementor)
20490b57cec5SDimitry Andric     return lldb::ValueObjectSP();
20500b57cec5SDimitry Andric 
20510b57cec5SDimitry Andric   lldb::ValueObjectSP ret_val;
20520b57cec5SDimitry Andric   {
20530b57cec5SDimitry Andric     Locker py_lock(this,
20540b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
205506c3fb27SDimitry Andric     PyObject *child_ptr =
205606c3fb27SDimitry Andric         SWIGBridge::LLDBSwigPython_GetChildAtIndex(implementor, idx);
20570b57cec5SDimitry Andric     if (child_ptr != nullptr && child_ptr != Py_None) {
20580b57cec5SDimitry Andric       lldb::SBValue *sb_value_ptr =
20590b57cec5SDimitry Andric           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
20600b57cec5SDimitry Andric       if (sb_value_ptr == nullptr)
20610b57cec5SDimitry Andric         Py_XDECREF(child_ptr);
20620b57cec5SDimitry Andric       else
206306c3fb27SDimitry Andric         ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
206406c3fb27SDimitry Andric             sb_value_ptr);
20650b57cec5SDimitry Andric     } else {
20660b57cec5SDimitry Andric       Py_XDECREF(child_ptr);
20670b57cec5SDimitry Andric     }
20680b57cec5SDimitry Andric   }
20690b57cec5SDimitry Andric 
20700b57cec5SDimitry Andric   return ret_val;
20710b57cec5SDimitry Andric }
20720b57cec5SDimitry Andric 
20730b57cec5SDimitry Andric int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
20740b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
20750b57cec5SDimitry Andric   if (!implementor_sp)
20760b57cec5SDimitry Andric     return UINT32_MAX;
20770b57cec5SDimitry Andric 
20780b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
20790b57cec5SDimitry Andric   if (!generic)
20800b57cec5SDimitry Andric     return UINT32_MAX;
20814824e7fdSDimitry Andric   auto *implementor = static_cast<PyObject *>(generic->GetValue());
20820b57cec5SDimitry Andric   if (!implementor)
20830b57cec5SDimitry Andric     return UINT32_MAX;
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric   int ret_val = UINT32_MAX;
20860b57cec5SDimitry Andric 
20870b57cec5SDimitry Andric   {
20880b57cec5SDimitry Andric     Locker py_lock(this,
20890b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
209006c3fb27SDimitry Andric     ret_val = SWIGBridge::LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
20910b57cec5SDimitry Andric   }
20920b57cec5SDimitry Andric 
20930b57cec5SDimitry Andric   return ret_val;
20940b57cec5SDimitry Andric }
20950b57cec5SDimitry Andric 
20960b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
20970b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp) {
20980b57cec5SDimitry Andric   bool ret_val = false;
20990b57cec5SDimitry Andric 
21000b57cec5SDimitry Andric   if (!implementor_sp)
21010b57cec5SDimitry Andric     return ret_val;
21020b57cec5SDimitry Andric 
21030b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
21040b57cec5SDimitry Andric   if (!generic)
21050b57cec5SDimitry Andric     return ret_val;
21064824e7fdSDimitry Andric   auto *implementor = static_cast<PyObject *>(generic->GetValue());
21070b57cec5SDimitry Andric   if (!implementor)
21080b57cec5SDimitry Andric     return ret_val;
21090b57cec5SDimitry Andric 
21100b57cec5SDimitry Andric   {
21110b57cec5SDimitry Andric     Locker py_lock(this,
21120b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
211306c3fb27SDimitry Andric     ret_val =
211406c3fb27SDimitry Andric         SWIGBridge::LLDBSwigPython_UpdateSynthProviderInstance(implementor);
21150b57cec5SDimitry Andric   }
21160b57cec5SDimitry Andric 
21170b57cec5SDimitry Andric   return ret_val;
21180b57cec5SDimitry Andric }
21190b57cec5SDimitry Andric 
21200b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
21210b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp) {
21220b57cec5SDimitry Andric   bool ret_val = false;
21230b57cec5SDimitry Andric 
21240b57cec5SDimitry Andric   if (!implementor_sp)
21250b57cec5SDimitry Andric     return ret_val;
21260b57cec5SDimitry Andric 
21270b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
21280b57cec5SDimitry Andric   if (!generic)
21290b57cec5SDimitry Andric     return ret_val;
21304824e7fdSDimitry Andric   auto *implementor = static_cast<PyObject *>(generic->GetValue());
21310b57cec5SDimitry Andric   if (!implementor)
21320b57cec5SDimitry Andric     return ret_val;
21330b57cec5SDimitry Andric 
21340b57cec5SDimitry Andric   {
21350b57cec5SDimitry Andric     Locker py_lock(this,
21360b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
213706c3fb27SDimitry Andric     ret_val = SWIGBridge::LLDBSwigPython_MightHaveChildrenSynthProviderInstance(
213806c3fb27SDimitry Andric         implementor);
21390b57cec5SDimitry Andric   }
21400b57cec5SDimitry Andric 
21410b57cec5SDimitry Andric   return ret_val;
21420b57cec5SDimitry Andric }
21430b57cec5SDimitry Andric 
21440b57cec5SDimitry Andric lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
21450b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp) {
21460b57cec5SDimitry Andric   lldb::ValueObjectSP ret_val(nullptr);
21470b57cec5SDimitry Andric 
21480b57cec5SDimitry Andric   if (!implementor_sp)
21490b57cec5SDimitry Andric     return ret_val;
21500b57cec5SDimitry Andric 
21510b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
21520b57cec5SDimitry Andric   if (!generic)
21530b57cec5SDimitry Andric     return ret_val;
21544824e7fdSDimitry Andric   auto *implementor = static_cast<PyObject *>(generic->GetValue());
21550b57cec5SDimitry Andric   if (!implementor)
21560b57cec5SDimitry Andric     return ret_val;
21570b57cec5SDimitry Andric 
21580b57cec5SDimitry Andric   {
21590b57cec5SDimitry Andric     Locker py_lock(this,
21600b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
21614824e7fdSDimitry Andric     PyObject *child_ptr =
216206c3fb27SDimitry Andric         SWIGBridge::LLDBSwigPython_GetValueSynthProviderInstance(implementor);
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 
21790b57cec5SDimitry Andric ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
21800b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp) {
21810b57cec5SDimitry Andric   Locker py_lock(this,
21820b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
21830b57cec5SDimitry Andric 
2184bdd1243dSDimitry Andric   if (!implementor_sp)
2185bdd1243dSDimitry Andric     return {};
2186bdd1243dSDimitry Andric 
2187bdd1243dSDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2188bdd1243dSDimitry Andric   if (!generic)
2189bdd1243dSDimitry Andric     return {};
2190bdd1243dSDimitry Andric 
2191bdd1243dSDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
2192bdd1243dSDimitry Andric                            (PyObject *)generic->GetValue());
2193bdd1243dSDimitry Andric   if (!implementor.IsAllocated())
2194bdd1243dSDimitry Andric     return {};
2195bdd1243dSDimitry Andric 
2196bdd1243dSDimitry Andric   llvm::Expected<PythonObject> expected_py_return =
2197bdd1243dSDimitry Andric       implementor.CallMethod("get_type_name");
2198bdd1243dSDimitry Andric 
2199bdd1243dSDimitry Andric   if (!expected_py_return) {
2200bdd1243dSDimitry Andric     llvm::consumeError(expected_py_return.takeError());
2201bdd1243dSDimitry Andric     return {};
2202bdd1243dSDimitry Andric   }
2203bdd1243dSDimitry Andric 
2204bdd1243dSDimitry Andric   PythonObject py_return = std::move(expected_py_return.get());
22055f757f3fSDimitry Andric   if (!py_return.IsAllocated() || !PythonString::Check(py_return.get()))
22065f757f3fSDimitry Andric     return {};
22070b57cec5SDimitry Andric 
22085f757f3fSDimitry Andric   PythonString type_name(PyRefType::Borrowed, py_return.get());
22095f757f3fSDimitry Andric   return ConstString(type_name.GetString());
22100b57cec5SDimitry Andric }
22110b57cec5SDimitry Andric 
22120b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
22130b57cec5SDimitry Andric     const char *impl_function, Process *process, std::string &output,
22140b57cec5SDimitry Andric     Status &error) {
22150b57cec5SDimitry Andric   bool ret_val;
22160b57cec5SDimitry Andric   if (!process) {
22170b57cec5SDimitry Andric     error.SetErrorString("no process");
22180b57cec5SDimitry Andric     return false;
22190b57cec5SDimitry Andric   }
22200b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
22210b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
22220b57cec5SDimitry Andric     return false;
22230b57cec5SDimitry Andric   }
22240b57cec5SDimitry Andric 
22250b57cec5SDimitry Andric   {
22260b57cec5SDimitry Andric     Locker py_lock(this,
22270b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
222806c3fb27SDimitry Andric     ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordProcess(
22294824e7fdSDimitry Andric         impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
22304824e7fdSDimitry Andric         output);
22310b57cec5SDimitry Andric     if (!ret_val)
22320b57cec5SDimitry Andric       error.SetErrorString("python script evaluation failed");
22330b57cec5SDimitry Andric   }
22340b57cec5SDimitry Andric   return ret_val;
22350b57cec5SDimitry Andric }
22360b57cec5SDimitry Andric 
22370b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
22380b57cec5SDimitry Andric     const char *impl_function, Thread *thread, std::string &output,
22390b57cec5SDimitry Andric     Status &error) {
22400b57cec5SDimitry Andric   if (!thread) {
22410b57cec5SDimitry Andric     error.SetErrorString("no thread");
22420b57cec5SDimitry Andric     return false;
22430b57cec5SDimitry Andric   }
22440b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
22450b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
22460b57cec5SDimitry Andric     return false;
22470b57cec5SDimitry Andric   }
22480b57cec5SDimitry Andric 
22490b57cec5SDimitry Andric   Locker py_lock(this,
22500b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
225106c3fb27SDimitry Andric   if (std::optional<std::string> result =
225206c3fb27SDimitry Andric           SWIGBridge::LLDBSWIGPythonRunScriptKeywordThread(
22530eae32dcSDimitry Andric               impl_function, m_dictionary_name.c_str(),
22540eae32dcSDimitry Andric               thread->shared_from_this())) {
22550eae32dcSDimitry Andric     output = std::move(*result);
22560eae32dcSDimitry Andric     return true;
22570b57cec5SDimitry Andric   }
22580eae32dcSDimitry Andric   error.SetErrorString("python script evaluation failed");
22590eae32dcSDimitry Andric   return false;
22600b57cec5SDimitry Andric }
22610b57cec5SDimitry Andric 
22620b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
22630b57cec5SDimitry Andric     const char *impl_function, Target *target, std::string &output,
22640b57cec5SDimitry Andric     Status &error) {
22650b57cec5SDimitry Andric   bool ret_val;
22660b57cec5SDimitry Andric   if (!target) {
22670b57cec5SDimitry Andric     error.SetErrorString("no thread");
22680b57cec5SDimitry Andric     return false;
22690b57cec5SDimitry Andric   }
22700b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
22710b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
22720b57cec5SDimitry Andric     return false;
22730b57cec5SDimitry Andric   }
22740b57cec5SDimitry Andric 
22750b57cec5SDimitry Andric   {
22760b57cec5SDimitry Andric     TargetSP target_sp(target->shared_from_this());
22770b57cec5SDimitry Andric     Locker py_lock(this,
22780b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
227906c3fb27SDimitry Andric     ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordTarget(
22800b57cec5SDimitry Andric         impl_function, m_dictionary_name.c_str(), target_sp, output);
22810b57cec5SDimitry Andric     if (!ret_val)
22820b57cec5SDimitry Andric       error.SetErrorString("python script evaluation failed");
22830b57cec5SDimitry Andric   }
22840b57cec5SDimitry Andric   return ret_val;
22850b57cec5SDimitry Andric }
22860b57cec5SDimitry Andric 
22870b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
22880b57cec5SDimitry Andric     const char *impl_function, StackFrame *frame, std::string &output,
22890b57cec5SDimitry Andric     Status &error) {
22900b57cec5SDimitry Andric   if (!frame) {
22910b57cec5SDimitry Andric     error.SetErrorString("no frame");
22920b57cec5SDimitry Andric     return false;
22930b57cec5SDimitry Andric   }
22940b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
22950b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
22960b57cec5SDimitry Andric     return false;
22970b57cec5SDimitry Andric   }
22980b57cec5SDimitry Andric 
22990b57cec5SDimitry Andric   Locker py_lock(this,
23000b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
230106c3fb27SDimitry Andric   if (std::optional<std::string> result =
230206c3fb27SDimitry Andric           SWIGBridge::LLDBSWIGPythonRunScriptKeywordFrame(
23030eae32dcSDimitry Andric               impl_function, m_dictionary_name.c_str(),
23040eae32dcSDimitry Andric               frame->shared_from_this())) {
23050eae32dcSDimitry Andric     output = std::move(*result);
23060eae32dcSDimitry Andric     return true;
23070b57cec5SDimitry Andric   }
23080eae32dcSDimitry Andric   error.SetErrorString("python script evaluation failed");
23090eae32dcSDimitry Andric   return false;
23100b57cec5SDimitry Andric }
23110b57cec5SDimitry Andric 
23120b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
23130b57cec5SDimitry Andric     const char *impl_function, ValueObject *value, std::string &output,
23140b57cec5SDimitry Andric     Status &error) {
23150b57cec5SDimitry Andric   bool ret_val;
23160b57cec5SDimitry Andric   if (!value) {
23170b57cec5SDimitry Andric     error.SetErrorString("no value");
23180b57cec5SDimitry Andric     return false;
23190b57cec5SDimitry Andric   }
23200b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
23210b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
23220b57cec5SDimitry Andric     return false;
23230b57cec5SDimitry Andric   }
23240b57cec5SDimitry Andric 
23250b57cec5SDimitry Andric   {
23260b57cec5SDimitry Andric     Locker py_lock(this,
23270b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
232806c3fb27SDimitry Andric     ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordValue(
23294824e7fdSDimitry Andric         impl_function, m_dictionary_name.c_str(), value->GetSP(), output);
23300b57cec5SDimitry Andric     if (!ret_val)
23310b57cec5SDimitry Andric       error.SetErrorString("python script evaluation failed");
23320b57cec5SDimitry Andric   }
23330b57cec5SDimitry Andric   return ret_val;
23340b57cec5SDimitry Andric }
23350b57cec5SDimitry Andric 
23360b57cec5SDimitry Andric uint64_t replace_all(std::string &str, const std::string &oldStr,
23370b57cec5SDimitry Andric                      const std::string &newStr) {
23380b57cec5SDimitry Andric   size_t pos = 0;
23390b57cec5SDimitry Andric   uint64_t matches = 0;
23400b57cec5SDimitry Andric   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
23410b57cec5SDimitry Andric     matches++;
23420b57cec5SDimitry Andric     str.replace(pos, oldStr.length(), newStr);
23430b57cec5SDimitry Andric     pos += newStr.length();
23440b57cec5SDimitry Andric   }
23450b57cec5SDimitry Andric   return matches;
23460b57cec5SDimitry Andric }
23470b57cec5SDimitry Andric 
23480b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2349fe6060f1SDimitry Andric     const char *pathname, const LoadScriptOptions &options,
2350fe6060f1SDimitry Andric     lldb_private::Status &error, StructuredData::ObjectSP *module_sp,
2351fe6060f1SDimitry Andric     FileSpec extra_search_dir) {
2352e8d8bef9SDimitry Andric   namespace fs = llvm::sys::fs;
2353e8d8bef9SDimitry Andric   namespace path = llvm::sys::path;
2354e8d8bef9SDimitry Andric 
2355fe6060f1SDimitry Andric   ExecuteScriptOptions exc_options = ExecuteScriptOptions()
2356fe6060f1SDimitry Andric                                          .SetEnableIO(!options.GetSilent())
2357fe6060f1SDimitry Andric                                          .SetSetLLDBGlobals(false);
2358fe6060f1SDimitry Andric 
23590b57cec5SDimitry Andric   if (!pathname || !pathname[0]) {
2360fcaf7f86SDimitry Andric     error.SetErrorString("empty path");
23610b57cec5SDimitry Andric     return false;
23620b57cec5SDimitry Andric   }
23630b57cec5SDimitry Andric 
2364fe6060f1SDimitry Andric   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2365fe6060f1SDimitry Andric       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2366fe6060f1SDimitry Andric           exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2367fe6060f1SDimitry Andric 
2368fe6060f1SDimitry Andric   if (!io_redirect_or_error) {
2369fe6060f1SDimitry Andric     error = io_redirect_or_error.takeError();
2370fe6060f1SDimitry Andric     return false;
2371fe6060f1SDimitry Andric   }
2372fe6060f1SDimitry Andric 
2373fe6060f1SDimitry Andric   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
23740b57cec5SDimitry Andric 
23750b57cec5SDimitry Andric   // Before executing Python code, lock the GIL.
23760b57cec5SDimitry Andric   Locker py_lock(this,
23770b57cec5SDimitry Andric                  Locker::AcquireLock |
2378fe6060f1SDimitry Andric                      (options.GetInitSession() ? Locker::InitSession : 0) |
2379fe6060f1SDimitry Andric                      Locker::NoSTDIN,
23800b57cec5SDimitry Andric                  Locker::FreeAcquiredLock |
2381fe6060f1SDimitry Andric                      (options.GetInitSession() ? Locker::TearDownSession : 0),
2382fe6060f1SDimitry Andric                  io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2383fe6060f1SDimitry Andric                  io_redirect.GetErrorFile());
23840b57cec5SDimitry Andric 
2385fe6060f1SDimitry Andric   auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2386e8d8bef9SDimitry Andric     if (directory.empty()) {
2387*0fca6ea1SDimitry Andric       return llvm::createStringError("invalid directory name");
23880b57cec5SDimitry Andric     }
23890b57cec5SDimitry Andric 
23900b57cec5SDimitry Andric     replace_all(directory, "\\", "\\\\");
23910b57cec5SDimitry Andric     replace_all(directory, "'", "\\'");
23920b57cec5SDimitry Andric 
2393e8d8bef9SDimitry Andric     // Make sure that Python has "directory" in the search path.
23940b57cec5SDimitry Andric     StreamString command_stream;
23950b57cec5SDimitry Andric     command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
23960b57cec5SDimitry Andric                           "sys.path.insert(1,'%s');\n\n",
23970b57cec5SDimitry Andric                           directory.c_str(), directory.c_str());
23980b57cec5SDimitry Andric     bool syspath_retval =
2399fe6060f1SDimitry Andric         ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
2400*0fca6ea1SDimitry Andric     if (!syspath_retval)
2401*0fca6ea1SDimitry Andric       return llvm::createStringError("Python sys.path handling failed");
24020b57cec5SDimitry Andric 
2403e8d8bef9SDimitry Andric     return llvm::Error::success();
2404e8d8bef9SDimitry Andric   };
2405e8d8bef9SDimitry Andric 
2406e8d8bef9SDimitry Andric   std::string module_name(pathname);
2407fe6060f1SDimitry Andric   bool possible_package = false;
2408e8d8bef9SDimitry Andric 
2409e8d8bef9SDimitry Andric   if (extra_search_dir) {
2410e8d8bef9SDimitry Andric     if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2411e8d8bef9SDimitry Andric       error = std::move(e);
2412e8d8bef9SDimitry Andric       return false;
24130b57cec5SDimitry Andric     }
24140b57cec5SDimitry Andric   } else {
2415e8d8bef9SDimitry Andric     FileSpec module_file(pathname);
2416e8d8bef9SDimitry Andric     FileSystem::Instance().Resolve(module_file);
2417e8d8bef9SDimitry Andric 
2418e8d8bef9SDimitry Andric     fs::file_status st;
2419e8d8bef9SDimitry Andric     std::error_code ec = status(module_file.GetPath(), st);
2420e8d8bef9SDimitry Andric 
2421e8d8bef9SDimitry Andric     if (ec || st.type() == fs::file_type::status_error ||
2422e8d8bef9SDimitry Andric         st.type() == fs::file_type::type_unknown ||
2423e8d8bef9SDimitry Andric         st.type() == fs::file_type::file_not_found) {
2424e8d8bef9SDimitry Andric       // if not a valid file of any sort, check if it might be a filename still
2425e8d8bef9SDimitry Andric       // dot can't be used but / and \ can, and if either is found, reject
2426e8d8bef9SDimitry Andric       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2427fcaf7f86SDimitry Andric         error.SetErrorStringWithFormatv("invalid pathname '{0}'", pathname);
2428e8d8bef9SDimitry Andric         return false;
2429e8d8bef9SDimitry Andric       }
2430e8d8bef9SDimitry Andric       // Not a filename, probably a package of some sort, let it go through.
2431fe6060f1SDimitry Andric       possible_package = true;
2432e8d8bef9SDimitry Andric     } else if (is_directory(st) || is_regular_file(st)) {
2433e8d8bef9SDimitry Andric       if (module_file.GetDirectory().IsEmpty()) {
2434fcaf7f86SDimitry Andric         error.SetErrorStringWithFormatv("invalid directory name '{0}'", pathname);
2435e8d8bef9SDimitry Andric         return false;
2436e8d8bef9SDimitry Andric       }
2437e8d8bef9SDimitry Andric       if (llvm::Error e =
2438e8d8bef9SDimitry Andric               ExtendSysPath(module_file.GetDirectory().GetCString())) {
2439e8d8bef9SDimitry Andric         error = std::move(e);
2440e8d8bef9SDimitry Andric         return false;
2441e8d8bef9SDimitry Andric       }
2442e8d8bef9SDimitry Andric       module_name = module_file.GetFilename().GetCString();
2443e8d8bef9SDimitry Andric     } else {
24440b57cec5SDimitry Andric       error.SetErrorString("no known way to import this module specification");
24450b57cec5SDimitry Andric       return false;
24460b57cec5SDimitry Andric     }
2447e8d8bef9SDimitry Andric   }
2448e8d8bef9SDimitry Andric 
2449e8d8bef9SDimitry Andric   // Strip .py or .pyc extension
2450e8d8bef9SDimitry Andric   llvm::StringRef extension = llvm::sys::path::extension(module_name);
2451e8d8bef9SDimitry Andric   if (!extension.empty()) {
2452e8d8bef9SDimitry Andric     if (extension == ".py")
2453e8d8bef9SDimitry Andric       module_name.resize(module_name.length() - 3);
2454e8d8bef9SDimitry Andric     else if (extension == ".pyc")
2455e8d8bef9SDimitry Andric       module_name.resize(module_name.length() - 4);
2456e8d8bef9SDimitry Andric   }
24570b57cec5SDimitry Andric 
2458fe6060f1SDimitry Andric   if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2459fe6060f1SDimitry Andric     error.SetErrorStringWithFormat(
2460fe6060f1SDimitry Andric         "Python does not allow dots in module names: %s", module_name.c_str());
2461fe6060f1SDimitry Andric     return false;
2462fe6060f1SDimitry Andric   }
2463fe6060f1SDimitry Andric 
2464fe6060f1SDimitry Andric   if (module_name.find('-') != llvm::StringRef::npos) {
2465fe6060f1SDimitry Andric     error.SetErrorStringWithFormat(
2466fe6060f1SDimitry Andric         "Python discourages dashes in module names: %s", module_name.c_str());
2467fe6060f1SDimitry Andric     return false;
2468fe6060f1SDimitry Andric   }
2469fe6060f1SDimitry Andric 
2470fe6060f1SDimitry Andric   // Check if the module is already imported.
2471e8d8bef9SDimitry Andric   StreamString command_stream;
24720b57cec5SDimitry Andric   command_stream.Clear();
2473e8d8bef9SDimitry Andric   command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
24740b57cec5SDimitry Andric   bool does_contain = false;
2475fe6060f1SDimitry Andric   // This call will succeed if the module was ever imported in any Debugger in
2476fe6060f1SDimitry Andric   // the lifetime of the process in which this LLDB framework is living.
2477fe6060f1SDimitry Andric   const bool does_contain_executed = ExecuteOneLineWithReturn(
24780b57cec5SDimitry Andric       command_stream.GetData(),
2479fe6060f1SDimitry Andric       ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options);
2480fe6060f1SDimitry Andric 
2481fe6060f1SDimitry Andric   const bool was_imported_globally = does_contain_executed && does_contain;
2482fe6060f1SDimitry Andric   const bool was_imported_locally =
2483fe6060f1SDimitry Andric       GetSessionDictionary()
2484e8d8bef9SDimitry Andric           .GetItemForKey(PythonString(module_name))
24850b57cec5SDimitry Andric           .IsAllocated();
24860b57cec5SDimitry Andric 
24870b57cec5SDimitry Andric   // now actually do the import
24880b57cec5SDimitry Andric   command_stream.Clear();
24890b57cec5SDimitry Andric 
2490fe6060f1SDimitry Andric   if (was_imported_globally || was_imported_locally) {
24910b57cec5SDimitry Andric     if (!was_imported_locally)
2492e8d8bef9SDimitry Andric       command_stream.Printf("import %s ; reload_module(%s)",
2493e8d8bef9SDimitry Andric                             module_name.c_str(), module_name.c_str());
24940b57cec5SDimitry Andric     else
2495e8d8bef9SDimitry Andric       command_stream.Printf("reload_module(%s)", module_name.c_str());
24960b57cec5SDimitry Andric   } else
2497e8d8bef9SDimitry Andric     command_stream.Printf("import %s", module_name.c_str());
24980b57cec5SDimitry Andric 
2499fe6060f1SDimitry Andric   error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
25000b57cec5SDimitry Andric   if (error.Fail())
25010b57cec5SDimitry Andric     return false;
25020b57cec5SDimitry Andric 
25030b57cec5SDimitry Andric   // if we are here, everything worked
25040b57cec5SDimitry Andric   // call __lldb_init_module(debugger,dict)
250506c3fb27SDimitry Andric   if (!SWIGBridge::LLDBSwigPythonCallModuleInit(
250606c3fb27SDimitry Andric           module_name.c_str(), m_dictionary_name.c_str(),
25070eae32dcSDimitry Andric           m_debugger.shared_from_this())) {
25080b57cec5SDimitry Andric     error.SetErrorString("calling __lldb_init_module failed");
25090b57cec5SDimitry Andric     return false;
25100b57cec5SDimitry Andric   }
25110b57cec5SDimitry Andric 
25120b57cec5SDimitry Andric   if (module_sp) {
25130b57cec5SDimitry Andric     // everything went just great, now set the module object
25140b57cec5SDimitry Andric     command_stream.Clear();
2515e8d8bef9SDimitry Andric     command_stream.Printf("%s", module_name.c_str());
25160b57cec5SDimitry Andric     void *module_pyobj = nullptr;
25170b57cec5SDimitry Andric     if (ExecuteOneLineWithReturn(
25180b57cec5SDimitry Andric             command_stream.GetData(),
2519fe6060f1SDimitry Andric             ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2520fe6060f1SDimitry Andric             exc_options) &&
25210b57cec5SDimitry Andric         module_pyobj)
252204eeddc0SDimitry Andric       *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
252304eeddc0SDimitry Andric           PyRefType::Owned, static_cast<PyObject *>(module_pyobj)));
25240b57cec5SDimitry Andric   }
25250b57cec5SDimitry Andric 
25260b57cec5SDimitry Andric   return true;
25270b57cec5SDimitry Andric }
25280b57cec5SDimitry Andric 
25290b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
25300b57cec5SDimitry Andric   if (!word || !word[0])
25310b57cec5SDimitry Andric     return false;
25320b57cec5SDimitry Andric 
25330b57cec5SDimitry Andric   llvm::StringRef word_sr(word);
25340b57cec5SDimitry Andric 
25350b57cec5SDimitry Andric   // filter out a few characters that would just confuse us and that are
25360b57cec5SDimitry Andric   // clearly not keyword material anyway
25370b57cec5SDimitry Andric   if (word_sr.find('"') != llvm::StringRef::npos ||
25380b57cec5SDimitry Andric       word_sr.find('\'') != llvm::StringRef::npos)
25390b57cec5SDimitry Andric     return false;
25400b57cec5SDimitry Andric 
25410b57cec5SDimitry Andric   StreamString command_stream;
25420b57cec5SDimitry Andric   command_stream.Printf("keyword.iskeyword('%s')", word);
25430b57cec5SDimitry Andric   bool result;
25440b57cec5SDimitry Andric   ExecuteScriptOptions options;
25450b57cec5SDimitry Andric   options.SetEnableIO(false);
25460b57cec5SDimitry Andric   options.SetMaskoutErrors(true);
25470b57cec5SDimitry Andric   options.SetSetLLDBGlobals(false);
25480b57cec5SDimitry Andric   if (ExecuteOneLineWithReturn(command_stream.GetData(),
25490b57cec5SDimitry Andric                                ScriptInterpreter::eScriptReturnTypeBool,
25500b57cec5SDimitry Andric                                &result, options))
25510b57cec5SDimitry Andric     return result;
25520b57cec5SDimitry Andric   return false;
25530b57cec5SDimitry Andric }
25540b57cec5SDimitry Andric 
25550b57cec5SDimitry Andric ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
25560b57cec5SDimitry Andric     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
25570b57cec5SDimitry Andric     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
25580b57cec5SDimitry Andric       m_old_asynch(debugger_sp->GetAsyncExecution()) {
25590b57cec5SDimitry Andric   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
25600b57cec5SDimitry Andric     m_debugger_sp->SetAsyncExecution(false);
25610b57cec5SDimitry Andric   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
25620b57cec5SDimitry Andric     m_debugger_sp->SetAsyncExecution(true);
25630b57cec5SDimitry Andric }
25640b57cec5SDimitry Andric 
25650b57cec5SDimitry Andric ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
25660b57cec5SDimitry Andric   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
25670b57cec5SDimitry Andric     m_debugger_sp->SetAsyncExecution(m_old_asynch);
25680b57cec5SDimitry Andric }
25690b57cec5SDimitry Andric 
25700b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
25710b57cec5SDimitry Andric     const char *impl_function, llvm::StringRef args,
25720b57cec5SDimitry Andric     ScriptedCommandSynchronicity synchronicity,
25730b57cec5SDimitry Andric     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
25740b57cec5SDimitry Andric     const lldb_private::ExecutionContext &exe_ctx) {
25750b57cec5SDimitry Andric   if (!impl_function) {
25760b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
25770b57cec5SDimitry Andric     return false;
25780b57cec5SDimitry Andric   }
25790b57cec5SDimitry Andric 
25800b57cec5SDimitry Andric   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
25810b57cec5SDimitry Andric   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
25820b57cec5SDimitry Andric 
25830b57cec5SDimitry Andric   if (!debugger_sp.get()) {
25840b57cec5SDimitry Andric     error.SetErrorString("invalid Debugger pointer");
25850b57cec5SDimitry Andric     return false;
25860b57cec5SDimitry Andric   }
25870b57cec5SDimitry Andric 
25880b57cec5SDimitry Andric   bool ret_val = false;
25890b57cec5SDimitry Andric 
25900b57cec5SDimitry Andric   std::string err_msg;
25910b57cec5SDimitry Andric 
25920b57cec5SDimitry Andric   {
25930b57cec5SDimitry Andric     Locker py_lock(this,
25940b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession |
25950b57cec5SDimitry Andric                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
25960b57cec5SDimitry Andric                    Locker::FreeLock | Locker::TearDownSession);
25970b57cec5SDimitry Andric 
25980b57cec5SDimitry Andric     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
25990b57cec5SDimitry Andric 
26000b57cec5SDimitry Andric     std::string args_str = args.str();
260106c3fb27SDimitry Andric     ret_val = SWIGBridge::LLDBSwigPythonCallCommand(
26020b57cec5SDimitry Andric         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
26030b57cec5SDimitry Andric         cmd_retobj, exe_ctx_ref_sp);
26040b57cec5SDimitry Andric   }
26050b57cec5SDimitry Andric 
26060b57cec5SDimitry Andric   if (!ret_val)
26070b57cec5SDimitry Andric     error.SetErrorString("unable to execute script function");
2608bdd1243dSDimitry Andric   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2609bdd1243dSDimitry Andric     return false;
26100b57cec5SDimitry Andric 
2611bdd1243dSDimitry Andric   error.Clear();
26120b57cec5SDimitry Andric   return ret_val;
26130b57cec5SDimitry Andric }
26140b57cec5SDimitry Andric 
26150b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
26160b57cec5SDimitry Andric     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
26170b57cec5SDimitry Andric     ScriptedCommandSynchronicity synchronicity,
26180b57cec5SDimitry Andric     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
26190b57cec5SDimitry Andric     const lldb_private::ExecutionContext &exe_ctx) {
26200b57cec5SDimitry Andric   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
26210b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
26220b57cec5SDimitry Andric     return false;
26230b57cec5SDimitry Andric   }
26240b57cec5SDimitry Andric 
26250b57cec5SDimitry Andric   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
26260b57cec5SDimitry Andric   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
26270b57cec5SDimitry Andric 
26280b57cec5SDimitry Andric   if (!debugger_sp.get()) {
26290b57cec5SDimitry Andric     error.SetErrorString("invalid Debugger pointer");
26300b57cec5SDimitry Andric     return false;
26310b57cec5SDimitry Andric   }
26320b57cec5SDimitry Andric 
26330b57cec5SDimitry Andric   bool ret_val = false;
26340b57cec5SDimitry Andric 
26350b57cec5SDimitry Andric   std::string err_msg;
26360b57cec5SDimitry Andric 
26370b57cec5SDimitry Andric   {
26380b57cec5SDimitry Andric     Locker py_lock(this,
26390b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession |
26400b57cec5SDimitry Andric                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
26410b57cec5SDimitry Andric                    Locker::FreeLock | Locker::TearDownSession);
26420b57cec5SDimitry Andric 
26430b57cec5SDimitry Andric     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
26440b57cec5SDimitry Andric 
26450b57cec5SDimitry Andric     std::string args_str = args.str();
264606c3fb27SDimitry Andric     ret_val = SWIGBridge::LLDBSwigPythonCallCommandObject(
26474824e7fdSDimitry Andric         static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
26484824e7fdSDimitry Andric         args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
26490b57cec5SDimitry Andric   }
26500b57cec5SDimitry Andric 
26510b57cec5SDimitry Andric   if (!ret_val)
26520b57cec5SDimitry Andric     error.SetErrorString("unable to execute script function");
2653bdd1243dSDimitry Andric   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2654bdd1243dSDimitry Andric     return false;
26550b57cec5SDimitry Andric 
2656bdd1243dSDimitry Andric   error.Clear();
26570b57cec5SDimitry Andric   return ret_val;
26580b57cec5SDimitry Andric }
26590b57cec5SDimitry Andric 
2660*0fca6ea1SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptBasedParsedCommand(
2661*0fca6ea1SDimitry Andric     StructuredData::GenericSP impl_obj_sp, Args &args,
2662*0fca6ea1SDimitry Andric     ScriptedCommandSynchronicity synchronicity,
2663*0fca6ea1SDimitry Andric     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2664*0fca6ea1SDimitry Andric     const lldb_private::ExecutionContext &exe_ctx) {
2665*0fca6ea1SDimitry Andric   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2666*0fca6ea1SDimitry Andric     error.SetErrorString("no function to execute");
2667*0fca6ea1SDimitry Andric     return false;
2668*0fca6ea1SDimitry Andric   }
2669*0fca6ea1SDimitry Andric 
2670*0fca6ea1SDimitry Andric   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2671*0fca6ea1SDimitry Andric   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2672*0fca6ea1SDimitry Andric 
2673*0fca6ea1SDimitry Andric   if (!debugger_sp.get()) {
2674*0fca6ea1SDimitry Andric     error.SetErrorString("invalid Debugger pointer");
2675*0fca6ea1SDimitry Andric     return false;
2676*0fca6ea1SDimitry Andric   }
2677*0fca6ea1SDimitry Andric 
2678*0fca6ea1SDimitry Andric   bool ret_val = false;
2679*0fca6ea1SDimitry Andric 
2680*0fca6ea1SDimitry Andric   std::string err_msg;
2681*0fca6ea1SDimitry Andric 
2682*0fca6ea1SDimitry Andric   {
2683*0fca6ea1SDimitry Andric     Locker py_lock(this,
2684*0fca6ea1SDimitry Andric                    Locker::AcquireLock | Locker::InitSession |
2685*0fca6ea1SDimitry Andric                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2686*0fca6ea1SDimitry Andric                    Locker::FreeLock | Locker::TearDownSession);
2687*0fca6ea1SDimitry Andric 
2688*0fca6ea1SDimitry Andric     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2689*0fca6ea1SDimitry Andric 
2690*0fca6ea1SDimitry Andric     StructuredData::ArraySP args_arr_sp(new StructuredData::Array());
2691*0fca6ea1SDimitry Andric 
2692*0fca6ea1SDimitry Andric     for (const Args::ArgEntry &entry : args) {
2693*0fca6ea1SDimitry Andric       args_arr_sp->AddStringItem(entry.ref());
2694*0fca6ea1SDimitry Andric     }
2695*0fca6ea1SDimitry Andric     StructuredDataImpl args_impl(args_arr_sp);
2696*0fca6ea1SDimitry Andric 
2697*0fca6ea1SDimitry Andric     ret_val = SWIGBridge::LLDBSwigPythonCallParsedCommandObject(
2698*0fca6ea1SDimitry Andric         static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
2699*0fca6ea1SDimitry Andric         args_impl, cmd_retobj, exe_ctx_ref_sp);
2700*0fca6ea1SDimitry Andric   }
2701*0fca6ea1SDimitry Andric 
2702*0fca6ea1SDimitry Andric   if (!ret_val)
2703*0fca6ea1SDimitry Andric     error.SetErrorString("unable to execute script function");
2704*0fca6ea1SDimitry Andric   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2705*0fca6ea1SDimitry Andric     return false;
2706*0fca6ea1SDimitry Andric 
2707*0fca6ea1SDimitry Andric   error.Clear();
2708*0fca6ea1SDimitry Andric   return ret_val;
2709*0fca6ea1SDimitry Andric }
2710*0fca6ea1SDimitry Andric 
2711*0fca6ea1SDimitry Andric std::optional<std::string>
2712*0fca6ea1SDimitry Andric ScriptInterpreterPythonImpl::GetRepeatCommandForScriptedCommand(
2713*0fca6ea1SDimitry Andric     StructuredData::GenericSP impl_obj_sp, Args &args) {
2714*0fca6ea1SDimitry Andric   if (!impl_obj_sp || !impl_obj_sp->IsValid())
2715*0fca6ea1SDimitry Andric     return std::nullopt;
2716*0fca6ea1SDimitry Andric 
2717*0fca6ea1SDimitry Andric   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2718*0fca6ea1SDimitry Andric 
2719*0fca6ea1SDimitry Andric   if (!debugger_sp.get())
2720*0fca6ea1SDimitry Andric     return std::nullopt;
2721*0fca6ea1SDimitry Andric 
2722*0fca6ea1SDimitry Andric   std::optional<std::string> ret_val;
2723*0fca6ea1SDimitry Andric 
2724*0fca6ea1SDimitry Andric   {
2725*0fca6ea1SDimitry Andric     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
2726*0fca6ea1SDimitry Andric                    Locker::FreeLock);
2727*0fca6ea1SDimitry Andric 
2728*0fca6ea1SDimitry Andric     StructuredData::ArraySP args_arr_sp(new StructuredData::Array());
2729*0fca6ea1SDimitry Andric 
2730*0fca6ea1SDimitry Andric     // For scripting commands, we send the command string:
2731*0fca6ea1SDimitry Andric     std::string command;
2732*0fca6ea1SDimitry Andric     args.GetQuotedCommandString(command);
2733*0fca6ea1SDimitry Andric     ret_val = SWIGBridge::LLDBSwigPythonGetRepeatCommandForScriptedCommand(
2734*0fca6ea1SDimitry Andric         static_cast<PyObject *>(impl_obj_sp->GetValue()), command);
2735*0fca6ea1SDimitry Andric   }
2736*0fca6ea1SDimitry Andric   return ret_val;
2737*0fca6ea1SDimitry Andric }
2738*0fca6ea1SDimitry Andric 
27395ffd83dbSDimitry Andric /// In Python, a special attribute __doc__ contains the docstring for an object
27405ffd83dbSDimitry Andric /// (function, method, class, ...) if any is defined Otherwise, the attribute's
27415ffd83dbSDimitry Andric /// value is None.
27420b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
27430b57cec5SDimitry Andric                                                           std::string &dest) {
27440b57cec5SDimitry Andric   dest.clear();
27455ffd83dbSDimitry Andric 
27460b57cec5SDimitry Andric   if (!item || !*item)
27470b57cec5SDimitry Andric     return false;
27485ffd83dbSDimitry Andric 
27490b57cec5SDimitry Andric   std::string command(item);
27500b57cec5SDimitry Andric   command += ".__doc__";
27510b57cec5SDimitry Andric 
27525ffd83dbSDimitry Andric   // Python is going to point this to valid data if ExecuteOneLineWithReturn
27535ffd83dbSDimitry Andric   // returns successfully.
27545ffd83dbSDimitry Andric   char *result_ptr = nullptr;
27550b57cec5SDimitry Andric 
27560b57cec5SDimitry Andric   if (ExecuteOneLineWithReturn(
27575ffd83dbSDimitry Andric           command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
27580b57cec5SDimitry Andric           &result_ptr,
2759fe6060f1SDimitry Andric           ExecuteScriptOptions().SetEnableIO(false))) {
27600b57cec5SDimitry Andric     if (result_ptr)
27610b57cec5SDimitry Andric       dest.assign(result_ptr);
27620b57cec5SDimitry Andric     return true;
27630b57cec5SDimitry Andric   }
27645ffd83dbSDimitry Andric 
27655ffd83dbSDimitry Andric   StreamString str_stream;
27665ffd83dbSDimitry Andric   str_stream << "Function " << item
27675ffd83dbSDimitry Andric              << " was not found. Containing module might be missing.";
27685ffd83dbSDimitry Andric   dest = std::string(str_stream.GetString());
27695ffd83dbSDimitry Andric 
27705ffd83dbSDimitry Andric   return false;
27710b57cec5SDimitry Andric }
27720b57cec5SDimitry Andric 
27730b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
27740b57cec5SDimitry Andric     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
27750b57cec5SDimitry Andric   dest.clear();
27760b57cec5SDimitry Andric 
27770b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
27780b57cec5SDimitry Andric 
27790b57cec5SDimitry Andric   if (!cmd_obj_sp)
27800b57cec5SDimitry Andric     return false;
27810b57cec5SDimitry Andric 
27820b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
27830b57cec5SDimitry Andric                            (PyObject *)cmd_obj_sp->GetValue());
27840b57cec5SDimitry Andric 
27850b57cec5SDimitry Andric   if (!implementor.IsAllocated())
27860b57cec5SDimitry Andric     return false;
27870b57cec5SDimitry Andric 
2788bdd1243dSDimitry Andric   llvm::Expected<PythonObject> expected_py_return =
2789bdd1243dSDimitry Andric       implementor.CallMethod("get_short_help");
27900b57cec5SDimitry Andric 
2791bdd1243dSDimitry Andric   if (!expected_py_return) {
2792bdd1243dSDimitry Andric     llvm::consumeError(expected_py_return.takeError());
27930b57cec5SDimitry Andric     return false;
27940b57cec5SDimitry Andric   }
27950b57cec5SDimitry Andric 
2796bdd1243dSDimitry Andric   PythonObject py_return = std::move(expected_py_return.get());
27970b57cec5SDimitry Andric 
27980b57cec5SDimitry Andric   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
27990b57cec5SDimitry Andric     PythonString py_string(PyRefType::Borrowed, py_return.get());
28000b57cec5SDimitry Andric     llvm::StringRef return_data(py_string.GetString());
28010b57cec5SDimitry Andric     dest.assign(return_data.data(), return_data.size());
28025ffd83dbSDimitry Andric     return true;
28030b57cec5SDimitry Andric   }
28045ffd83dbSDimitry Andric 
28055ffd83dbSDimitry Andric   return false;
28060b57cec5SDimitry Andric }
28070b57cec5SDimitry Andric 
28080b57cec5SDimitry Andric uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
28090b57cec5SDimitry Andric     StructuredData::GenericSP cmd_obj_sp) {
28100b57cec5SDimitry Andric   uint32_t result = 0;
28110b57cec5SDimitry Andric 
28120b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
28130b57cec5SDimitry Andric 
28140b57cec5SDimitry Andric   static char callee_name[] = "get_flags";
28150b57cec5SDimitry Andric 
28160b57cec5SDimitry Andric   if (!cmd_obj_sp)
28170b57cec5SDimitry Andric     return result;
28180b57cec5SDimitry Andric 
28190b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
28200b57cec5SDimitry Andric                            (PyObject *)cmd_obj_sp->GetValue());
28210b57cec5SDimitry Andric 
28220b57cec5SDimitry Andric   if (!implementor.IsAllocated())
28230b57cec5SDimitry Andric     return result;
28240b57cec5SDimitry Andric 
28250b57cec5SDimitry Andric   PythonObject pmeth(PyRefType::Owned,
28260b57cec5SDimitry Andric                      PyObject_GetAttrString(implementor.get(), callee_name));
28270b57cec5SDimitry Andric 
28280b57cec5SDimitry Andric   if (PyErr_Occurred())
28290b57cec5SDimitry Andric     PyErr_Clear();
28300b57cec5SDimitry Andric 
28310b57cec5SDimitry Andric   if (!pmeth.IsAllocated())
28320b57cec5SDimitry Andric     return result;
28330b57cec5SDimitry Andric 
28340b57cec5SDimitry Andric   if (PyCallable_Check(pmeth.get()) == 0) {
28350b57cec5SDimitry Andric     if (PyErr_Occurred())
28360b57cec5SDimitry Andric       PyErr_Clear();
28370b57cec5SDimitry Andric     return result;
28380b57cec5SDimitry Andric   }
28390b57cec5SDimitry Andric 
28400b57cec5SDimitry Andric   if (PyErr_Occurred())
28410b57cec5SDimitry Andric     PyErr_Clear();
28420b57cec5SDimitry Andric 
28435ffd83dbSDimitry Andric   long long py_return = unwrapOrSetPythonException(
28445ffd83dbSDimitry Andric       As<long long>(implementor.CallMethod(callee_name)));
28450b57cec5SDimitry Andric 
28460b57cec5SDimitry Andric   // if it fails, print the error but otherwise go on
28470b57cec5SDimitry Andric   if (PyErr_Occurred()) {
28480b57cec5SDimitry Andric     PyErr_Print();
28490b57cec5SDimitry Andric     PyErr_Clear();
28505ffd83dbSDimitry Andric   } else {
28515ffd83dbSDimitry Andric     result = py_return;
28520b57cec5SDimitry Andric   }
28530b57cec5SDimitry Andric 
28540b57cec5SDimitry Andric   return result;
28550b57cec5SDimitry Andric }
28560b57cec5SDimitry Andric 
2857*0fca6ea1SDimitry Andric StructuredData::ObjectSP
2858*0fca6ea1SDimitry Andric ScriptInterpreterPythonImpl::GetOptionsForCommandObject(
2859*0fca6ea1SDimitry Andric     StructuredData::GenericSP cmd_obj_sp) {
2860*0fca6ea1SDimitry Andric   StructuredData::ObjectSP result = {};
2861*0fca6ea1SDimitry Andric 
2862*0fca6ea1SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2863*0fca6ea1SDimitry Andric 
2864*0fca6ea1SDimitry Andric   static char callee_name[] = "get_options_definition";
2865*0fca6ea1SDimitry Andric 
2866*0fca6ea1SDimitry Andric   if (!cmd_obj_sp)
2867*0fca6ea1SDimitry Andric     return result;
2868*0fca6ea1SDimitry Andric 
2869*0fca6ea1SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
2870*0fca6ea1SDimitry Andric                            (PyObject *)cmd_obj_sp->GetValue());
2871*0fca6ea1SDimitry Andric 
2872*0fca6ea1SDimitry Andric   if (!implementor.IsAllocated())
2873*0fca6ea1SDimitry Andric     return result;
2874*0fca6ea1SDimitry Andric 
2875*0fca6ea1SDimitry Andric   PythonObject pmeth(PyRefType::Owned,
2876*0fca6ea1SDimitry Andric                      PyObject_GetAttrString(implementor.get(), callee_name));
2877*0fca6ea1SDimitry Andric 
2878*0fca6ea1SDimitry Andric   if (PyErr_Occurred())
2879*0fca6ea1SDimitry Andric     PyErr_Clear();
2880*0fca6ea1SDimitry Andric 
2881*0fca6ea1SDimitry Andric   if (!pmeth.IsAllocated())
2882*0fca6ea1SDimitry Andric     return result;
2883*0fca6ea1SDimitry Andric 
2884*0fca6ea1SDimitry Andric   if (PyCallable_Check(pmeth.get()) == 0) {
2885*0fca6ea1SDimitry Andric     if (PyErr_Occurred())
2886*0fca6ea1SDimitry Andric       PyErr_Clear();
2887*0fca6ea1SDimitry Andric     return result;
2888*0fca6ea1SDimitry Andric   }
2889*0fca6ea1SDimitry Andric 
2890*0fca6ea1SDimitry Andric   if (PyErr_Occurred())
2891*0fca6ea1SDimitry Andric     PyErr_Clear();
2892*0fca6ea1SDimitry Andric 
2893*0fca6ea1SDimitry Andric   PythonDictionary py_return = unwrapOrSetPythonException(
2894*0fca6ea1SDimitry Andric       As<PythonDictionary>(implementor.CallMethod(callee_name)));
2895*0fca6ea1SDimitry Andric 
2896*0fca6ea1SDimitry Andric   // if it fails, print the error but otherwise go on
2897*0fca6ea1SDimitry Andric   if (PyErr_Occurred()) {
2898*0fca6ea1SDimitry Andric     PyErr_Print();
2899*0fca6ea1SDimitry Andric     PyErr_Clear();
2900*0fca6ea1SDimitry Andric     return {};
2901*0fca6ea1SDimitry Andric   }
2902*0fca6ea1SDimitry Andric     return py_return.CreateStructuredObject();
2903*0fca6ea1SDimitry Andric }
2904*0fca6ea1SDimitry Andric 
2905*0fca6ea1SDimitry Andric StructuredData::ObjectSP
2906*0fca6ea1SDimitry Andric ScriptInterpreterPythonImpl::GetArgumentsForCommandObject(
2907*0fca6ea1SDimitry Andric     StructuredData::GenericSP cmd_obj_sp) {
2908*0fca6ea1SDimitry Andric   StructuredData::ObjectSP result = {};
2909*0fca6ea1SDimitry Andric 
2910*0fca6ea1SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2911*0fca6ea1SDimitry Andric 
2912*0fca6ea1SDimitry Andric   static char callee_name[] = "get_args_definition";
2913*0fca6ea1SDimitry Andric 
2914*0fca6ea1SDimitry Andric   if (!cmd_obj_sp)
2915*0fca6ea1SDimitry Andric     return result;
2916*0fca6ea1SDimitry Andric 
2917*0fca6ea1SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
2918*0fca6ea1SDimitry Andric                            (PyObject *)cmd_obj_sp->GetValue());
2919*0fca6ea1SDimitry Andric 
2920*0fca6ea1SDimitry Andric   if (!implementor.IsAllocated())
2921*0fca6ea1SDimitry Andric     return result;
2922*0fca6ea1SDimitry Andric 
2923*0fca6ea1SDimitry Andric   PythonObject pmeth(PyRefType::Owned,
2924*0fca6ea1SDimitry Andric                      PyObject_GetAttrString(implementor.get(), callee_name));
2925*0fca6ea1SDimitry Andric 
2926*0fca6ea1SDimitry Andric   if (PyErr_Occurred())
2927*0fca6ea1SDimitry Andric     PyErr_Clear();
2928*0fca6ea1SDimitry Andric 
2929*0fca6ea1SDimitry Andric   if (!pmeth.IsAllocated())
2930*0fca6ea1SDimitry Andric     return result;
2931*0fca6ea1SDimitry Andric 
2932*0fca6ea1SDimitry Andric   if (PyCallable_Check(pmeth.get()) == 0) {
2933*0fca6ea1SDimitry Andric     if (PyErr_Occurred())
2934*0fca6ea1SDimitry Andric       PyErr_Clear();
2935*0fca6ea1SDimitry Andric     return result;
2936*0fca6ea1SDimitry Andric   }
2937*0fca6ea1SDimitry Andric 
2938*0fca6ea1SDimitry Andric   if (PyErr_Occurred())
2939*0fca6ea1SDimitry Andric     PyErr_Clear();
2940*0fca6ea1SDimitry Andric 
2941*0fca6ea1SDimitry Andric   PythonList py_return = unwrapOrSetPythonException(
2942*0fca6ea1SDimitry Andric       As<PythonList>(implementor.CallMethod(callee_name)));
2943*0fca6ea1SDimitry Andric 
2944*0fca6ea1SDimitry Andric   // if it fails, print the error but otherwise go on
2945*0fca6ea1SDimitry Andric   if (PyErr_Occurred()) {
2946*0fca6ea1SDimitry Andric     PyErr_Print();
2947*0fca6ea1SDimitry Andric     PyErr_Clear();
2948*0fca6ea1SDimitry Andric     return {};
2949*0fca6ea1SDimitry Andric   }
2950*0fca6ea1SDimitry Andric     return py_return.CreateStructuredObject();
2951*0fca6ea1SDimitry Andric }
2952*0fca6ea1SDimitry Andric 
2953*0fca6ea1SDimitry Andric void
2954*0fca6ea1SDimitry Andric ScriptInterpreterPythonImpl::OptionParsingStartedForCommandObject(
2955*0fca6ea1SDimitry Andric     StructuredData::GenericSP cmd_obj_sp) {
2956*0fca6ea1SDimitry Andric 
2957*0fca6ea1SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2958*0fca6ea1SDimitry Andric 
2959*0fca6ea1SDimitry Andric   static char callee_name[] = "option_parsing_started";
2960*0fca6ea1SDimitry Andric 
2961*0fca6ea1SDimitry Andric   if (!cmd_obj_sp)
2962*0fca6ea1SDimitry Andric     return ;
2963*0fca6ea1SDimitry Andric 
2964*0fca6ea1SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
2965*0fca6ea1SDimitry Andric                            (PyObject *)cmd_obj_sp->GetValue());
2966*0fca6ea1SDimitry Andric 
2967*0fca6ea1SDimitry Andric   if (!implementor.IsAllocated())
2968*0fca6ea1SDimitry Andric     return;
2969*0fca6ea1SDimitry Andric 
2970*0fca6ea1SDimitry Andric   PythonObject pmeth(PyRefType::Owned,
2971*0fca6ea1SDimitry Andric                      PyObject_GetAttrString(implementor.get(), callee_name));
2972*0fca6ea1SDimitry Andric 
2973*0fca6ea1SDimitry Andric   if (PyErr_Occurred())
2974*0fca6ea1SDimitry Andric     PyErr_Clear();
2975*0fca6ea1SDimitry Andric 
2976*0fca6ea1SDimitry Andric   if (!pmeth.IsAllocated())
2977*0fca6ea1SDimitry Andric     return;
2978*0fca6ea1SDimitry Andric 
2979*0fca6ea1SDimitry Andric   if (PyCallable_Check(pmeth.get()) == 0) {
2980*0fca6ea1SDimitry Andric     if (PyErr_Occurred())
2981*0fca6ea1SDimitry Andric       PyErr_Clear();
2982*0fca6ea1SDimitry Andric     return;
2983*0fca6ea1SDimitry Andric   }
2984*0fca6ea1SDimitry Andric 
2985*0fca6ea1SDimitry Andric   if (PyErr_Occurred())
2986*0fca6ea1SDimitry Andric     PyErr_Clear();
2987*0fca6ea1SDimitry Andric 
2988*0fca6ea1SDimitry Andric   // option_parsing_starting doesn't return anything, ignore anything but
2989*0fca6ea1SDimitry Andric   // python errors.
2990*0fca6ea1SDimitry Andric   unwrapOrSetPythonException(
2991*0fca6ea1SDimitry Andric       As<bool>(implementor.CallMethod(callee_name)));
2992*0fca6ea1SDimitry Andric 
2993*0fca6ea1SDimitry Andric   // if it fails, print the error but otherwise go on
2994*0fca6ea1SDimitry Andric   if (PyErr_Occurred()) {
2995*0fca6ea1SDimitry Andric     PyErr_Print();
2996*0fca6ea1SDimitry Andric     PyErr_Clear();
2997*0fca6ea1SDimitry Andric     return;
2998*0fca6ea1SDimitry Andric   }
2999*0fca6ea1SDimitry Andric }
3000*0fca6ea1SDimitry Andric 
3001*0fca6ea1SDimitry Andric bool
3002*0fca6ea1SDimitry Andric ScriptInterpreterPythonImpl::SetOptionValueForCommandObject(
3003*0fca6ea1SDimitry Andric     StructuredData::GenericSP cmd_obj_sp, ExecutionContext *exe_ctx,
3004*0fca6ea1SDimitry Andric     llvm::StringRef long_option, llvm::StringRef value) {
3005*0fca6ea1SDimitry Andric   StructuredData::ObjectSP result = {};
3006*0fca6ea1SDimitry Andric 
3007*0fca6ea1SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3008*0fca6ea1SDimitry Andric 
3009*0fca6ea1SDimitry Andric   static char callee_name[] = "set_option_value";
3010*0fca6ea1SDimitry Andric 
3011*0fca6ea1SDimitry Andric   if (!cmd_obj_sp)
3012*0fca6ea1SDimitry Andric     return false;
3013*0fca6ea1SDimitry Andric 
3014*0fca6ea1SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
3015*0fca6ea1SDimitry Andric                            (PyObject *)cmd_obj_sp->GetValue());
3016*0fca6ea1SDimitry Andric 
3017*0fca6ea1SDimitry Andric   if (!implementor.IsAllocated())
3018*0fca6ea1SDimitry Andric     return false;
3019*0fca6ea1SDimitry Andric 
3020*0fca6ea1SDimitry Andric   PythonObject pmeth(PyRefType::Owned,
3021*0fca6ea1SDimitry Andric                      PyObject_GetAttrString(implementor.get(), callee_name));
3022*0fca6ea1SDimitry Andric 
3023*0fca6ea1SDimitry Andric   if (PyErr_Occurred())
3024*0fca6ea1SDimitry Andric     PyErr_Clear();
3025*0fca6ea1SDimitry Andric 
3026*0fca6ea1SDimitry Andric   if (!pmeth.IsAllocated())
3027*0fca6ea1SDimitry Andric     return false;
3028*0fca6ea1SDimitry Andric 
3029*0fca6ea1SDimitry Andric   if (PyCallable_Check(pmeth.get()) == 0) {
3030*0fca6ea1SDimitry Andric     if (PyErr_Occurred())
3031*0fca6ea1SDimitry Andric       PyErr_Clear();
3032*0fca6ea1SDimitry Andric     return false;
3033*0fca6ea1SDimitry Andric   }
3034*0fca6ea1SDimitry Andric 
3035*0fca6ea1SDimitry Andric   if (PyErr_Occurred())
3036*0fca6ea1SDimitry Andric     PyErr_Clear();
3037*0fca6ea1SDimitry Andric 
3038*0fca6ea1SDimitry Andric   lldb::ExecutionContextRefSP exe_ctx_ref_sp;
3039*0fca6ea1SDimitry Andric   if (exe_ctx)
3040*0fca6ea1SDimitry Andric     exe_ctx_ref_sp.reset(new ExecutionContextRef(exe_ctx));
3041*0fca6ea1SDimitry Andric   PythonObject ctx_ref_obj = SWIGBridge::ToSWIGWrapper(exe_ctx_ref_sp);
3042*0fca6ea1SDimitry Andric 
3043*0fca6ea1SDimitry Andric   bool py_return = unwrapOrSetPythonException(
3044*0fca6ea1SDimitry Andric       As<bool>(implementor.CallMethod(callee_name, ctx_ref_obj, long_option.str().c_str(),
3045*0fca6ea1SDimitry Andric                                       value.str().c_str())));
3046*0fca6ea1SDimitry Andric 
3047*0fca6ea1SDimitry Andric   // if it fails, print the error but otherwise go on
3048*0fca6ea1SDimitry Andric   if (PyErr_Occurred()) {
3049*0fca6ea1SDimitry Andric     PyErr_Print();
3050*0fca6ea1SDimitry Andric     PyErr_Clear();
3051*0fca6ea1SDimitry Andric     return false;
3052*0fca6ea1SDimitry Andric   }
3053*0fca6ea1SDimitry Andric   return py_return;
3054*0fca6ea1SDimitry Andric }
3055*0fca6ea1SDimitry Andric 
30560b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
30570b57cec5SDimitry Andric     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
30580b57cec5SDimitry Andric   dest.clear();
30590b57cec5SDimitry Andric 
30600b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
30610b57cec5SDimitry Andric 
30620b57cec5SDimitry Andric   if (!cmd_obj_sp)
30630b57cec5SDimitry Andric     return false;
30640b57cec5SDimitry Andric 
30650b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
30660b57cec5SDimitry Andric                            (PyObject *)cmd_obj_sp->GetValue());
30670b57cec5SDimitry Andric 
30680b57cec5SDimitry Andric   if (!implementor.IsAllocated())
30690b57cec5SDimitry Andric     return false;
30700b57cec5SDimitry Andric 
3071bdd1243dSDimitry Andric   llvm::Expected<PythonObject> expected_py_return =
3072bdd1243dSDimitry Andric       implementor.CallMethod("get_long_help");
30730b57cec5SDimitry Andric 
3074bdd1243dSDimitry Andric   if (!expected_py_return) {
3075bdd1243dSDimitry Andric     llvm::consumeError(expected_py_return.takeError());
30760b57cec5SDimitry Andric     return false;
30770b57cec5SDimitry Andric   }
30780b57cec5SDimitry Andric 
3079bdd1243dSDimitry Andric   PythonObject py_return = std::move(expected_py_return.get());
30800b57cec5SDimitry Andric 
3081bdd1243dSDimitry Andric   bool got_string = false;
30820b57cec5SDimitry Andric   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
30830b57cec5SDimitry Andric     PythonString str(PyRefType::Borrowed, py_return.get());
30840b57cec5SDimitry Andric     llvm::StringRef str_data(str.GetString());
30850b57cec5SDimitry Andric     dest.assign(str_data.data(), str_data.size());
30860b57cec5SDimitry Andric     got_string = true;
30870b57cec5SDimitry Andric   }
30880b57cec5SDimitry Andric 
30890b57cec5SDimitry Andric   return got_string;
30900b57cec5SDimitry Andric }
30910b57cec5SDimitry Andric 
30920b57cec5SDimitry Andric std::unique_ptr<ScriptInterpreterLocker>
30930b57cec5SDimitry Andric ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
30940b57cec5SDimitry Andric   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
30950b57cec5SDimitry Andric       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
30960b57cec5SDimitry Andric       Locker::FreeLock | Locker::TearDownSession));
30970b57cec5SDimitry Andric   return py_lock;
30980b57cec5SDimitry Andric }
30990b57cec5SDimitry Andric 
310004eeddc0SDimitry Andric void ScriptInterpreterPythonImpl::Initialize() {
3101e8d8bef9SDimitry Andric   LLDB_SCOPED_TIMER();
31020b57cec5SDimitry Andric 
31030b57cec5SDimitry Andric   // RAII-based initialization which correctly handles multiple-initialization,
31040b57cec5SDimitry Andric   // version- specific differences among Python 2 and Python 3, and saving and
31050b57cec5SDimitry Andric   // restoring various other pieces of state that can get mucked with during
31060b57cec5SDimitry Andric   // initialization.
31070b57cec5SDimitry Andric   InitializePythonRAII initialize_guard;
31080b57cec5SDimitry Andric 
31090b57cec5SDimitry Andric   LLDBSwigPyInit();
31100b57cec5SDimitry Andric 
31110b57cec5SDimitry Andric   // Update the path python uses to search for modules to include the current
31120b57cec5SDimitry Andric   // directory.
31130b57cec5SDimitry Andric 
31140b57cec5SDimitry Andric   PyRun_SimpleString("import sys");
31150b57cec5SDimitry Andric   AddToSysPath(AddLocation::End, ".");
31160b57cec5SDimitry Andric 
31170b57cec5SDimitry Andric   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
31180b57cec5SDimitry Andric   // that use a backslash as the path separator, this will result in executing
31190b57cec5SDimitry Andric   // python code containing paths with unescaped backslashes.  But Python also
31200b57cec5SDimitry Andric   // accepts forward slashes, so to make life easier we just use that.
31210b57cec5SDimitry Andric   if (FileSpec file_spec = GetPythonDir())
31220b57cec5SDimitry Andric     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
31230b57cec5SDimitry Andric   if (FileSpec file_spec = HostInfo::GetShlibDir())
31240b57cec5SDimitry Andric     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
31250b57cec5SDimitry Andric 
31260b57cec5SDimitry Andric   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
31270b57cec5SDimitry Andric                      "lldb.embedded_interpreter; from "
31280b57cec5SDimitry Andric                      "lldb.embedded_interpreter import run_python_interpreter; "
31290b57cec5SDimitry Andric                      "from lldb.embedded_interpreter import run_one_line");
313004eeddc0SDimitry Andric 
313104eeddc0SDimitry Andric #if LLDB_USE_PYTHON_SET_INTERRUPT
313204eeddc0SDimitry Andric   // Python will not just overwrite its internal SIGINT handler but also the
313304eeddc0SDimitry Andric   // one from the process. Backup the current SIGINT handler to prevent that
313404eeddc0SDimitry Andric   // Python deletes it.
313504eeddc0SDimitry Andric   RestoreSignalHandlerScope save_sigint(SIGINT);
313604eeddc0SDimitry Andric 
313704eeddc0SDimitry Andric   // Setup a default SIGINT signal handler that works the same way as the
313804eeddc0SDimitry Andric   // normal Python REPL signal handler which raises a KeyboardInterrupt.
313904eeddc0SDimitry Andric   // Also make sure to not pollute the user's REPL with the signal module nor
314004eeddc0SDimitry Andric   // our utility function.
314104eeddc0SDimitry Andric   PyRun_SimpleString("def lldb_setup_sigint_handler():\n"
314204eeddc0SDimitry Andric                      "  import signal;\n"
314304eeddc0SDimitry Andric                      "  def signal_handler(sig, frame):\n"
314404eeddc0SDimitry Andric                      "    raise KeyboardInterrupt()\n"
314504eeddc0SDimitry Andric                      "  signal.signal(signal.SIGINT, signal_handler);\n"
314604eeddc0SDimitry Andric                      "lldb_setup_sigint_handler();\n"
314704eeddc0SDimitry Andric                      "del lldb_setup_sigint_handler\n");
314804eeddc0SDimitry Andric #endif
31490b57cec5SDimitry Andric }
31500b57cec5SDimitry Andric 
31510b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
31520b57cec5SDimitry Andric                                                std::string path) {
31530b57cec5SDimitry Andric   std::string path_copy;
31540b57cec5SDimitry Andric 
31550b57cec5SDimitry Andric   std::string statement;
31560b57cec5SDimitry Andric   if (location == AddLocation::Beginning) {
31570b57cec5SDimitry Andric     statement.assign("sys.path.insert(0,\"");
31580b57cec5SDimitry Andric     statement.append(path);
31590b57cec5SDimitry Andric     statement.append("\")");
31600b57cec5SDimitry Andric   } else {
31610b57cec5SDimitry Andric     statement.assign("sys.path.append(\"");
31620b57cec5SDimitry Andric     statement.append(path);
31630b57cec5SDimitry Andric     statement.append("\")");
31640b57cec5SDimitry Andric   }
31650b57cec5SDimitry Andric   PyRun_SimpleString(statement.c_str());
31660b57cec5SDimitry Andric }
31670b57cec5SDimitry Andric 
31680b57cec5SDimitry Andric // We are intentionally NOT calling Py_Finalize here (this would be the logical
31690b57cec5SDimitry Andric // place to call it).  Calling Py_Finalize here causes test suite runs to seg
31700b57cec5SDimitry Andric // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
31710b57cec5SDimitry Andric // be called 'at_exit'.  When the test suite Python harness finishes up, it
31720b57cec5SDimitry Andric // calls Py_Finalize, which calls all the 'at_exit' registered functions.
31730b57cec5SDimitry Andric // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
31740b57cec5SDimitry Andric // which calls ScriptInterpreter::Terminate, which calls
31750b57cec5SDimitry Andric // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
31760b57cec5SDimitry Andric // end up with Py_Finalize being called from within Py_Finalize, which results
31770b57cec5SDimitry Andric // in a seg fault. Since this function only gets called when lldb is shutting
31780b57cec5SDimitry Andric // down and going away anyway, the fact that we don't actually call Py_Finalize
31790b57cec5SDimitry Andric // should not cause any problems (everything should shut down/go away anyway
31800b57cec5SDimitry Andric // when the process exits).
31810b57cec5SDimitry Andric //
31820b57cec5SDimitry Andric // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
31830b57cec5SDimitry Andric 
3184480093f4SDimitry Andric #endif
3185