xref: /openbsd-src/gnu/llvm/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp (revision f6aab3d83b51b91c24247ad2c2573574de475a82)
1dda28197Spatrick //===-- ScriptInterpreterPython.cpp ---------------------------------------===//
2061da546Spatrick //
3061da546Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4061da546Spatrick // See https://llvm.org/LICENSE.txt for license information.
5061da546Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6061da546Spatrick //
7061da546Spatrick //===----------------------------------------------------------------------===//
8061da546Spatrick 
9061da546Spatrick #include "lldb/Host/Config.h"
10be691f3bSpatrick #include "lldb/lldb-enumerations.h"
11061da546Spatrick 
12061da546Spatrick #if LLDB_ENABLE_PYTHON
13061da546Spatrick 
14061da546Spatrick // LLDB Python header must be included first
15061da546Spatrick #include "lldb-python.h"
16061da546Spatrick 
17061da546Spatrick #include "PythonDataObjects.h"
18061da546Spatrick #include "PythonReadline.h"
19be691f3bSpatrick #include "SWIGPythonBridge.h"
20061da546Spatrick #include "ScriptInterpreterPythonImpl.h"
21*f6aab3d8Srobert #include "ScriptedPlatformPythonInterface.h"
22be691f3bSpatrick #include "ScriptedProcessPythonInterface.h"
23be691f3bSpatrick 
24be691f3bSpatrick #include "lldb/API/SBError.h"
25061da546Spatrick #include "lldb/API/SBFrame.h"
26061da546Spatrick #include "lldb/API/SBValue.h"
27061da546Spatrick #include "lldb/Breakpoint/StoppointCallbackContext.h"
28061da546Spatrick #include "lldb/Breakpoint/WatchpointOptions.h"
29061da546Spatrick #include "lldb/Core/Debugger.h"
30061da546Spatrick #include "lldb/Core/PluginManager.h"
31*f6aab3d8Srobert #include "lldb/Core/ThreadedCommunication.h"
32061da546Spatrick #include "lldb/Core/ValueObject.h"
33061da546Spatrick #include "lldb/DataFormatters/TypeSummary.h"
34061da546Spatrick #include "lldb/Host/FileSystem.h"
35061da546Spatrick #include "lldb/Host/HostInfo.h"
36061da546Spatrick #include "lldb/Host/Pipe.h"
37061da546Spatrick #include "lldb/Interpreter/CommandInterpreter.h"
38061da546Spatrick #include "lldb/Interpreter/CommandReturnObject.h"
39061da546Spatrick #include "lldb/Target/Thread.h"
40061da546Spatrick #include "lldb/Target/ThreadPlan.h"
41*f6aab3d8Srobert #include "lldb/Utility/Instrumentation.h"
42*f6aab3d8Srobert #include "lldb/Utility/LLDBLog.h"
43061da546Spatrick #include "lldb/Utility/Timer.h"
44061da546Spatrick #include "llvm/ADT/STLExtras.h"
45061da546Spatrick #include "llvm/ADT/StringRef.h"
46dda28197Spatrick #include "llvm/Support/Error.h"
47061da546Spatrick #include "llvm/Support/FileSystem.h"
48061da546Spatrick #include "llvm/Support/FormatAdapters.h"
49061da546Spatrick 
50be691f3bSpatrick #include <cstdio>
51be691f3bSpatrick #include <cstdlib>
52061da546Spatrick #include <memory>
53061da546Spatrick #include <mutex>
54*f6aab3d8Srobert #include <optional>
55061da546Spatrick #include <string>
56061da546Spatrick 
57061da546Spatrick using namespace lldb;
58061da546Spatrick using namespace lldb_private;
59061da546Spatrick using namespace lldb_private::python;
60061da546Spatrick using llvm::Expected;
61061da546Spatrick 
62dda28197Spatrick LLDB_PLUGIN_DEFINE(ScriptInterpreterPython)
63dda28197Spatrick 
64061da546Spatrick // Defined in the SWIG source file
65061da546Spatrick extern "C" PyObject *PyInit__lldb(void);
66061da546Spatrick 
67061da546Spatrick #define LLDBSwigPyInit PyInit__lldb
68061da546Spatrick 
69*f6aab3d8Srobert #if defined(_WIN32)
70*f6aab3d8Srobert // Don't mess with the signal handlers on Windows.
71*f6aab3d8Srobert #define LLDB_USE_PYTHON_SET_INTERRUPT 0
72061da546Spatrick #else
73*f6aab3d8Srobert // PyErr_SetInterrupt was introduced in 3.2.
74*f6aab3d8Srobert #define LLDB_USE_PYTHON_SET_INTERRUPT                                          \
75*f6aab3d8Srobert   (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
76061da546Spatrick #endif
77061da546Spatrick 
GetPythonInterpreter(Debugger & debugger)78be691f3bSpatrick static ScriptInterpreterPythonImpl *GetPythonInterpreter(Debugger &debugger) {
79be691f3bSpatrick   ScriptInterpreter *script_interpreter =
80be691f3bSpatrick       debugger.GetScriptInterpreter(true, lldb::eScriptLanguagePython);
81be691f3bSpatrick   return static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
82be691f3bSpatrick }
83be691f3bSpatrick 
84061da546Spatrick namespace {
85061da546Spatrick 
86061da546Spatrick // Initializing Python is not a straightforward process.  We cannot control
87061da546Spatrick // what external code may have done before getting to this point in LLDB,
88061da546Spatrick // including potentially having already initialized Python, so we need to do a
89061da546Spatrick // lot of work to ensure that the existing state of the system is maintained
90061da546Spatrick // across our initialization.  We do this by using an RAII pattern where we
91061da546Spatrick // save off initial state at the beginning, and restore it at the end
92061da546Spatrick struct InitializePythonRAII {
93061da546Spatrick public:
InitializePythonRAII__anond2b647a90111::InitializePythonRAII94be691f3bSpatrick   InitializePythonRAII() {
95061da546Spatrick     InitializePythonHome();
96061da546Spatrick 
97061da546Spatrick #ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
98061da546Spatrick     // Python's readline is incompatible with libedit being linked into lldb.
99061da546Spatrick     // Provide a patched version local to the embedded interpreter.
100061da546Spatrick     bool ReadlinePatched = false;
101*f6aab3d8Srobert     for (auto *p = PyImport_Inittab; p->name != nullptr; p++) {
102061da546Spatrick       if (strcmp(p->name, "readline") == 0) {
103061da546Spatrick         p->initfunc = initlldb_readline;
104061da546Spatrick         break;
105061da546Spatrick       }
106061da546Spatrick     }
107061da546Spatrick     if (!ReadlinePatched) {
108061da546Spatrick       PyImport_AppendInittab("readline", initlldb_readline);
109061da546Spatrick       ReadlinePatched = true;
110061da546Spatrick     }
111061da546Spatrick #endif
112061da546Spatrick 
113061da546Spatrick     // Register _lldb as a built-in module.
114061da546Spatrick     PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
115061da546Spatrick 
116061da546Spatrick // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
117061da546Spatrick // calling `Py_Initialize` and `PyEval_InitThreads`.  < 3.2 requires that you
118061da546Spatrick // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
119061da546Spatrick #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
120061da546Spatrick     Py_InitializeEx(0);
121061da546Spatrick     InitializeThreadsPrivate();
122061da546Spatrick #else
123061da546Spatrick     InitializeThreadsPrivate();
124061da546Spatrick     Py_InitializeEx(0);
125061da546Spatrick #endif
126061da546Spatrick   }
127061da546Spatrick 
~InitializePythonRAII__anond2b647a90111::InitializePythonRAII128061da546Spatrick   ~InitializePythonRAII() {
129061da546Spatrick     if (m_was_already_initialized) {
130*f6aab3d8Srobert       Log *log = GetLog(LLDBLog::Script);
131061da546Spatrick       LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
132061da546Spatrick                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
133061da546Spatrick       PyGILState_Release(m_gil_state);
134061da546Spatrick     } else {
135061da546Spatrick       // We initialized the threads in this function, just unlock the GIL.
136061da546Spatrick       PyEval_SaveThread();
137061da546Spatrick     }
138061da546Spatrick   }
139061da546Spatrick 
140061da546Spatrick private:
InitializePythonHome__anond2b647a90111::InitializePythonRAII141061da546Spatrick   void InitializePythonHome() {
142dda28197Spatrick #if LLDB_EMBED_PYTHON_HOME
143dda28197Spatrick     typedef wchar_t *str_type;
144dda28197Spatrick     static str_type g_python_home = []() -> str_type {
145dda28197Spatrick       const char *lldb_python_home = LLDB_PYTHON_HOME;
146dda28197Spatrick       const char *absolute_python_home = nullptr;
147dda28197Spatrick       llvm::SmallString<64> path;
148dda28197Spatrick       if (llvm::sys::path::is_absolute(lldb_python_home)) {
149dda28197Spatrick         absolute_python_home = lldb_python_home;
150dda28197Spatrick       } else {
151dda28197Spatrick         FileSpec spec = HostInfo::GetShlibDir();
152dda28197Spatrick         if (!spec)
153dda28197Spatrick           return nullptr;
154dda28197Spatrick         spec.GetPath(path);
155dda28197Spatrick         llvm::sys::path::append(path, lldb_python_home);
156dda28197Spatrick         absolute_python_home = path.c_str();
157dda28197Spatrick       }
158061da546Spatrick       size_t size = 0;
159dda28197Spatrick       return Py_DecodeLocale(absolute_python_home, &size);
160dda28197Spatrick     }();
161dda28197Spatrick     if (g_python_home != nullptr) {
162061da546Spatrick       Py_SetPythonHome(g_python_home);
163dda28197Spatrick     }
164061da546Spatrick #endif
165061da546Spatrick   }
166061da546Spatrick 
InitializeThreadsPrivate__anond2b647a90111::InitializePythonRAII167061da546Spatrick   void InitializeThreadsPrivate() {
168061da546Spatrick // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself,
169061da546Spatrick // so there is no way to determine whether the embedded interpreter
170061da546Spatrick // was already initialized by some external code. `PyEval_ThreadsInitialized`
171061da546Spatrick // would always return `true` and `PyGILState_Ensure/Release` flow would be
172061da546Spatrick // executed instead of unlocking GIL with `PyEval_SaveThread`. When
173061da546Spatrick // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock.
174061da546Spatrick #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3)
175061da546Spatrick     // The only case we should go further and acquire the GIL: it is unlocked.
176061da546Spatrick     if (PyGILState_Check())
177061da546Spatrick       return;
178061da546Spatrick #endif
179061da546Spatrick 
180061da546Spatrick     if (PyEval_ThreadsInitialized()) {
181*f6aab3d8Srobert       Log *log = GetLog(LLDBLog::Script);
182061da546Spatrick 
183061da546Spatrick       m_was_already_initialized = true;
184061da546Spatrick       m_gil_state = PyGILState_Ensure();
185061da546Spatrick       LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n",
186061da546Spatrick                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
187061da546Spatrick       return;
188061da546Spatrick     }
189061da546Spatrick 
190061da546Spatrick     // InitThreads acquires the GIL if it hasn't been called before.
191061da546Spatrick     PyEval_InitThreads();
192061da546Spatrick   }
193061da546Spatrick 
194be691f3bSpatrick   PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
195be691f3bSpatrick   bool m_was_already_initialized = false;
196061da546Spatrick };
197*f6aab3d8Srobert 
198*f6aab3d8Srobert #if LLDB_USE_PYTHON_SET_INTERRUPT
199*f6aab3d8Srobert /// Saves the current signal handler for the specified signal and restores
200*f6aab3d8Srobert /// it at the end of the current scope.
201*f6aab3d8Srobert struct RestoreSignalHandlerScope {
202*f6aab3d8Srobert   /// The signal handler.
203*f6aab3d8Srobert   struct sigaction m_prev_handler;
204*f6aab3d8Srobert   int m_signal_code;
RestoreSignalHandlerScope__anond2b647a90111::RestoreSignalHandlerScope205*f6aab3d8Srobert   RestoreSignalHandlerScope(int signal_code) : m_signal_code(signal_code) {
206*f6aab3d8Srobert     // Initialize sigaction to their default state.
207*f6aab3d8Srobert     std::memset(&m_prev_handler, 0, sizeof(m_prev_handler));
208*f6aab3d8Srobert     // Don't install a new handler, just read back the old one.
209*f6aab3d8Srobert     struct sigaction *new_handler = nullptr;
210*f6aab3d8Srobert     int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler);
211*f6aab3d8Srobert     lldbassert(signal_err == 0 && "sigaction failed to read handler");
212*f6aab3d8Srobert   }
~RestoreSignalHandlerScope__anond2b647a90111::RestoreSignalHandlerScope213*f6aab3d8Srobert   ~RestoreSignalHandlerScope() {
214*f6aab3d8Srobert     int signal_err = ::sigaction(m_signal_code, &m_prev_handler, nullptr);
215*f6aab3d8Srobert     lldbassert(signal_err == 0 && "sigaction failed to restore old handler");
216*f6aab3d8Srobert   }
217*f6aab3d8Srobert };
218*f6aab3d8Srobert #endif
219061da546Spatrick } // namespace
220061da546Spatrick 
ComputePythonDirForApple(llvm::SmallVectorImpl<char> & path)221061da546Spatrick void ScriptInterpreterPython::ComputePythonDirForApple(
222061da546Spatrick     llvm::SmallVectorImpl<char> &path) {
223061da546Spatrick   auto style = llvm::sys::path::Style::posix;
224061da546Spatrick 
225061da546Spatrick   llvm::StringRef path_ref(path.begin(), path.size());
226061da546Spatrick   auto rbegin = llvm::sys::path::rbegin(path_ref, style);
227061da546Spatrick   auto rend = llvm::sys::path::rend(path_ref);
228061da546Spatrick   auto framework = std::find(rbegin, rend, "LLDB.framework");
229061da546Spatrick   if (framework == rend) {
230061da546Spatrick     ComputePythonDir(path);
231061da546Spatrick     return;
232061da546Spatrick   }
233061da546Spatrick   path.resize(framework - rend);
234061da546Spatrick   llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
235061da546Spatrick }
236061da546Spatrick 
ComputePythonDir(llvm::SmallVectorImpl<char> & path)237061da546Spatrick void ScriptInterpreterPython::ComputePythonDir(
238061da546Spatrick     llvm::SmallVectorImpl<char> &path) {
239061da546Spatrick   // Build the path by backing out of the lib dir, then building with whatever
240061da546Spatrick   // the real python interpreter uses.  (e.g. lib for most, lib64 on RHEL
241061da546Spatrick   // x86_64, or bin on Windows).
242061da546Spatrick   llvm::sys::path::remove_filename(path);
243061da546Spatrick   llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
244061da546Spatrick 
245061da546Spatrick #if defined(_WIN32)
246*f6aab3d8Srobert   // This will be injected directly through FileSpec.SetDirectory(),
247061da546Spatrick   // so we need to normalize manually.
248061da546Spatrick   std::replace(path.begin(), path.end(), '\\', '/');
249061da546Spatrick #endif
250061da546Spatrick }
251061da546Spatrick 
GetPythonDir()252061da546Spatrick FileSpec ScriptInterpreterPython::GetPythonDir() {
253061da546Spatrick   static FileSpec g_spec = []() {
254061da546Spatrick     FileSpec spec = HostInfo::GetShlibDir();
255061da546Spatrick     if (!spec)
256061da546Spatrick       return FileSpec();
257061da546Spatrick     llvm::SmallString<64> path;
258061da546Spatrick     spec.GetPath(path);
259061da546Spatrick 
260061da546Spatrick #if defined(__APPLE__)
261061da546Spatrick     ComputePythonDirForApple(path);
262061da546Spatrick #else
263061da546Spatrick     ComputePythonDir(path);
264061da546Spatrick #endif
265*f6aab3d8Srobert     spec.SetDirectory(path);
266061da546Spatrick     return spec;
267061da546Spatrick   }();
268061da546Spatrick   return g_spec;
269061da546Spatrick }
270061da546Spatrick 
271*f6aab3d8Srobert static const char GetInterpreterInfoScript[] = R"(
272*f6aab3d8Srobert import os
273*f6aab3d8Srobert import sys
274*f6aab3d8Srobert 
275*f6aab3d8Srobert def main(lldb_python_dir, python_exe_relative_path):
276*f6aab3d8Srobert   info = {
277*f6aab3d8Srobert     "lldb-pythonpath": lldb_python_dir,
278*f6aab3d8Srobert     "language": "python",
279*f6aab3d8Srobert     "prefix": sys.prefix,
280*f6aab3d8Srobert     "executable": os.path.join(sys.prefix, python_exe_relative_path)
281*f6aab3d8Srobert   }
282*f6aab3d8Srobert   return info
283*f6aab3d8Srobert )";
284*f6aab3d8Srobert 
285*f6aab3d8Srobert static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH;
286*f6aab3d8Srobert 
GetInterpreterInfo()287*f6aab3d8Srobert StructuredData::DictionarySP ScriptInterpreterPython::GetInterpreterInfo() {
288*f6aab3d8Srobert   GIL gil;
289*f6aab3d8Srobert   FileSpec python_dir_spec = GetPythonDir();
290*f6aab3d8Srobert   if (!python_dir_spec)
291*f6aab3d8Srobert     return nullptr;
292*f6aab3d8Srobert   PythonScript get_info(GetInterpreterInfoScript);
293*f6aab3d8Srobert   auto info_json = unwrapIgnoringErrors(
294*f6aab3d8Srobert       As<PythonDictionary>(get_info(PythonString(python_dir_spec.GetPath()),
295*f6aab3d8Srobert                                     PythonString(python_exe_relative_path))));
296*f6aab3d8Srobert   if (!info_json)
297*f6aab3d8Srobert     return nullptr;
298*f6aab3d8Srobert   return info_json.CreateStructuredDictionary();
299*f6aab3d8Srobert }
300*f6aab3d8Srobert 
SharedLibraryDirectoryHelper(FileSpec & this_file)301be691f3bSpatrick void ScriptInterpreterPython::SharedLibraryDirectoryHelper(
302be691f3bSpatrick     FileSpec &this_file) {
303be691f3bSpatrick   // When we're loaded from python, this_file will point to the file inside the
304be691f3bSpatrick   // python package directory. Replace it with the one in the lib directory.
305be691f3bSpatrick #ifdef _WIN32
306be691f3bSpatrick   // On windows, we need to manually back out of the python tree, and go into
307be691f3bSpatrick   // the bin directory. This is pretty much the inverse of what ComputePythonDir
308be691f3bSpatrick   // does.
309be691f3bSpatrick   if (this_file.GetFileNameExtension() == ConstString(".pyd")) {
310be691f3bSpatrick     this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd
311be691f3bSpatrick     this_file.RemoveLastPathComponent(); // lldb
312be691f3bSpatrick     llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
313be691f3bSpatrick     for (auto it = llvm::sys::path::begin(libdir),
314be691f3bSpatrick               end = llvm::sys::path::end(libdir);
315be691f3bSpatrick          it != end; ++it)
316be691f3bSpatrick       this_file.RemoveLastPathComponent();
317be691f3bSpatrick     this_file.AppendPathComponent("bin");
318be691f3bSpatrick     this_file.AppendPathComponent("liblldb.dll");
319be691f3bSpatrick   }
320be691f3bSpatrick #else
321be691f3bSpatrick   // The python file is a symlink, so we can find the real library by resolving
322be691f3bSpatrick   // it. We can do this unconditionally.
323be691f3bSpatrick   FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
324be691f3bSpatrick #endif
325be691f3bSpatrick }
326be691f3bSpatrick 
GetPluginDescriptionStatic()327*f6aab3d8Srobert llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() {
328061da546Spatrick   return "Embedded Python interpreter";
329061da546Spatrick }
330061da546Spatrick 
Initialize()331061da546Spatrick void ScriptInterpreterPython::Initialize() {
332061da546Spatrick   static llvm::once_flag g_once_flag;
333061da546Spatrick   llvm::call_once(g_once_flag, []() {
334061da546Spatrick     PluginManager::RegisterPlugin(GetPluginNameStatic(),
335061da546Spatrick                                   GetPluginDescriptionStatic(),
336061da546Spatrick                                   lldb::eScriptLanguagePython,
337061da546Spatrick                                   ScriptInterpreterPythonImpl::CreateInstance);
338*f6aab3d8Srobert     ScriptInterpreterPythonImpl::Initialize();
339061da546Spatrick   });
340061da546Spatrick }
341061da546Spatrick 
Terminate()342061da546Spatrick void ScriptInterpreterPython::Terminate() {}
343061da546Spatrick 
Locker(ScriptInterpreterPythonImpl * py_interpreter,uint16_t on_entry,uint16_t on_leave,FileSP in,FileSP out,FileSP err)344061da546Spatrick ScriptInterpreterPythonImpl::Locker::Locker(
345061da546Spatrick     ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
346061da546Spatrick     uint16_t on_leave, FileSP in, FileSP out, FileSP err)
347061da546Spatrick     : ScriptInterpreterLocker(),
348061da546Spatrick       m_teardown_session((on_leave & TearDownSession) == TearDownSession),
349061da546Spatrick       m_python_interpreter(py_interpreter) {
350061da546Spatrick   DoAcquireLock();
351061da546Spatrick   if ((on_entry & InitSession) == InitSession) {
352061da546Spatrick     if (!DoInitSession(on_entry, in, out, err)) {
353061da546Spatrick       // Don't teardown the session if we didn't init it.
354061da546Spatrick       m_teardown_session = false;
355061da546Spatrick     }
356061da546Spatrick   }
357061da546Spatrick }
358061da546Spatrick 
DoAcquireLock()359061da546Spatrick bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
360*f6aab3d8Srobert   Log *log = GetLog(LLDBLog::Script);
361061da546Spatrick   m_GILState = PyGILState_Ensure();
362061da546Spatrick   LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked",
363061da546Spatrick             m_GILState == PyGILState_UNLOCKED ? "un" : "");
364061da546Spatrick 
365061da546Spatrick   // we need to save the thread state when we first start the command because
366061da546Spatrick   // we might decide to interrupt it while some action is taking place outside
367061da546Spatrick   // of Python (e.g. printing to screen, waiting for the network, ...) in that
368061da546Spatrick   // case, _PyThreadState_Current will be NULL - and we would be unable to set
369061da546Spatrick   // the asynchronous exception - not a desirable situation
370061da546Spatrick   m_python_interpreter->SetThreadState(PyThreadState_Get());
371061da546Spatrick   m_python_interpreter->IncrementLockCount();
372061da546Spatrick   return true;
373061da546Spatrick }
374061da546Spatrick 
DoInitSession(uint16_t on_entry_flags,FileSP in,FileSP out,FileSP err)375061da546Spatrick bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
376061da546Spatrick                                                         FileSP in, FileSP out,
377061da546Spatrick                                                         FileSP err) {
378061da546Spatrick   if (!m_python_interpreter)
379061da546Spatrick     return false;
380061da546Spatrick   return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
381061da546Spatrick }
382061da546Spatrick 
DoFreeLock()383061da546Spatrick bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
384*f6aab3d8Srobert   Log *log = GetLog(LLDBLog::Script);
385061da546Spatrick   LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
386061da546Spatrick             m_GILState == PyGILState_UNLOCKED ? "un" : "");
387061da546Spatrick   PyGILState_Release(m_GILState);
388061da546Spatrick   m_python_interpreter->DecrementLockCount();
389061da546Spatrick   return true;
390061da546Spatrick }
391061da546Spatrick 
DoTearDownSession()392061da546Spatrick bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
393061da546Spatrick   if (!m_python_interpreter)
394061da546Spatrick     return false;
395061da546Spatrick   m_python_interpreter->LeaveSession();
396061da546Spatrick   return true;
397061da546Spatrick }
398061da546Spatrick 
~Locker()399061da546Spatrick ScriptInterpreterPythonImpl::Locker::~Locker() {
400061da546Spatrick   if (m_teardown_session)
401061da546Spatrick     DoTearDownSession();
402061da546Spatrick   DoFreeLock();
403061da546Spatrick }
404061da546Spatrick 
ScriptInterpreterPythonImpl(Debugger & debugger)405061da546Spatrick ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger)
406061da546Spatrick     : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
407061da546Spatrick       m_saved_stderr(), m_main_module(),
408061da546Spatrick       m_session_dict(PyInitialValue::Invalid),
409061da546Spatrick       m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(),
410061da546Spatrick       m_run_one_line_str_global(),
411061da546Spatrick       m_dictionary_name(m_debugger.GetInstanceName().AsCString()),
412061da546Spatrick       m_active_io_handler(eIOHandlerNone), m_session_is_active(false),
413dda28197Spatrick       m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
414061da546Spatrick       m_command_thread_state(nullptr) {
415be691f3bSpatrick   m_scripted_process_interface_up =
416be691f3bSpatrick       std::make_unique<ScriptedProcessPythonInterface>(*this);
417*f6aab3d8Srobert   m_scripted_platform_interface_up =
418*f6aab3d8Srobert       std::make_unique<ScriptedPlatformPythonInterface>(*this);
419be691f3bSpatrick 
420061da546Spatrick   m_dictionary_name.append("_dict");
421061da546Spatrick   StreamString run_string;
422061da546Spatrick   run_string.Printf("%s = dict()", m_dictionary_name.c_str());
423061da546Spatrick 
424061da546Spatrick   Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock);
425061da546Spatrick   PyRun_SimpleString(run_string.GetData());
426061da546Spatrick 
427061da546Spatrick   run_string.Clear();
428061da546Spatrick   run_string.Printf(
429061da546Spatrick       "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
430061da546Spatrick       m_dictionary_name.c_str());
431061da546Spatrick   PyRun_SimpleString(run_string.GetData());
432061da546Spatrick 
433061da546Spatrick   // Reloading modules requires a different syntax in Python 2 and Python 3.
434061da546Spatrick   // This provides a consistent syntax no matter what version of Python.
435061da546Spatrick   run_string.Clear();
436*f6aab3d8Srobert   run_string.Printf("run_one_line (%s, 'from importlib import reload as reload_module')",
437061da546Spatrick                     m_dictionary_name.c_str());
438061da546Spatrick   PyRun_SimpleString(run_string.GetData());
439061da546Spatrick 
440061da546Spatrick   // WARNING: temporary code that loads Cocoa formatters - this should be done
441061da546Spatrick   // on a per-platform basis rather than loading the whole set and letting the
442061da546Spatrick   // individual formatter classes exploit APIs to check whether they can/cannot
443061da546Spatrick   // do their task
444061da546Spatrick   run_string.Clear();
445061da546Spatrick   run_string.Printf(
446061da546Spatrick       "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')",
447061da546Spatrick       m_dictionary_name.c_str());
448061da546Spatrick   PyRun_SimpleString(run_string.GetData());
449061da546Spatrick   run_string.Clear();
450061da546Spatrick 
451061da546Spatrick   run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
452061da546Spatrick                     "lldb.embedded_interpreter import run_python_interpreter; "
453061da546Spatrick                     "from lldb.embedded_interpreter import run_one_line')",
454061da546Spatrick                     m_dictionary_name.c_str());
455061da546Spatrick   PyRun_SimpleString(run_string.GetData());
456061da546Spatrick   run_string.Clear();
457061da546Spatrick 
458061da546Spatrick   run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
459061da546Spatrick                     "; pydoc.pager = pydoc.plainpager')",
460061da546Spatrick                     m_dictionary_name.c_str(), m_debugger.GetID());
461061da546Spatrick   PyRun_SimpleString(run_string.GetData());
462061da546Spatrick }
463061da546Spatrick 
~ScriptInterpreterPythonImpl()464061da546Spatrick ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
465061da546Spatrick   // the session dictionary may hold objects with complex state which means
466061da546Spatrick   // that they may need to be torn down with some level of smarts and that, in
467061da546Spatrick   // turn, requires a valid thread state force Python to procure itself such a
468061da546Spatrick   // thread state, nuke the session dictionary and then release it for others
469061da546Spatrick   // to use and proceed with the rest of the shutdown
470061da546Spatrick   auto gil_state = PyGILState_Ensure();
471061da546Spatrick   m_session_dict.Reset();
472061da546Spatrick   PyGILState_Release(gil_state);
473061da546Spatrick }
474061da546Spatrick 
IOHandlerActivated(IOHandler & io_handler,bool interactive)475061da546Spatrick void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler,
476061da546Spatrick                                                      bool interactive) {
477061da546Spatrick   const char *instructions = nullptr;
478061da546Spatrick 
479061da546Spatrick   switch (m_active_io_handler) {
480061da546Spatrick   case eIOHandlerNone:
481061da546Spatrick     break;
482061da546Spatrick   case eIOHandlerBreakpoint:
483061da546Spatrick     instructions = R"(Enter your Python command(s). Type 'DONE' to end.
484061da546Spatrick def function (frame, bp_loc, internal_dict):
485061da546Spatrick     """frame: the lldb.SBFrame for the location at which you stopped
486061da546Spatrick        bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
487061da546Spatrick        internal_dict: an LLDB support object not to be used"""
488061da546Spatrick )";
489061da546Spatrick     break;
490061da546Spatrick   case eIOHandlerWatchpoint:
491061da546Spatrick     instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
492061da546Spatrick     break;
493061da546Spatrick   }
494061da546Spatrick 
495061da546Spatrick   if (instructions) {
496061da546Spatrick     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
497061da546Spatrick     if (output_sp && interactive) {
498061da546Spatrick       output_sp->PutCString(instructions);
499061da546Spatrick       output_sp->Flush();
500061da546Spatrick     }
501061da546Spatrick   }
502061da546Spatrick }
503061da546Spatrick 
IOHandlerInputComplete(IOHandler & io_handler,std::string & data)504061da546Spatrick void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler,
505061da546Spatrick                                                          std::string &data) {
506061da546Spatrick   io_handler.SetIsDone(true);
507061da546Spatrick   bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
508061da546Spatrick 
509061da546Spatrick   switch (m_active_io_handler) {
510061da546Spatrick   case eIOHandlerNone:
511061da546Spatrick     break;
512061da546Spatrick   case eIOHandlerBreakpoint: {
513be691f3bSpatrick     std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
514be691f3bSpatrick         (std::vector<std::reference_wrapper<BreakpointOptions>> *)
515be691f3bSpatrick             io_handler.GetUserData();
516be691f3bSpatrick     for (BreakpointOptions &bp_options : *bp_options_vec) {
517061da546Spatrick 
518061da546Spatrick       auto data_up = std::make_unique<CommandDataPython>();
519061da546Spatrick       if (!data_up)
520061da546Spatrick         break;
521061da546Spatrick       data_up->user_source.SplitIntoLines(data);
522061da546Spatrick 
523061da546Spatrick       StructuredData::ObjectSP empty_args_sp;
524061da546Spatrick       if (GenerateBreakpointCommandCallbackData(data_up->user_source,
525061da546Spatrick                                                 data_up->script_source,
526061da546Spatrick                                                 false)
527061da546Spatrick               .Success()) {
528061da546Spatrick         auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
529061da546Spatrick             std::move(data_up));
530be691f3bSpatrick         bp_options.SetCallback(
531061da546Spatrick             ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
532061da546Spatrick       } else if (!batch_mode) {
533061da546Spatrick         StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
534061da546Spatrick         if (error_sp) {
535061da546Spatrick           error_sp->Printf("Warning: No command attached to breakpoint.\n");
536061da546Spatrick           error_sp->Flush();
537061da546Spatrick         }
538061da546Spatrick       }
539061da546Spatrick     }
540061da546Spatrick     m_active_io_handler = eIOHandlerNone;
541061da546Spatrick   } break;
542061da546Spatrick   case eIOHandlerWatchpoint: {
543061da546Spatrick     WatchpointOptions *wp_options =
544061da546Spatrick         (WatchpointOptions *)io_handler.GetUserData();
545061da546Spatrick     auto data_up = std::make_unique<WatchpointOptions::CommandData>();
546061da546Spatrick     data_up->user_source.SplitIntoLines(data);
547061da546Spatrick 
548061da546Spatrick     if (GenerateWatchpointCommandCallbackData(data_up->user_source,
549061da546Spatrick                                               data_up->script_source)) {
550061da546Spatrick       auto baton_sp =
551061da546Spatrick           std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
552061da546Spatrick       wp_options->SetCallback(
553061da546Spatrick           ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
554061da546Spatrick     } else if (!batch_mode) {
555061da546Spatrick       StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
556061da546Spatrick       if (error_sp) {
557061da546Spatrick         error_sp->Printf("Warning: No command attached to breakpoint.\n");
558061da546Spatrick         error_sp->Flush();
559061da546Spatrick       }
560061da546Spatrick     }
561061da546Spatrick     m_active_io_handler = eIOHandlerNone;
562061da546Spatrick   } break;
563061da546Spatrick   }
564061da546Spatrick }
565061da546Spatrick 
566061da546Spatrick lldb::ScriptInterpreterSP
CreateInstance(Debugger & debugger)567061da546Spatrick ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) {
568061da546Spatrick   return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
569061da546Spatrick }
570061da546Spatrick 
LeaveSession()571061da546Spatrick void ScriptInterpreterPythonImpl::LeaveSession() {
572*f6aab3d8Srobert   Log *log = GetLog(LLDBLog::Script);
573061da546Spatrick   if (log)
574061da546Spatrick     log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
575061da546Spatrick 
576061da546Spatrick   // Unset the LLDB global variables.
577061da546Spatrick   PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
578061da546Spatrick                      "= None; lldb.thread = None; lldb.frame = None");
579061da546Spatrick 
580061da546Spatrick   // checking that we have a valid thread state - since we use our own
581061da546Spatrick   // threading and locking in some (rare) cases during cleanup Python may end
582061da546Spatrick   // up believing we have no thread state and PyImport_AddModule will crash if
583061da546Spatrick   // that is the case - since that seems to only happen when destroying the
584061da546Spatrick   // SBDebugger, we can make do without clearing up stdout and stderr
585061da546Spatrick 
586061da546Spatrick   // rdar://problem/11292882
587061da546Spatrick   // When the current thread state is NULL, PyThreadState_Get() issues a fatal
588061da546Spatrick   // error.
589061da546Spatrick   if (PyThreadState_GetDict()) {
590061da546Spatrick     PythonDictionary &sys_module_dict = GetSysModuleDictionary();
591061da546Spatrick     if (sys_module_dict.IsValid()) {
592061da546Spatrick       if (m_saved_stdin.IsValid()) {
593061da546Spatrick         sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
594061da546Spatrick         m_saved_stdin.Reset();
595061da546Spatrick       }
596061da546Spatrick       if (m_saved_stdout.IsValid()) {
597061da546Spatrick         sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
598061da546Spatrick         m_saved_stdout.Reset();
599061da546Spatrick       }
600061da546Spatrick       if (m_saved_stderr.IsValid()) {
601061da546Spatrick         sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
602061da546Spatrick         m_saved_stderr.Reset();
603061da546Spatrick       }
604061da546Spatrick     }
605061da546Spatrick   }
606061da546Spatrick 
607061da546Spatrick   m_session_is_active = false;
608061da546Spatrick }
609061da546Spatrick 
SetStdHandle(FileSP file_sp,const char * py_name,PythonObject & save_file,const char * mode)610061da546Spatrick bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp,
611061da546Spatrick                                                const char *py_name,
612061da546Spatrick                                                PythonObject &save_file,
613061da546Spatrick                                                const char *mode) {
614061da546Spatrick   if (!file_sp || !*file_sp) {
615061da546Spatrick     save_file.Reset();
616061da546Spatrick     return false;
617061da546Spatrick   }
618061da546Spatrick   File &file = *file_sp;
619061da546Spatrick 
620061da546Spatrick   // Flush the file before giving it to python to avoid interleaved output.
621061da546Spatrick   file.Flush();
622061da546Spatrick 
623061da546Spatrick   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
624061da546Spatrick 
625061da546Spatrick   auto new_file = PythonFile::FromFile(file, mode);
626061da546Spatrick   if (!new_file) {
627061da546Spatrick     llvm::consumeError(new_file.takeError());
628061da546Spatrick     return false;
629061da546Spatrick   }
630061da546Spatrick 
631061da546Spatrick   save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
632061da546Spatrick 
633061da546Spatrick   sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
634061da546Spatrick   return true;
635061da546Spatrick }
636061da546Spatrick 
EnterSession(uint16_t on_entry_flags,FileSP in_sp,FileSP out_sp,FileSP err_sp)637061da546Spatrick bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
638061da546Spatrick                                                FileSP in_sp, FileSP out_sp,
639061da546Spatrick                                                FileSP err_sp) {
640061da546Spatrick   // If we have already entered the session, without having officially 'left'
641061da546Spatrick   // it, then there is no need to 'enter' it again.
642*f6aab3d8Srobert   Log *log = GetLog(LLDBLog::Script);
643061da546Spatrick   if (m_session_is_active) {
644061da546Spatrick     LLDB_LOGF(
645061da546Spatrick         log,
646061da546Spatrick         "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
647061da546Spatrick         ") session is already active, returning without doing anything",
648061da546Spatrick         on_entry_flags);
649061da546Spatrick     return false;
650061da546Spatrick   }
651061da546Spatrick 
652061da546Spatrick   LLDB_LOGF(
653061da546Spatrick       log,
654061da546Spatrick       "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
655061da546Spatrick       on_entry_flags);
656061da546Spatrick 
657061da546Spatrick   m_session_is_active = true;
658061da546Spatrick 
659061da546Spatrick   StreamString run_string;
660061da546Spatrick 
661061da546Spatrick   if (on_entry_flags & Locker::InitGlobals) {
662061da546Spatrick     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
663061da546Spatrick                       m_dictionary_name.c_str(), m_debugger.GetID());
664061da546Spatrick     run_string.Printf(
665061da546Spatrick         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
666061da546Spatrick         m_debugger.GetID());
667061da546Spatrick     run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
668061da546Spatrick     run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
669061da546Spatrick     run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
670061da546Spatrick     run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
671061da546Spatrick     run_string.PutCString("')");
672061da546Spatrick   } else {
673061da546Spatrick     // If we aren't initing the globals, we should still always set the
674061da546Spatrick     // debugger (since that is always unique.)
675061da546Spatrick     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
676061da546Spatrick                       m_dictionary_name.c_str(), m_debugger.GetID());
677061da546Spatrick     run_string.Printf(
678061da546Spatrick         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
679061da546Spatrick         m_debugger.GetID());
680061da546Spatrick     run_string.PutCString("')");
681061da546Spatrick   }
682061da546Spatrick 
683061da546Spatrick   PyRun_SimpleString(run_string.GetData());
684061da546Spatrick   run_string.Clear();
685061da546Spatrick 
686061da546Spatrick   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
687061da546Spatrick   if (sys_module_dict.IsValid()) {
688061da546Spatrick     lldb::FileSP top_in_sp;
689061da546Spatrick     lldb::StreamFileSP top_out_sp, top_err_sp;
690061da546Spatrick     if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
691061da546Spatrick       m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
692061da546Spatrick                                                  top_err_sp);
693061da546Spatrick 
694061da546Spatrick     if (on_entry_flags & Locker::NoSTDIN) {
695061da546Spatrick       m_saved_stdin.Reset();
696061da546Spatrick     } else {
697061da546Spatrick       if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
698061da546Spatrick         if (top_in_sp)
699061da546Spatrick           SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
700061da546Spatrick       }
701061da546Spatrick     }
702061da546Spatrick 
703061da546Spatrick     if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
704061da546Spatrick       if (top_out_sp)
705061da546Spatrick         SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w");
706061da546Spatrick     }
707061da546Spatrick 
708061da546Spatrick     if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
709061da546Spatrick       if (top_err_sp)
710061da546Spatrick         SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w");
711061da546Spatrick     }
712061da546Spatrick   }
713061da546Spatrick 
714061da546Spatrick   if (PyErr_Occurred())
715061da546Spatrick     PyErr_Clear();
716061da546Spatrick 
717061da546Spatrick   return true;
718061da546Spatrick }
719061da546Spatrick 
GetMainModule()720061da546Spatrick PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
721061da546Spatrick   if (!m_main_module.IsValid())
722061da546Spatrick     m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__"));
723061da546Spatrick   return m_main_module;
724061da546Spatrick }
725061da546Spatrick 
GetSessionDictionary()726061da546Spatrick PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
727061da546Spatrick   if (m_session_dict.IsValid())
728061da546Spatrick     return m_session_dict;
729061da546Spatrick 
730061da546Spatrick   PythonObject &main_module = GetMainModule();
731061da546Spatrick   if (!main_module.IsValid())
732061da546Spatrick     return m_session_dict;
733061da546Spatrick 
734061da546Spatrick   PythonDictionary main_dict(PyRefType::Borrowed,
735061da546Spatrick                              PyModule_GetDict(main_module.get()));
736061da546Spatrick   if (!main_dict.IsValid())
737061da546Spatrick     return m_session_dict;
738061da546Spatrick 
739061da546Spatrick   m_session_dict = unwrapIgnoringErrors(
740061da546Spatrick       As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
741061da546Spatrick   return m_session_dict;
742061da546Spatrick }
743061da546Spatrick 
GetSysModuleDictionary()744061da546Spatrick PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
745061da546Spatrick   if (m_sys_module_dict.IsValid())
746061da546Spatrick     return m_sys_module_dict;
747061da546Spatrick   PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys"));
748061da546Spatrick   m_sys_module_dict = sys_module.GetDictionary();
749061da546Spatrick   return m_sys_module_dict;
750061da546Spatrick }
751061da546Spatrick 
752061da546Spatrick llvm::Expected<unsigned>
GetMaxPositionalArgumentsForCallable(const llvm::StringRef & callable_name)753061da546Spatrick ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
754061da546Spatrick     const llvm::StringRef &callable_name) {
755061da546Spatrick   if (callable_name.empty()) {
756061da546Spatrick     return llvm::createStringError(
757061da546Spatrick         llvm::inconvertibleErrorCode(),
758061da546Spatrick         "called with empty callable name.");
759061da546Spatrick   }
760061da546Spatrick   Locker py_lock(this, Locker::AcquireLock |
761061da546Spatrick                  Locker::InitSession |
762061da546Spatrick                  Locker::NoSTDIN);
763061da546Spatrick   auto dict = PythonModule::MainModule()
764061da546Spatrick       .ResolveName<PythonDictionary>(m_dictionary_name);
765061da546Spatrick   auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
766061da546Spatrick       callable_name, dict);
767061da546Spatrick   if (!pfunc.IsAllocated()) {
768061da546Spatrick     return llvm::createStringError(
769061da546Spatrick         llvm::inconvertibleErrorCode(),
770061da546Spatrick         "can't find callable: %s", callable_name.str().c_str());
771061da546Spatrick   }
772061da546Spatrick   llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
773061da546Spatrick   if (!arg_info)
774061da546Spatrick     return arg_info.takeError();
775061da546Spatrick   return arg_info.get().max_positional_args;
776061da546Spatrick }
777061da546Spatrick 
GenerateUniqueName(const char * base_name_wanted,uint32_t & functions_counter,const void * name_token=nullptr)778061da546Spatrick static std::string GenerateUniqueName(const char *base_name_wanted,
779061da546Spatrick                                       uint32_t &functions_counter,
780061da546Spatrick                                       const void *name_token = nullptr) {
781061da546Spatrick   StreamString sstr;
782061da546Spatrick 
783061da546Spatrick   if (!base_name_wanted)
784061da546Spatrick     return std::string();
785061da546Spatrick 
786061da546Spatrick   if (!name_token)
787061da546Spatrick     sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
788061da546Spatrick   else
789061da546Spatrick     sstr.Printf("%s_%p", base_name_wanted, name_token);
790061da546Spatrick 
791dda28197Spatrick   return std::string(sstr.GetString());
792061da546Spatrick }
793061da546Spatrick 
GetEmbeddedInterpreterModuleObjects()794061da546Spatrick bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
795061da546Spatrick   if (m_run_one_line_function.IsValid())
796061da546Spatrick     return true;
797061da546Spatrick 
798061da546Spatrick   PythonObject module(PyRefType::Borrowed,
799061da546Spatrick                       PyImport_AddModule("lldb.embedded_interpreter"));
800061da546Spatrick   if (!module.IsValid())
801061da546Spatrick     return false;
802061da546Spatrick 
803061da546Spatrick   PythonDictionary module_dict(PyRefType::Borrowed,
804061da546Spatrick                                PyModule_GetDict(module.get()));
805061da546Spatrick   if (!module_dict.IsValid())
806061da546Spatrick     return false;
807061da546Spatrick 
808061da546Spatrick   m_run_one_line_function =
809061da546Spatrick       module_dict.GetItemForKey(PythonString("run_one_line"));
810061da546Spatrick   m_run_one_line_str_global =
811061da546Spatrick       module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
812061da546Spatrick   return m_run_one_line_function.IsValid();
813061da546Spatrick }
814061da546Spatrick 
ExecuteOneLine(llvm::StringRef command,CommandReturnObject * result,const ExecuteScriptOptions & options)815061da546Spatrick bool ScriptInterpreterPythonImpl::ExecuteOneLine(
816061da546Spatrick     llvm::StringRef command, CommandReturnObject *result,
817061da546Spatrick     const ExecuteScriptOptions &options) {
818061da546Spatrick   std::string command_str = command.str();
819061da546Spatrick 
820061da546Spatrick   if (!m_valid_session)
821061da546Spatrick     return false;
822061da546Spatrick 
823061da546Spatrick   if (!command.empty()) {
824061da546Spatrick     // We want to call run_one_line, passing in the dictionary and the command
825061da546Spatrick     // string.  We cannot do this through PyRun_SimpleString here because the
826061da546Spatrick     // command string may contain escaped characters, and putting it inside
827061da546Spatrick     // another string to pass to PyRun_SimpleString messes up the escaping.  So
828061da546Spatrick     // we use the following more complicated method to pass the command string
829061da546Spatrick     // directly down to Python.
830dda28197Spatrick     llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
831dda28197Spatrick         io_redirect_or_error = ScriptInterpreterIORedirect::Create(
832dda28197Spatrick             options.GetEnableIO(), m_debugger, result);
833dda28197Spatrick     if (!io_redirect_or_error) {
834dda28197Spatrick       if (result)
835dda28197Spatrick         result->AppendErrorWithFormatv(
836dda28197Spatrick             "failed to redirect I/O: {0}\n",
837dda28197Spatrick             llvm::fmt_consume(io_redirect_or_error.takeError()));
838dda28197Spatrick       else
839dda28197Spatrick         llvm::consumeError(io_redirect_or_error.takeError());
840061da546Spatrick       return false;
841061da546Spatrick     }
842dda28197Spatrick 
843dda28197Spatrick     ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
844061da546Spatrick 
845061da546Spatrick     bool success = false;
846061da546Spatrick     {
847061da546Spatrick       // WARNING!  It's imperative that this RAII scope be as tight as
848061da546Spatrick       // possible. In particular, the scope must end *before* we try to join
849061da546Spatrick       // the read thread.  The reason for this is that a pre-requisite for
850061da546Spatrick       // joining the read thread is that we close the write handle (to break
851061da546Spatrick       // the pipe and cause it to wake up and exit).  But acquiring the GIL as
852061da546Spatrick       // below will redirect Python's stdio to use this same handle.  If we
853061da546Spatrick       // close the handle while Python is still using it, bad things will
854061da546Spatrick       // happen.
855061da546Spatrick       Locker locker(
856061da546Spatrick           this,
857061da546Spatrick           Locker::AcquireLock | Locker::InitSession |
858061da546Spatrick               (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
859061da546Spatrick               ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
860dda28197Spatrick           Locker::FreeAcquiredLock | Locker::TearDownSession,
861dda28197Spatrick           io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
862dda28197Spatrick           io_redirect.GetErrorFile());
863061da546Spatrick 
864061da546Spatrick       // Find the correct script interpreter dictionary in the main module.
865061da546Spatrick       PythonDictionary &session_dict = GetSessionDictionary();
866061da546Spatrick       if (session_dict.IsValid()) {
867061da546Spatrick         if (GetEmbeddedInterpreterModuleObjects()) {
868061da546Spatrick           if (PyCallable_Check(m_run_one_line_function.get())) {
869061da546Spatrick             PythonObject pargs(
870061da546Spatrick                 PyRefType::Owned,
871061da546Spatrick                 Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
872061da546Spatrick             if (pargs.IsValid()) {
873061da546Spatrick               PythonObject return_value(
874061da546Spatrick                   PyRefType::Owned,
875061da546Spatrick                   PyObject_CallObject(m_run_one_line_function.get(),
876061da546Spatrick                                       pargs.get()));
877061da546Spatrick               if (return_value.IsValid())
878061da546Spatrick                 success = true;
879061da546Spatrick               else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
880061da546Spatrick                 PyErr_Print();
881061da546Spatrick                 PyErr_Clear();
882061da546Spatrick               }
883061da546Spatrick             }
884061da546Spatrick           }
885061da546Spatrick         }
886061da546Spatrick       }
887061da546Spatrick 
888dda28197Spatrick       io_redirect.Flush();
889061da546Spatrick     }
890061da546Spatrick 
891061da546Spatrick     if (success)
892061da546Spatrick       return true;
893061da546Spatrick 
894061da546Spatrick     // The one-liner failed.  Append the error message.
895061da546Spatrick     if (result) {
896061da546Spatrick       result->AppendErrorWithFormat(
897061da546Spatrick           "python failed attempting to evaluate '%s'\n", command_str.c_str());
898061da546Spatrick     }
899061da546Spatrick     return false;
900061da546Spatrick   }
901061da546Spatrick 
902061da546Spatrick   if (result)
903061da546Spatrick     result->AppendError("empty command passed to python\n");
904061da546Spatrick   return false;
905061da546Spatrick }
906061da546Spatrick 
ExecuteInterpreterLoop()907061da546Spatrick void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
908be691f3bSpatrick   LLDB_SCOPED_TIMER();
909061da546Spatrick 
910061da546Spatrick   Debugger &debugger = m_debugger;
911061da546Spatrick 
912061da546Spatrick   // At the moment, the only time the debugger does not have an input file
913061da546Spatrick   // handle is when this is called directly from Python, in which case it is
914061da546Spatrick   // both dangerous and unnecessary (not to mention confusing) to try to embed
915061da546Spatrick   // a running interpreter loop inside the already running Python interpreter
916061da546Spatrick   // loop, so we won't do it.
917061da546Spatrick 
918061da546Spatrick   if (!debugger.GetInputFile().IsValid())
919061da546Spatrick     return;
920061da546Spatrick 
921061da546Spatrick   IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
922061da546Spatrick   if (io_handler_sp) {
923dda28197Spatrick     debugger.RunIOHandlerAsync(io_handler_sp);
924061da546Spatrick   }
925061da546Spatrick }
926061da546Spatrick 
Interrupt()927061da546Spatrick bool ScriptInterpreterPythonImpl::Interrupt() {
928*f6aab3d8Srobert #if LLDB_USE_PYTHON_SET_INTERRUPT
929*f6aab3d8Srobert   // If the interpreter isn't evaluating any Python at the moment then return
930*f6aab3d8Srobert   // false to signal that this function didn't handle the interrupt and the
931*f6aab3d8Srobert   // next component should try handling it.
932*f6aab3d8Srobert   if (!IsExecutingPython())
933*f6aab3d8Srobert     return false;
934*f6aab3d8Srobert 
935*f6aab3d8Srobert   // Tell Python that it should pretend to have received a SIGINT.
936*f6aab3d8Srobert   PyErr_SetInterrupt();
937*f6aab3d8Srobert   // PyErr_SetInterrupt has no way to return an error so we can only pretend the
938*f6aab3d8Srobert   // signal got successfully handled and return true.
939*f6aab3d8Srobert   // Python 3.10 introduces PyErr_SetInterruptEx that could return an error, but
940*f6aab3d8Srobert   // the error handling is limited to checking the arguments which would be
941*f6aab3d8Srobert   // just our (hardcoded) input signal code SIGINT, so that's not useful at all.
942*f6aab3d8Srobert   return true;
943*f6aab3d8Srobert #else
944*f6aab3d8Srobert   Log *log = GetLog(LLDBLog::Script);
945061da546Spatrick 
946061da546Spatrick   if (IsExecutingPython()) {
947061da546Spatrick     PyThreadState *state = PyThreadState_GET();
948061da546Spatrick     if (!state)
949061da546Spatrick       state = GetThreadState();
950061da546Spatrick     if (state) {
951061da546Spatrick       long tid = state->thread_id;
952061da546Spatrick       PyThreadState_Swap(state);
953061da546Spatrick       int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
954061da546Spatrick       LLDB_LOGF(log,
955061da546Spatrick                 "ScriptInterpreterPythonImpl::Interrupt() sending "
956061da546Spatrick                 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
957061da546Spatrick                 tid, num_threads);
958061da546Spatrick       return true;
959061da546Spatrick     }
960061da546Spatrick   }
961061da546Spatrick   LLDB_LOGF(log,
962061da546Spatrick             "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
963061da546Spatrick             "can't interrupt");
964061da546Spatrick   return false;
965*f6aab3d8Srobert #endif
966061da546Spatrick }
967061da546Spatrick 
ExecuteOneLineWithReturn(llvm::StringRef in_string,ScriptInterpreter::ScriptReturnType return_type,void * ret_value,const ExecuteScriptOptions & options)968061da546Spatrick bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
969061da546Spatrick     llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
970061da546Spatrick     void *ret_value, const ExecuteScriptOptions &options) {
971061da546Spatrick 
972be691f3bSpatrick   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
973be691f3bSpatrick       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
974be691f3bSpatrick           options.GetEnableIO(), m_debugger, /*result=*/nullptr);
975be691f3bSpatrick 
976be691f3bSpatrick   if (!io_redirect_or_error) {
977be691f3bSpatrick     llvm::consumeError(io_redirect_or_error.takeError());
978be691f3bSpatrick     return false;
979be691f3bSpatrick   }
980be691f3bSpatrick 
981be691f3bSpatrick   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
982be691f3bSpatrick 
983061da546Spatrick   Locker locker(this,
984061da546Spatrick                 Locker::AcquireLock | Locker::InitSession |
985061da546Spatrick                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
986061da546Spatrick                     Locker::NoSTDIN,
987be691f3bSpatrick                 Locker::FreeAcquiredLock | Locker::TearDownSession,
988be691f3bSpatrick                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
989be691f3bSpatrick                 io_redirect.GetErrorFile());
990061da546Spatrick 
991061da546Spatrick   PythonModule &main_module = GetMainModule();
992061da546Spatrick   PythonDictionary globals = main_module.GetDictionary();
993061da546Spatrick 
994061da546Spatrick   PythonDictionary locals = GetSessionDictionary();
995061da546Spatrick   if (!locals.IsValid())
996061da546Spatrick     locals = unwrapIgnoringErrors(
997061da546Spatrick         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
998061da546Spatrick   if (!locals.IsValid())
999061da546Spatrick     locals = globals;
1000061da546Spatrick 
1001061da546Spatrick   Expected<PythonObject> maybe_py_return =
1002061da546Spatrick       runStringOneLine(in_string, globals, locals);
1003061da546Spatrick 
1004061da546Spatrick   if (!maybe_py_return) {
1005061da546Spatrick     llvm::handleAllErrors(
1006061da546Spatrick         maybe_py_return.takeError(),
1007061da546Spatrick         [&](PythonException &E) {
1008061da546Spatrick           E.Restore();
1009061da546Spatrick           if (options.GetMaskoutErrors()) {
1010061da546Spatrick             if (E.Matches(PyExc_SyntaxError)) {
1011061da546Spatrick               PyErr_Print();
1012061da546Spatrick             }
1013061da546Spatrick             PyErr_Clear();
1014061da546Spatrick           }
1015061da546Spatrick         },
1016061da546Spatrick         [](const llvm::ErrorInfoBase &E) {});
1017061da546Spatrick     return false;
1018061da546Spatrick   }
1019061da546Spatrick 
1020061da546Spatrick   PythonObject py_return = std::move(maybe_py_return.get());
1021061da546Spatrick   assert(py_return.IsValid());
1022061da546Spatrick 
1023061da546Spatrick   switch (return_type) {
1024061da546Spatrick   case eScriptReturnTypeCharPtr: // "char *"
1025061da546Spatrick   {
1026061da546Spatrick     const char format[3] = "s#";
1027061da546Spatrick     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
1028061da546Spatrick   }
1029061da546Spatrick   case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
1030061da546Spatrick                                        // Py_None
1031061da546Spatrick   {
1032061da546Spatrick     const char format[3] = "z";
1033061da546Spatrick     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
1034061da546Spatrick   }
1035061da546Spatrick   case eScriptReturnTypeBool: {
1036061da546Spatrick     const char format[2] = "b";
1037061da546Spatrick     return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
1038061da546Spatrick   }
1039061da546Spatrick   case eScriptReturnTypeShortInt: {
1040061da546Spatrick     const char format[2] = "h";
1041061da546Spatrick     return PyArg_Parse(py_return.get(), format, (short *)ret_value);
1042061da546Spatrick   }
1043061da546Spatrick   case eScriptReturnTypeShortIntUnsigned: {
1044061da546Spatrick     const char format[2] = "H";
1045061da546Spatrick     return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
1046061da546Spatrick   }
1047061da546Spatrick   case eScriptReturnTypeInt: {
1048061da546Spatrick     const char format[2] = "i";
1049061da546Spatrick     return PyArg_Parse(py_return.get(), format, (int *)ret_value);
1050061da546Spatrick   }
1051061da546Spatrick   case eScriptReturnTypeIntUnsigned: {
1052061da546Spatrick     const char format[2] = "I";
1053061da546Spatrick     return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
1054061da546Spatrick   }
1055061da546Spatrick   case eScriptReturnTypeLongInt: {
1056061da546Spatrick     const char format[2] = "l";
1057061da546Spatrick     return PyArg_Parse(py_return.get(), format, (long *)ret_value);
1058061da546Spatrick   }
1059061da546Spatrick   case eScriptReturnTypeLongIntUnsigned: {
1060061da546Spatrick     const char format[2] = "k";
1061061da546Spatrick     return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
1062061da546Spatrick   }
1063061da546Spatrick   case eScriptReturnTypeLongLong: {
1064061da546Spatrick     const char format[2] = "L";
1065061da546Spatrick     return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
1066061da546Spatrick   }
1067061da546Spatrick   case eScriptReturnTypeLongLongUnsigned: {
1068061da546Spatrick     const char format[2] = "K";
1069061da546Spatrick     return PyArg_Parse(py_return.get(), format,
1070061da546Spatrick                        (unsigned long long *)ret_value);
1071061da546Spatrick   }
1072061da546Spatrick   case eScriptReturnTypeFloat: {
1073061da546Spatrick     const char format[2] = "f";
1074061da546Spatrick     return PyArg_Parse(py_return.get(), format, (float *)ret_value);
1075061da546Spatrick   }
1076061da546Spatrick   case eScriptReturnTypeDouble: {
1077061da546Spatrick     const char format[2] = "d";
1078061da546Spatrick     return PyArg_Parse(py_return.get(), format, (double *)ret_value);
1079061da546Spatrick   }
1080061da546Spatrick   case eScriptReturnTypeChar: {
1081061da546Spatrick     const char format[2] = "c";
1082061da546Spatrick     return PyArg_Parse(py_return.get(), format, (char *)ret_value);
1083061da546Spatrick   }
1084061da546Spatrick   case eScriptReturnTypeOpaqueObject: {
1085061da546Spatrick     *((PyObject **)ret_value) = py_return.release();
1086061da546Spatrick     return true;
1087061da546Spatrick   }
1088061da546Spatrick   }
1089061da546Spatrick   llvm_unreachable("Fully covered switch!");
1090061da546Spatrick }
1091061da546Spatrick 
ExecuteMultipleLines(const char * in_string,const ExecuteScriptOptions & options)1092061da546Spatrick Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1093061da546Spatrick     const char *in_string, const ExecuteScriptOptions &options) {
1094061da546Spatrick 
1095061da546Spatrick   if (in_string == nullptr)
1096061da546Spatrick     return Status();
1097061da546Spatrick 
1098be691f3bSpatrick   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1099be691f3bSpatrick       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1100be691f3bSpatrick           options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1101be691f3bSpatrick 
1102be691f3bSpatrick   if (!io_redirect_or_error)
1103be691f3bSpatrick     return Status(io_redirect_or_error.takeError());
1104be691f3bSpatrick 
1105be691f3bSpatrick   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1106be691f3bSpatrick 
1107061da546Spatrick   Locker locker(this,
1108061da546Spatrick                 Locker::AcquireLock | Locker::InitSession |
1109061da546Spatrick                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1110061da546Spatrick                     Locker::NoSTDIN,
1111be691f3bSpatrick                 Locker::FreeAcquiredLock | Locker::TearDownSession,
1112be691f3bSpatrick                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1113be691f3bSpatrick                 io_redirect.GetErrorFile());
1114061da546Spatrick 
1115061da546Spatrick   PythonModule &main_module = GetMainModule();
1116061da546Spatrick   PythonDictionary globals = main_module.GetDictionary();
1117061da546Spatrick 
1118061da546Spatrick   PythonDictionary locals = GetSessionDictionary();
1119061da546Spatrick   if (!locals.IsValid())
1120061da546Spatrick     locals = unwrapIgnoringErrors(
1121061da546Spatrick         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1122061da546Spatrick   if (!locals.IsValid())
1123061da546Spatrick     locals = globals;
1124061da546Spatrick 
1125061da546Spatrick   Expected<PythonObject> return_value =
1126061da546Spatrick       runStringMultiLine(in_string, globals, locals);
1127061da546Spatrick 
1128061da546Spatrick   if (!return_value) {
1129061da546Spatrick     llvm::Error error =
1130061da546Spatrick         llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
1131061da546Spatrick           llvm::Error error = llvm::createStringError(
1132061da546Spatrick               llvm::inconvertibleErrorCode(), E.ReadBacktrace());
1133061da546Spatrick           if (!options.GetMaskoutErrors())
1134061da546Spatrick             E.Restore();
1135061da546Spatrick           return error;
1136061da546Spatrick         });
1137061da546Spatrick     return Status(std::move(error));
1138061da546Spatrick   }
1139061da546Spatrick 
1140061da546Spatrick   return Status();
1141061da546Spatrick }
1142061da546Spatrick 
CollectDataForBreakpointCommandCallback(std::vector<std::reference_wrapper<BreakpointOptions>> & bp_options_vec,CommandReturnObject & result)1143061da546Spatrick void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1144be691f3bSpatrick     std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1145061da546Spatrick     CommandReturnObject &result) {
1146061da546Spatrick   m_active_io_handler = eIOHandlerBreakpoint;
1147061da546Spatrick   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1148061da546Spatrick       "    ", *this, &bp_options_vec);
1149061da546Spatrick }
1150061da546Spatrick 
CollectDataForWatchpointCommandCallback(WatchpointOptions * wp_options,CommandReturnObject & result)1151061da546Spatrick void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1152061da546Spatrick     WatchpointOptions *wp_options, CommandReturnObject &result) {
1153061da546Spatrick   m_active_io_handler = eIOHandlerWatchpoint;
1154061da546Spatrick   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1155061da546Spatrick       "    ", *this, wp_options);
1156061da546Spatrick }
1157061da546Spatrick 
SetBreakpointCommandCallbackFunction(BreakpointOptions & bp_options,const char * function_name,StructuredData::ObjectSP extra_args_sp)1158061da546Spatrick Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1159be691f3bSpatrick     BreakpointOptions &bp_options, const char *function_name,
1160061da546Spatrick     StructuredData::ObjectSP extra_args_sp) {
1161061da546Spatrick   Status error;
1162061da546Spatrick   // For now just cons up a oneliner that calls the provided function.
1163061da546Spatrick   std::string oneliner("return ");
1164061da546Spatrick   oneliner += function_name;
1165061da546Spatrick 
1166061da546Spatrick   llvm::Expected<unsigned> maybe_args =
1167061da546Spatrick       GetMaxPositionalArgumentsForCallable(function_name);
1168061da546Spatrick   if (!maybe_args) {
1169061da546Spatrick     error.SetErrorStringWithFormat(
1170061da546Spatrick         "could not get num args: %s",
1171061da546Spatrick         llvm::toString(maybe_args.takeError()).c_str());
1172061da546Spatrick     return error;
1173061da546Spatrick   }
1174061da546Spatrick   size_t max_args = *maybe_args;
1175061da546Spatrick 
1176061da546Spatrick   bool uses_extra_args = false;
1177061da546Spatrick   if (max_args >= 4) {
1178061da546Spatrick     uses_extra_args = true;
1179061da546Spatrick     oneliner += "(frame, bp_loc, extra_args, internal_dict)";
1180061da546Spatrick   } else if (max_args >= 3) {
1181061da546Spatrick     if (extra_args_sp) {
1182061da546Spatrick       error.SetErrorString("cannot pass extra_args to a three argument callback"
1183061da546Spatrick                           );
1184061da546Spatrick       return error;
1185061da546Spatrick     }
1186061da546Spatrick     uses_extra_args = false;
1187061da546Spatrick     oneliner += "(frame, bp_loc, internal_dict)";
1188061da546Spatrick   } else {
1189061da546Spatrick     error.SetErrorStringWithFormat("expected 3 or 4 argument "
1190061da546Spatrick                                    "function, %s can only take %zu",
1191061da546Spatrick                                    function_name, max_args);
1192061da546Spatrick     return error;
1193061da546Spatrick   }
1194061da546Spatrick 
1195061da546Spatrick   SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp,
1196061da546Spatrick                                uses_extra_args);
1197061da546Spatrick   return error;
1198061da546Spatrick }
1199061da546Spatrick 
SetBreakpointCommandCallback(BreakpointOptions & bp_options,std::unique_ptr<BreakpointOptions::CommandData> & cmd_data_up)1200061da546Spatrick Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1201be691f3bSpatrick     BreakpointOptions &bp_options,
1202061da546Spatrick     std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
1203061da546Spatrick   Status error;
1204061da546Spatrick   error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1205061da546Spatrick                                                 cmd_data_up->script_source,
1206061da546Spatrick                                                 false);
1207061da546Spatrick   if (error.Fail()) {
1208061da546Spatrick     return error;
1209061da546Spatrick   }
1210061da546Spatrick   auto baton_sp =
1211061da546Spatrick       std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1212be691f3bSpatrick   bp_options.SetCallback(
1213061da546Spatrick       ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1214061da546Spatrick   return error;
1215061da546Spatrick }
1216061da546Spatrick 
SetBreakpointCommandCallback(BreakpointOptions & bp_options,const char * command_body_text)1217061da546Spatrick Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1218be691f3bSpatrick     BreakpointOptions &bp_options, const char *command_body_text) {
1219061da546Spatrick   return SetBreakpointCommandCallback(bp_options, command_body_text, {},false);
1220061da546Spatrick }
1221061da546Spatrick 
1222061da546Spatrick // Set a Python one-liner as the callback for the breakpoint.
SetBreakpointCommandCallback(BreakpointOptions & bp_options,const char * command_body_text,StructuredData::ObjectSP extra_args_sp,bool uses_extra_args)1223061da546Spatrick Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1224be691f3bSpatrick     BreakpointOptions &bp_options, const char *command_body_text,
1225be691f3bSpatrick     StructuredData::ObjectSP extra_args_sp, bool uses_extra_args) {
1226061da546Spatrick   auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1227061da546Spatrick   // Split the command_body_text into lines, and pass that to
1228061da546Spatrick   // GenerateBreakpointCommandCallbackData.  That will wrap the body in an
1229061da546Spatrick   // auto-generated function, and return the function name in script_source.
1230061da546Spatrick   // That is what the callback will actually invoke.
1231061da546Spatrick 
1232061da546Spatrick   data_up->user_source.SplitIntoLines(command_body_text);
1233061da546Spatrick   Status error = GenerateBreakpointCommandCallbackData(data_up->user_source,
1234061da546Spatrick                                                        data_up->script_source,
1235061da546Spatrick                                                        uses_extra_args);
1236061da546Spatrick   if (error.Success()) {
1237061da546Spatrick     auto baton_sp =
1238061da546Spatrick         std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1239be691f3bSpatrick     bp_options.SetCallback(
1240061da546Spatrick         ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1241061da546Spatrick     return error;
1242dda28197Spatrick   }
1243061da546Spatrick   return error;
1244061da546Spatrick }
1245061da546Spatrick 
1246061da546Spatrick // Set a Python one-liner as the callback for the watchpoint.
SetWatchpointCommandCallback(WatchpointOptions * wp_options,const char * oneliner)1247061da546Spatrick void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1248061da546Spatrick     WatchpointOptions *wp_options, const char *oneliner) {
1249061da546Spatrick   auto data_up = std::make_unique<WatchpointOptions::CommandData>();
1250061da546Spatrick 
1251061da546Spatrick   // It's necessary to set both user_source and script_source to the oneliner.
1252061da546Spatrick   // The former is used to generate callback description (as in watchpoint
1253061da546Spatrick   // command list) while the latter is used for Python to interpret during the
1254061da546Spatrick   // actual callback.
1255061da546Spatrick 
1256061da546Spatrick   data_up->user_source.AppendString(oneliner);
1257061da546Spatrick   data_up->script_source.assign(oneliner);
1258061da546Spatrick 
1259061da546Spatrick   if (GenerateWatchpointCommandCallbackData(data_up->user_source,
1260061da546Spatrick                                             data_up->script_source)) {
1261061da546Spatrick     auto baton_sp =
1262061da546Spatrick         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
1263061da546Spatrick     wp_options->SetCallback(
1264061da546Spatrick         ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
1265061da546Spatrick   }
1266061da546Spatrick }
1267061da546Spatrick 
ExportFunctionDefinitionToInterpreter(StringList & function_def)1268061da546Spatrick Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1269061da546Spatrick     StringList &function_def) {
1270061da546Spatrick   // Convert StringList to one long, newline delimited, const char *.
1271061da546Spatrick   std::string function_def_string(function_def.CopyList());
1272061da546Spatrick 
1273061da546Spatrick   Status error = ExecuteMultipleLines(
1274061da546Spatrick       function_def_string.c_str(),
1275be691f3bSpatrick       ExecuteScriptOptions().SetEnableIO(false));
1276061da546Spatrick   return error;
1277061da546Spatrick }
1278061da546Spatrick 
GenerateFunction(const char * signature,const StringList & input)1279061da546Spatrick Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature,
1280061da546Spatrick                                                      const StringList &input) {
1281061da546Spatrick   Status error;
1282061da546Spatrick   int num_lines = input.GetSize();
1283061da546Spatrick   if (num_lines == 0) {
1284061da546Spatrick     error.SetErrorString("No input data.");
1285061da546Spatrick     return error;
1286061da546Spatrick   }
1287061da546Spatrick 
1288061da546Spatrick   if (!signature || *signature == 0) {
1289061da546Spatrick     error.SetErrorString("No output function name.");
1290061da546Spatrick     return error;
1291061da546Spatrick   }
1292061da546Spatrick 
1293061da546Spatrick   StreamString sstr;
1294061da546Spatrick   StringList auto_generated_function;
1295061da546Spatrick   auto_generated_function.AppendString(signature);
1296061da546Spatrick   auto_generated_function.AppendString(
1297061da546Spatrick       "     global_dict = globals()"); // Grab the global dictionary
1298061da546Spatrick   auto_generated_function.AppendString(
1299061da546Spatrick       "     new_keys = internal_dict.keys()"); // Make a list of keys in the
1300061da546Spatrick                                                // session dict
1301061da546Spatrick   auto_generated_function.AppendString(
1302061da546Spatrick       "     old_keys = global_dict.keys()"); // Save list of keys in global dict
1303061da546Spatrick   auto_generated_function.AppendString(
1304061da546Spatrick       "     global_dict.update (internal_dict)"); // Add the session dictionary
1305061da546Spatrick                                                   // to the
1306061da546Spatrick   // global dictionary.
1307061da546Spatrick 
1308061da546Spatrick   // Wrap everything up inside the function, increasing the indentation.
1309061da546Spatrick 
1310061da546Spatrick   auto_generated_function.AppendString("     if True:");
1311061da546Spatrick   for (int i = 0; i < num_lines; ++i) {
1312061da546Spatrick     sstr.Clear();
1313061da546Spatrick     sstr.Printf("       %s", input.GetStringAtIndex(i));
1314061da546Spatrick     auto_generated_function.AppendString(sstr.GetData());
1315061da546Spatrick   }
1316061da546Spatrick   auto_generated_function.AppendString(
1317061da546Spatrick       "     for key in new_keys:"); // Iterate over all the keys from session
1318061da546Spatrick                                     // dict
1319061da546Spatrick   auto_generated_function.AppendString(
1320061da546Spatrick       "         internal_dict[key] = global_dict[key]"); // Update session dict
1321061da546Spatrick                                                          // values
1322061da546Spatrick   auto_generated_function.AppendString(
1323061da546Spatrick       "         if key not in old_keys:"); // If key was not originally in
1324061da546Spatrick                                            // global dict
1325061da546Spatrick   auto_generated_function.AppendString(
1326061da546Spatrick       "             del global_dict[key]"); //  ...then remove key/value from
1327061da546Spatrick                                             //  global dict
1328061da546Spatrick 
1329061da546Spatrick   // Verify that the results are valid Python.
1330061da546Spatrick 
1331061da546Spatrick   error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
1332061da546Spatrick 
1333061da546Spatrick   return error;
1334061da546Spatrick }
1335061da546Spatrick 
GenerateTypeScriptFunction(StringList & user_input,std::string & output,const void * name_token)1336061da546Spatrick bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1337061da546Spatrick     StringList &user_input, std::string &output, const void *name_token) {
1338061da546Spatrick   static uint32_t num_created_functions = 0;
1339061da546Spatrick   user_input.RemoveBlankLines();
1340061da546Spatrick   StreamString sstr;
1341061da546Spatrick 
1342061da546Spatrick   // Check to see if we have any data; if not, just return.
1343061da546Spatrick   if (user_input.GetSize() == 0)
1344061da546Spatrick     return false;
1345061da546Spatrick 
1346061da546Spatrick   // Take what the user wrote, wrap it all up inside one big auto-generated
1347061da546Spatrick   // Python function, passing in the ValueObject as parameter to the function.
1348061da546Spatrick 
1349061da546Spatrick   std::string auto_generated_function_name(
1350061da546Spatrick       GenerateUniqueName("lldb_autogen_python_type_print_func",
1351061da546Spatrick                          num_created_functions, name_token));
1352061da546Spatrick   sstr.Printf("def %s (valobj, internal_dict):",
1353061da546Spatrick               auto_generated_function_name.c_str());
1354061da546Spatrick 
1355061da546Spatrick   if (!GenerateFunction(sstr.GetData(), user_input).Success())
1356061da546Spatrick     return false;
1357061da546Spatrick 
1358061da546Spatrick   // Store the name of the auto-generated function to be called.
1359061da546Spatrick   output.assign(auto_generated_function_name);
1360061da546Spatrick   return true;
1361061da546Spatrick }
1362061da546Spatrick 
GenerateScriptAliasFunction(StringList & user_input,std::string & output)1363061da546Spatrick bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1364061da546Spatrick     StringList &user_input, std::string &output) {
1365061da546Spatrick   static uint32_t num_created_functions = 0;
1366061da546Spatrick   user_input.RemoveBlankLines();
1367061da546Spatrick   StreamString sstr;
1368061da546Spatrick 
1369061da546Spatrick   // Check to see if we have any data; if not, just return.
1370061da546Spatrick   if (user_input.GetSize() == 0)
1371061da546Spatrick     return false;
1372061da546Spatrick 
1373061da546Spatrick   std::string auto_generated_function_name(GenerateUniqueName(
1374061da546Spatrick       "lldb_autogen_python_cmd_alias_func", num_created_functions));
1375061da546Spatrick 
1376*f6aab3d8Srobert   sstr.Printf("def %s (debugger, args, exe_ctx, result, internal_dict):",
1377061da546Spatrick               auto_generated_function_name.c_str());
1378061da546Spatrick 
1379061da546Spatrick   if (!GenerateFunction(sstr.GetData(), user_input).Success())
1380061da546Spatrick     return false;
1381061da546Spatrick 
1382061da546Spatrick   // Store the name of the auto-generated function to be called.
1383061da546Spatrick   output.assign(auto_generated_function_name);
1384061da546Spatrick   return true;
1385061da546Spatrick }
1386061da546Spatrick 
GenerateTypeSynthClass(StringList & user_input,std::string & output,const void * name_token)1387061da546Spatrick bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1388061da546Spatrick     StringList &user_input, std::string &output, const void *name_token) {
1389061da546Spatrick   static uint32_t num_created_classes = 0;
1390061da546Spatrick   user_input.RemoveBlankLines();
1391061da546Spatrick   int num_lines = user_input.GetSize();
1392061da546Spatrick   StreamString sstr;
1393061da546Spatrick 
1394061da546Spatrick   // Check to see if we have any data; if not, just return.
1395061da546Spatrick   if (user_input.GetSize() == 0)
1396061da546Spatrick     return false;
1397061da546Spatrick 
1398061da546Spatrick   // Wrap all user input into a Python class
1399061da546Spatrick 
1400061da546Spatrick   std::string auto_generated_class_name(GenerateUniqueName(
1401061da546Spatrick       "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1402061da546Spatrick 
1403061da546Spatrick   StringList auto_generated_class;
1404061da546Spatrick 
1405061da546Spatrick   // Create the function name & definition string.
1406061da546Spatrick 
1407061da546Spatrick   sstr.Printf("class %s:", auto_generated_class_name.c_str());
1408061da546Spatrick   auto_generated_class.AppendString(sstr.GetString());
1409061da546Spatrick 
1410061da546Spatrick   // Wrap everything up inside the class, increasing the indentation. we don't
1411061da546Spatrick   // need to play any fancy indentation tricks here because there is no
1412061da546Spatrick   // surrounding code whose indentation we need to honor
1413061da546Spatrick   for (int i = 0; i < num_lines; ++i) {
1414061da546Spatrick     sstr.Clear();
1415061da546Spatrick     sstr.Printf("     %s", user_input.GetStringAtIndex(i));
1416061da546Spatrick     auto_generated_class.AppendString(sstr.GetString());
1417061da546Spatrick   }
1418061da546Spatrick 
1419061da546Spatrick   // Verify that the results are valid Python. (even though the method is
1420061da546Spatrick   // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1421061da546Spatrick   // (TODO: rename that method to ExportDefinitionToInterpreter)
1422061da546Spatrick   if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
1423061da546Spatrick     return false;
1424061da546Spatrick 
1425061da546Spatrick   // Store the name of the auto-generated class
1426061da546Spatrick 
1427061da546Spatrick   output.assign(auto_generated_class_name);
1428061da546Spatrick   return true;
1429061da546Spatrick }
1430061da546Spatrick 
1431061da546Spatrick StructuredData::GenericSP
CreateFrameRecognizer(const char * class_name)1432061da546Spatrick ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
1433061da546Spatrick   if (class_name == nullptr || class_name[0] == '\0')
1434061da546Spatrick     return StructuredData::GenericSP();
1435061da546Spatrick 
1436*f6aab3d8Srobert   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1437*f6aab3d8Srobert   PythonObject ret_val = LLDBSWIGPython_CreateFrameRecognizer(
1438*f6aab3d8Srobert       class_name, m_dictionary_name.c_str());
1439061da546Spatrick 
1440*f6aab3d8Srobert   return StructuredData::GenericSP(
1441*f6aab3d8Srobert       new StructuredPythonObject(std::move(ret_val)));
1442061da546Spatrick }
1443061da546Spatrick 
GetRecognizedArguments(const StructuredData::ObjectSP & os_plugin_object_sp,lldb::StackFrameSP frame_sp)1444061da546Spatrick lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
1445061da546Spatrick     const StructuredData::ObjectSP &os_plugin_object_sp,
1446061da546Spatrick     lldb::StackFrameSP frame_sp) {
1447061da546Spatrick   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1448061da546Spatrick 
1449061da546Spatrick   if (!os_plugin_object_sp)
1450061da546Spatrick     return ValueObjectListSP();
1451061da546Spatrick 
1452061da546Spatrick   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1453061da546Spatrick   if (!generic)
1454061da546Spatrick     return nullptr;
1455061da546Spatrick 
1456061da546Spatrick   PythonObject implementor(PyRefType::Borrowed,
1457061da546Spatrick                            (PyObject *)generic->GetValue());
1458061da546Spatrick 
1459061da546Spatrick   if (!implementor.IsAllocated())
1460061da546Spatrick     return ValueObjectListSP();
1461061da546Spatrick 
1462*f6aab3d8Srobert   PythonObject py_return(
1463*f6aab3d8Srobert       PyRefType::Owned,
1464*f6aab3d8Srobert       LLDBSwigPython_GetRecognizedArguments(implementor.get(), frame_sp));
1465061da546Spatrick 
1466061da546Spatrick   // if it fails, print the error but otherwise go on
1467061da546Spatrick   if (PyErr_Occurred()) {
1468061da546Spatrick     PyErr_Print();
1469061da546Spatrick     PyErr_Clear();
1470061da546Spatrick   }
1471061da546Spatrick   if (py_return.get()) {
1472061da546Spatrick     PythonList result_list(PyRefType::Borrowed, py_return.get());
1473061da546Spatrick     ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
1474061da546Spatrick     for (size_t i = 0; i < result_list.GetSize(); i++) {
1475061da546Spatrick       PyObject *item = result_list.GetItemAtIndex(i).get();
1476061da546Spatrick       lldb::SBValue *sb_value_ptr =
1477061da546Spatrick           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
1478061da546Spatrick       auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
1479061da546Spatrick       if (valobj_sp)
1480061da546Spatrick         result->Append(valobj_sp);
1481061da546Spatrick     }
1482061da546Spatrick     return result;
1483061da546Spatrick   }
1484061da546Spatrick   return ValueObjectListSP();
1485061da546Spatrick }
1486061da546Spatrick 
1487061da546Spatrick StructuredData::GenericSP
OSPlugin_CreatePluginObject(const char * class_name,lldb::ProcessSP process_sp)1488061da546Spatrick ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject(
1489061da546Spatrick     const char *class_name, lldb::ProcessSP process_sp) {
1490061da546Spatrick   if (class_name == nullptr || class_name[0] == '\0')
1491061da546Spatrick     return StructuredData::GenericSP();
1492061da546Spatrick 
1493061da546Spatrick   if (!process_sp)
1494061da546Spatrick     return StructuredData::GenericSP();
1495061da546Spatrick 
1496*f6aab3d8Srobert   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1497*f6aab3d8Srobert   PythonObject ret_val = LLDBSWIGPythonCreateOSPlugin(
1498061da546Spatrick       class_name, m_dictionary_name.c_str(), process_sp);
1499061da546Spatrick 
1500*f6aab3d8Srobert   return StructuredData::GenericSP(
1501*f6aab3d8Srobert       new StructuredPythonObject(std::move(ret_val)));
1502061da546Spatrick }
1503061da546Spatrick 
OSPlugin_RegisterInfo(StructuredData::ObjectSP os_plugin_object_sp)1504061da546Spatrick StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo(
1505061da546Spatrick     StructuredData::ObjectSP os_plugin_object_sp) {
1506061da546Spatrick   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1507061da546Spatrick 
1508061da546Spatrick   if (!os_plugin_object_sp)
1509*f6aab3d8Srobert     return {};
1510061da546Spatrick 
1511061da546Spatrick   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1512061da546Spatrick   if (!generic)
1513*f6aab3d8Srobert     return {};
1514061da546Spatrick 
1515061da546Spatrick   PythonObject implementor(PyRefType::Borrowed,
1516061da546Spatrick                            (PyObject *)generic->GetValue());
1517061da546Spatrick 
1518061da546Spatrick   if (!implementor.IsAllocated())
1519*f6aab3d8Srobert     return {};
1520061da546Spatrick 
1521*f6aab3d8Srobert   llvm::Expected<PythonObject> expected_py_return =
1522*f6aab3d8Srobert       implementor.CallMethod("get_register_info");
1523061da546Spatrick 
1524*f6aab3d8Srobert   if (!expected_py_return) {
1525*f6aab3d8Srobert     llvm::consumeError(expected_py_return.takeError());
1526*f6aab3d8Srobert     return {};
1527061da546Spatrick   }
1528061da546Spatrick 
1529*f6aab3d8Srobert   PythonObject py_return = std::move(expected_py_return.get());
1530061da546Spatrick 
1531061da546Spatrick   if (py_return.get()) {
1532061da546Spatrick     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1533061da546Spatrick     return result_dict.CreateStructuredDictionary();
1534061da546Spatrick   }
1535061da546Spatrick   return StructuredData::DictionarySP();
1536061da546Spatrick }
1537061da546Spatrick 
OSPlugin_ThreadsInfo(StructuredData::ObjectSP os_plugin_object_sp)1538061da546Spatrick StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo(
1539061da546Spatrick     StructuredData::ObjectSP os_plugin_object_sp) {
1540061da546Spatrick   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1541061da546Spatrick   if (!os_plugin_object_sp)
1542*f6aab3d8Srobert     return {};
1543061da546Spatrick 
1544061da546Spatrick   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1545061da546Spatrick   if (!generic)
1546*f6aab3d8Srobert     return {};
1547061da546Spatrick 
1548061da546Spatrick   PythonObject implementor(PyRefType::Borrowed,
1549061da546Spatrick                            (PyObject *)generic->GetValue());
1550061da546Spatrick 
1551061da546Spatrick   if (!implementor.IsAllocated())
1552*f6aab3d8Srobert     return {};
1553061da546Spatrick 
1554*f6aab3d8Srobert   llvm::Expected<PythonObject> expected_py_return =
1555*f6aab3d8Srobert       implementor.CallMethod("get_thread_info");
1556061da546Spatrick 
1557*f6aab3d8Srobert   if (!expected_py_return) {
1558*f6aab3d8Srobert     llvm::consumeError(expected_py_return.takeError());
1559*f6aab3d8Srobert     return {};
1560061da546Spatrick   }
1561061da546Spatrick 
1562*f6aab3d8Srobert   PythonObject py_return = std::move(expected_py_return.get());
1563061da546Spatrick 
1564061da546Spatrick   if (py_return.get()) {
1565061da546Spatrick     PythonList result_list(PyRefType::Borrowed, py_return.get());
1566061da546Spatrick     return result_list.CreateStructuredArray();
1567061da546Spatrick   }
1568061da546Spatrick   return StructuredData::ArraySP();
1569061da546Spatrick }
1570061da546Spatrick 
1571061da546Spatrick StructuredData::StringSP
OSPlugin_RegisterContextData(StructuredData::ObjectSP os_plugin_object_sp,lldb::tid_t tid)1572061da546Spatrick ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData(
1573061da546Spatrick     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
1574061da546Spatrick   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1575061da546Spatrick 
1576061da546Spatrick   if (!os_plugin_object_sp)
1577*f6aab3d8Srobert     return {};
1578061da546Spatrick 
1579061da546Spatrick   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1580061da546Spatrick   if (!generic)
1581*f6aab3d8Srobert     return {};
1582061da546Spatrick   PythonObject implementor(PyRefType::Borrowed,
1583061da546Spatrick                            (PyObject *)generic->GetValue());
1584061da546Spatrick 
1585061da546Spatrick   if (!implementor.IsAllocated())
1586*f6aab3d8Srobert     return {};
1587061da546Spatrick 
1588*f6aab3d8Srobert   llvm::Expected<PythonObject> expected_py_return =
1589*f6aab3d8Srobert       implementor.CallMethod("get_register_data", tid);
1590061da546Spatrick 
1591*f6aab3d8Srobert   if (!expected_py_return) {
1592*f6aab3d8Srobert     llvm::consumeError(expected_py_return.takeError());
1593*f6aab3d8Srobert     return {};
1594061da546Spatrick   }
1595061da546Spatrick 
1596*f6aab3d8Srobert   PythonObject py_return = std::move(expected_py_return.get());
1597061da546Spatrick 
1598061da546Spatrick   if (py_return.get()) {
1599061da546Spatrick     PythonBytes result(PyRefType::Borrowed, py_return.get());
1600061da546Spatrick     return result.CreateStructuredString();
1601061da546Spatrick   }
1602*f6aab3d8Srobert   return {};
1603061da546Spatrick }
1604061da546Spatrick 
OSPlugin_CreateThread(StructuredData::ObjectSP os_plugin_object_sp,lldb::tid_t tid,lldb::addr_t context)1605061da546Spatrick StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread(
1606061da546Spatrick     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
1607061da546Spatrick     lldb::addr_t context) {
1608061da546Spatrick   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1609061da546Spatrick 
1610061da546Spatrick   if (!os_plugin_object_sp)
1611*f6aab3d8Srobert     return {};
1612061da546Spatrick 
1613061da546Spatrick   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1614061da546Spatrick   if (!generic)
1615*f6aab3d8Srobert     return {};
1616061da546Spatrick 
1617061da546Spatrick   PythonObject implementor(PyRefType::Borrowed,
1618061da546Spatrick                            (PyObject *)generic->GetValue());
1619061da546Spatrick 
1620061da546Spatrick   if (!implementor.IsAllocated())
1621*f6aab3d8Srobert     return {};
1622061da546Spatrick 
1623*f6aab3d8Srobert   llvm::Expected<PythonObject> expected_py_return =
1624*f6aab3d8Srobert       implementor.CallMethod("create_thread", tid, context);
1625061da546Spatrick 
1626*f6aab3d8Srobert   if (!expected_py_return) {
1627*f6aab3d8Srobert     llvm::consumeError(expected_py_return.takeError());
1628*f6aab3d8Srobert     return {};
1629061da546Spatrick   }
1630061da546Spatrick 
1631*f6aab3d8Srobert   PythonObject py_return = std::move(expected_py_return.get());
1632061da546Spatrick 
1633061da546Spatrick   if (py_return.get()) {
1634061da546Spatrick     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1635061da546Spatrick     return result_dict.CreateStructuredDictionary();
1636061da546Spatrick   }
1637061da546Spatrick   return StructuredData::DictionarySP();
1638061da546Spatrick }
1639061da546Spatrick 
CreateScriptedThreadPlan(const char * class_name,const StructuredDataImpl & args_data,std::string & error_str,lldb::ThreadPlanSP thread_plan_sp)1640061da546Spatrick StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan(
1641*f6aab3d8Srobert     const char *class_name, const StructuredDataImpl &args_data,
1642061da546Spatrick     std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) {
1643061da546Spatrick   if (class_name == nullptr || class_name[0] == '\0')
1644061da546Spatrick     return StructuredData::ObjectSP();
1645061da546Spatrick 
1646061da546Spatrick   if (!thread_plan_sp.get())
1647061da546Spatrick     return {};
1648061da546Spatrick 
1649061da546Spatrick   Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
1650061da546Spatrick   ScriptInterpreterPythonImpl *python_interpreter =
1651be691f3bSpatrick       GetPythonInterpreter(debugger);
1652061da546Spatrick 
1653be691f3bSpatrick   if (!python_interpreter)
1654061da546Spatrick     return {};
1655061da546Spatrick 
1656061da546Spatrick   Locker py_lock(this,
1657061da546Spatrick                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1658*f6aab3d8Srobert   PythonObject ret_val = LLDBSwigPythonCreateScriptedThreadPlan(
1659*f6aab3d8Srobert       class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
1660*f6aab3d8Srobert       error_str, thread_plan_sp);
1661061da546Spatrick   if (!ret_val)
1662061da546Spatrick     return {};
1663061da546Spatrick 
1664*f6aab3d8Srobert   return StructuredData::ObjectSP(
1665*f6aab3d8Srobert       new StructuredPythonObject(std::move(ret_val)));
1666061da546Spatrick }
1667061da546Spatrick 
ScriptedThreadPlanExplainsStop(StructuredData::ObjectSP implementor_sp,Event * event,bool & script_error)1668061da546Spatrick bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop(
1669061da546Spatrick     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1670061da546Spatrick   bool explains_stop = true;
1671061da546Spatrick   StructuredData::Generic *generic = nullptr;
1672061da546Spatrick   if (implementor_sp)
1673061da546Spatrick     generic = implementor_sp->GetAsGeneric();
1674061da546Spatrick   if (generic) {
1675061da546Spatrick     Locker py_lock(this,
1676061da546Spatrick                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1677061da546Spatrick     explains_stop = LLDBSWIGPythonCallThreadPlan(
1678061da546Spatrick         generic->GetValue(), "explains_stop", event, script_error);
1679061da546Spatrick     if (script_error)
1680061da546Spatrick       return true;
1681061da546Spatrick   }
1682061da546Spatrick   return explains_stop;
1683061da546Spatrick }
1684061da546Spatrick 
ScriptedThreadPlanShouldStop(StructuredData::ObjectSP implementor_sp,Event * event,bool & script_error)1685061da546Spatrick bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop(
1686061da546Spatrick     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1687061da546Spatrick   bool should_stop = true;
1688061da546Spatrick   StructuredData::Generic *generic = nullptr;
1689061da546Spatrick   if (implementor_sp)
1690061da546Spatrick     generic = implementor_sp->GetAsGeneric();
1691061da546Spatrick   if (generic) {
1692061da546Spatrick     Locker py_lock(this,
1693061da546Spatrick                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1694061da546Spatrick     should_stop = LLDBSWIGPythonCallThreadPlan(
1695061da546Spatrick         generic->GetValue(), "should_stop", event, script_error);
1696061da546Spatrick     if (script_error)
1697061da546Spatrick       return true;
1698061da546Spatrick   }
1699061da546Spatrick   return should_stop;
1700061da546Spatrick }
1701061da546Spatrick 
ScriptedThreadPlanIsStale(StructuredData::ObjectSP implementor_sp,bool & script_error)1702061da546Spatrick bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale(
1703061da546Spatrick     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1704061da546Spatrick   bool is_stale = true;
1705061da546Spatrick   StructuredData::Generic *generic = nullptr;
1706061da546Spatrick   if (implementor_sp)
1707061da546Spatrick     generic = implementor_sp->GetAsGeneric();
1708061da546Spatrick   if (generic) {
1709061da546Spatrick     Locker py_lock(this,
1710061da546Spatrick                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1711061da546Spatrick     is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale",
1712061da546Spatrick                                             nullptr, script_error);
1713061da546Spatrick     if (script_error)
1714061da546Spatrick       return true;
1715061da546Spatrick   }
1716061da546Spatrick   return is_stale;
1717061da546Spatrick }
1718061da546Spatrick 
ScriptedThreadPlanGetRunState(StructuredData::ObjectSP implementor_sp,bool & script_error)1719061da546Spatrick lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState(
1720061da546Spatrick     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1721061da546Spatrick   bool should_step = false;
1722061da546Spatrick   StructuredData::Generic *generic = nullptr;
1723061da546Spatrick   if (implementor_sp)
1724061da546Spatrick     generic = implementor_sp->GetAsGeneric();
1725061da546Spatrick   if (generic) {
1726061da546Spatrick     Locker py_lock(this,
1727061da546Spatrick                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1728061da546Spatrick     should_step = LLDBSWIGPythonCallThreadPlan(
1729061da546Spatrick         generic->GetValue(), "should_step", nullptr, script_error);
1730061da546Spatrick     if (script_error)
1731061da546Spatrick       should_step = true;
1732061da546Spatrick   }
1733061da546Spatrick   if (should_step)
1734061da546Spatrick     return lldb::eStateStepping;
1735061da546Spatrick   return lldb::eStateRunning;
1736061da546Spatrick }
1737061da546Spatrick 
1738061da546Spatrick StructuredData::GenericSP
CreateScriptedBreakpointResolver(const char * class_name,const StructuredDataImpl & args_data,lldb::BreakpointSP & bkpt_sp)1739061da546Spatrick ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
1740*f6aab3d8Srobert     const char *class_name, const StructuredDataImpl &args_data,
1741061da546Spatrick     lldb::BreakpointSP &bkpt_sp) {
1742061da546Spatrick 
1743061da546Spatrick   if (class_name == nullptr || class_name[0] == '\0')
1744061da546Spatrick     return StructuredData::GenericSP();
1745061da546Spatrick 
1746061da546Spatrick   if (!bkpt_sp.get())
1747061da546Spatrick     return StructuredData::GenericSP();
1748061da546Spatrick 
1749061da546Spatrick   Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
1750061da546Spatrick   ScriptInterpreterPythonImpl *python_interpreter =
1751be691f3bSpatrick       GetPythonInterpreter(debugger);
1752061da546Spatrick 
1753be691f3bSpatrick   if (!python_interpreter)
1754061da546Spatrick     return StructuredData::GenericSP();
1755061da546Spatrick 
1756061da546Spatrick   Locker py_lock(this,
1757061da546Spatrick                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1758061da546Spatrick 
1759*f6aab3d8Srobert   PythonObject ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver(
1760061da546Spatrick       class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
1761061da546Spatrick       bkpt_sp);
1762061da546Spatrick 
1763*f6aab3d8Srobert   return StructuredData::GenericSP(
1764*f6aab3d8Srobert       new StructuredPythonObject(std::move(ret_val)));
1765061da546Spatrick }
1766061da546Spatrick 
ScriptedBreakpointResolverSearchCallback(StructuredData::GenericSP implementor_sp,SymbolContext * sym_ctx)1767061da546Spatrick bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
1768061da546Spatrick     StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
1769061da546Spatrick   bool should_continue = false;
1770061da546Spatrick 
1771061da546Spatrick   if (implementor_sp) {
1772061da546Spatrick     Locker py_lock(this,
1773061da546Spatrick                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1774061da546Spatrick     should_continue = LLDBSwigPythonCallBreakpointResolver(
1775061da546Spatrick         implementor_sp->GetValue(), "__callback__", sym_ctx);
1776061da546Spatrick     if (PyErr_Occurred()) {
1777061da546Spatrick       PyErr_Print();
1778061da546Spatrick       PyErr_Clear();
1779061da546Spatrick     }
1780061da546Spatrick   }
1781061da546Spatrick   return should_continue;
1782061da546Spatrick }
1783061da546Spatrick 
1784061da546Spatrick lldb::SearchDepth
ScriptedBreakpointResolverSearchDepth(StructuredData::GenericSP implementor_sp)1785061da546Spatrick ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
1786061da546Spatrick     StructuredData::GenericSP implementor_sp) {
1787061da546Spatrick   int depth_as_int = lldb::eSearchDepthModule;
1788061da546Spatrick   if (implementor_sp) {
1789061da546Spatrick     Locker py_lock(this,
1790061da546Spatrick                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1791061da546Spatrick     depth_as_int = LLDBSwigPythonCallBreakpointResolver(
1792061da546Spatrick         implementor_sp->GetValue(), "__get_depth__", nullptr);
1793061da546Spatrick     if (PyErr_Occurred()) {
1794061da546Spatrick       PyErr_Print();
1795061da546Spatrick       PyErr_Clear();
1796061da546Spatrick     }
1797061da546Spatrick   }
1798061da546Spatrick   if (depth_as_int == lldb::eSearchDepthInvalid)
1799061da546Spatrick     return lldb::eSearchDepthModule;
1800061da546Spatrick 
1801061da546Spatrick   if (depth_as_int <= lldb::kLastSearchDepthKind)
1802061da546Spatrick     return (lldb::SearchDepth)depth_as_int;
1803061da546Spatrick   return lldb::eSearchDepthModule;
1804061da546Spatrick }
1805061da546Spatrick 
CreateScriptedStopHook(TargetSP target_sp,const char * class_name,const StructuredDataImpl & args_data,Status & error)1806be691f3bSpatrick StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
1807*f6aab3d8Srobert     TargetSP target_sp, const char *class_name,
1808*f6aab3d8Srobert     const StructuredDataImpl &args_data, Status &error) {
1809be691f3bSpatrick 
1810be691f3bSpatrick   if (!target_sp) {
1811be691f3bSpatrick     error.SetErrorString("No target for scripted stop-hook.");
1812be691f3bSpatrick     return StructuredData::GenericSP();
1813be691f3bSpatrick   }
1814be691f3bSpatrick 
1815be691f3bSpatrick   if (class_name == nullptr || class_name[0] == '\0') {
1816be691f3bSpatrick     error.SetErrorString("No class name for scripted stop-hook.");
1817be691f3bSpatrick     return StructuredData::GenericSP();
1818be691f3bSpatrick   }
1819be691f3bSpatrick 
1820be691f3bSpatrick   ScriptInterpreterPythonImpl *python_interpreter =
1821be691f3bSpatrick       GetPythonInterpreter(m_debugger);
1822be691f3bSpatrick 
1823be691f3bSpatrick   if (!python_interpreter) {
1824be691f3bSpatrick     error.SetErrorString("No script interpreter for scripted stop-hook.");
1825be691f3bSpatrick     return StructuredData::GenericSP();
1826be691f3bSpatrick   }
1827be691f3bSpatrick 
1828be691f3bSpatrick   Locker py_lock(this,
1829be691f3bSpatrick                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1830be691f3bSpatrick 
1831*f6aab3d8Srobert   PythonObject ret_val = LLDBSwigPythonCreateScriptedStopHook(
1832be691f3bSpatrick       target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
1833be691f3bSpatrick       args_data, error);
1834be691f3bSpatrick 
1835*f6aab3d8Srobert   return StructuredData::GenericSP(
1836*f6aab3d8Srobert       new StructuredPythonObject(std::move(ret_val)));
1837be691f3bSpatrick }
1838be691f3bSpatrick 
ScriptedStopHookHandleStop(StructuredData::GenericSP implementor_sp,ExecutionContext & exc_ctx,lldb::StreamSP stream_sp)1839be691f3bSpatrick bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
1840be691f3bSpatrick     StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
1841be691f3bSpatrick     lldb::StreamSP stream_sp) {
1842be691f3bSpatrick   assert(implementor_sp &&
1843be691f3bSpatrick          "can't call a stop hook with an invalid implementor");
1844be691f3bSpatrick   assert(stream_sp && "can't call a stop hook with an invalid stream");
1845be691f3bSpatrick 
1846be691f3bSpatrick   Locker py_lock(this,
1847be691f3bSpatrick                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1848be691f3bSpatrick 
1849be691f3bSpatrick   lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
1850be691f3bSpatrick 
1851be691f3bSpatrick   bool ret_val = LLDBSwigPythonStopHookCallHandleStop(
1852be691f3bSpatrick       implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
1853be691f3bSpatrick   return ret_val;
1854be691f3bSpatrick }
1855be691f3bSpatrick 
1856061da546Spatrick StructuredData::ObjectSP
LoadPluginModule(const FileSpec & file_spec,lldb_private::Status & error)1857061da546Spatrick ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
1858061da546Spatrick                                               lldb_private::Status &error) {
1859061da546Spatrick   if (!FileSystem::Instance().Exists(file_spec)) {
1860061da546Spatrick     error.SetErrorString("no such file");
1861061da546Spatrick     return StructuredData::ObjectSP();
1862061da546Spatrick   }
1863061da546Spatrick 
1864061da546Spatrick   StructuredData::ObjectSP module_sp;
1865061da546Spatrick 
1866be691f3bSpatrick   LoadScriptOptions load_script_options =
1867be691f3bSpatrick       LoadScriptOptions().SetInitSession(true).SetSilent(false);
1868be691f3bSpatrick   if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1869be691f3bSpatrick                           error, &module_sp))
1870061da546Spatrick     return module_sp;
1871061da546Spatrick 
1872061da546Spatrick   return StructuredData::ObjectSP();
1873061da546Spatrick }
1874061da546Spatrick 
GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp,Target * target,const char * setting_name,lldb_private::Status & error)1875061da546Spatrick StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
1876061da546Spatrick     StructuredData::ObjectSP plugin_module_sp, Target *target,
1877061da546Spatrick     const char *setting_name, lldb_private::Status &error) {
1878061da546Spatrick   if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
1879061da546Spatrick     return StructuredData::DictionarySP();
1880061da546Spatrick   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
1881061da546Spatrick   if (!generic)
1882061da546Spatrick     return StructuredData::DictionarySP();
1883061da546Spatrick 
1884061da546Spatrick   Locker py_lock(this,
1885061da546Spatrick                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1886061da546Spatrick   TargetSP target_sp(target->shared_from_this());
1887061da546Spatrick 
1888061da546Spatrick   auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting(
1889061da546Spatrick       generic->GetValue(), setting_name, target_sp);
1890061da546Spatrick 
1891061da546Spatrick   if (!setting)
1892061da546Spatrick     return StructuredData::DictionarySP();
1893061da546Spatrick 
1894061da546Spatrick   PythonDictionary py_dict =
1895061da546Spatrick       unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
1896061da546Spatrick 
1897061da546Spatrick   if (!py_dict)
1898061da546Spatrick     return StructuredData::DictionarySP();
1899061da546Spatrick 
1900061da546Spatrick   return py_dict.CreateStructuredDictionary();
1901061da546Spatrick }
1902061da546Spatrick 
1903061da546Spatrick StructuredData::ObjectSP
CreateSyntheticScriptedProvider(const char * class_name,lldb::ValueObjectSP valobj)1904061da546Spatrick ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
1905061da546Spatrick     const char *class_name, lldb::ValueObjectSP valobj) {
1906061da546Spatrick   if (class_name == nullptr || class_name[0] == '\0')
1907061da546Spatrick     return StructuredData::ObjectSP();
1908061da546Spatrick 
1909061da546Spatrick   if (!valobj.get())
1910061da546Spatrick     return StructuredData::ObjectSP();
1911061da546Spatrick 
1912061da546Spatrick   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
1913061da546Spatrick   Target *target = exe_ctx.GetTargetPtr();
1914061da546Spatrick 
1915061da546Spatrick   if (!target)
1916061da546Spatrick     return StructuredData::ObjectSP();
1917061da546Spatrick 
1918061da546Spatrick   Debugger &debugger = target->GetDebugger();
1919061da546Spatrick   ScriptInterpreterPythonImpl *python_interpreter =
1920be691f3bSpatrick       GetPythonInterpreter(debugger);
1921061da546Spatrick 
1922be691f3bSpatrick   if (!python_interpreter)
1923061da546Spatrick     return StructuredData::ObjectSP();
1924061da546Spatrick 
1925061da546Spatrick   Locker py_lock(this,
1926061da546Spatrick                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1927*f6aab3d8Srobert   PythonObject ret_val = LLDBSwigPythonCreateSyntheticProvider(
1928061da546Spatrick       class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
1929061da546Spatrick 
1930*f6aab3d8Srobert   return StructuredData::ObjectSP(
1931*f6aab3d8Srobert       new StructuredPythonObject(std::move(ret_val)));
1932061da546Spatrick }
1933061da546Spatrick 
1934061da546Spatrick StructuredData::GenericSP
CreateScriptCommandObject(const char * class_name)1935061da546Spatrick ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
1936061da546Spatrick   DebuggerSP debugger_sp(m_debugger.shared_from_this());
1937061da546Spatrick 
1938061da546Spatrick   if (class_name == nullptr || class_name[0] == '\0')
1939061da546Spatrick     return StructuredData::GenericSP();
1940061da546Spatrick 
1941061da546Spatrick   if (!debugger_sp.get())
1942061da546Spatrick     return StructuredData::GenericSP();
1943061da546Spatrick 
1944061da546Spatrick   Locker py_lock(this,
1945061da546Spatrick                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1946*f6aab3d8Srobert   PythonObject ret_val = LLDBSwigPythonCreateCommandObject(
1947061da546Spatrick       class_name, m_dictionary_name.c_str(), debugger_sp);
1948061da546Spatrick 
1949*f6aab3d8Srobert   return StructuredData::GenericSP(
1950*f6aab3d8Srobert       new StructuredPythonObject(std::move(ret_val)));
1951061da546Spatrick }
1952061da546Spatrick 
GenerateTypeScriptFunction(const char * oneliner,std::string & output,const void * name_token)1953061da546Spatrick bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1954061da546Spatrick     const char *oneliner, std::string &output, const void *name_token) {
1955061da546Spatrick   StringList input;
1956061da546Spatrick   input.SplitIntoLines(oneliner, strlen(oneliner));
1957061da546Spatrick   return GenerateTypeScriptFunction(input, output, name_token);
1958061da546Spatrick }
1959061da546Spatrick 
GenerateTypeSynthClass(const char * oneliner,std::string & output,const void * name_token)1960061da546Spatrick bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1961061da546Spatrick     const char *oneliner, std::string &output, const void *name_token) {
1962061da546Spatrick   StringList input;
1963061da546Spatrick   input.SplitIntoLines(oneliner, strlen(oneliner));
1964061da546Spatrick   return GenerateTypeSynthClass(input, output, name_token);
1965061da546Spatrick }
1966061da546Spatrick 
GenerateBreakpointCommandCallbackData(StringList & user_input,std::string & output,bool has_extra_args)1967061da546Spatrick Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
1968061da546Spatrick     StringList &user_input, std::string &output,
1969061da546Spatrick     bool has_extra_args) {
1970061da546Spatrick   static uint32_t num_created_functions = 0;
1971061da546Spatrick   user_input.RemoveBlankLines();
1972061da546Spatrick   StreamString sstr;
1973061da546Spatrick   Status error;
1974061da546Spatrick   if (user_input.GetSize() == 0) {
1975061da546Spatrick     error.SetErrorString("No input data.");
1976061da546Spatrick     return error;
1977061da546Spatrick   }
1978061da546Spatrick 
1979061da546Spatrick   std::string auto_generated_function_name(GenerateUniqueName(
1980061da546Spatrick       "lldb_autogen_python_bp_callback_func_", num_created_functions));
1981061da546Spatrick   if (has_extra_args)
1982061da546Spatrick     sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
1983061da546Spatrick                 auto_generated_function_name.c_str());
1984061da546Spatrick   else
1985061da546Spatrick     sstr.Printf("def %s (frame, bp_loc, internal_dict):",
1986061da546Spatrick                 auto_generated_function_name.c_str());
1987061da546Spatrick 
1988061da546Spatrick   error = GenerateFunction(sstr.GetData(), user_input);
1989061da546Spatrick   if (!error.Success())
1990061da546Spatrick     return error;
1991061da546Spatrick 
1992061da546Spatrick   // Store the name of the auto-generated function to be called.
1993061da546Spatrick   output.assign(auto_generated_function_name);
1994061da546Spatrick   return error;
1995061da546Spatrick }
1996061da546Spatrick 
GenerateWatchpointCommandCallbackData(StringList & user_input,std::string & output)1997061da546Spatrick bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
1998061da546Spatrick     StringList &user_input, std::string &output) {
1999061da546Spatrick   static uint32_t num_created_functions = 0;
2000061da546Spatrick   user_input.RemoveBlankLines();
2001061da546Spatrick   StreamString sstr;
2002061da546Spatrick 
2003061da546Spatrick   if (user_input.GetSize() == 0)
2004061da546Spatrick     return false;
2005061da546Spatrick 
2006061da546Spatrick   std::string auto_generated_function_name(GenerateUniqueName(
2007061da546Spatrick       "lldb_autogen_python_wp_callback_func_", num_created_functions));
2008061da546Spatrick   sstr.Printf("def %s (frame, wp, internal_dict):",
2009061da546Spatrick               auto_generated_function_name.c_str());
2010061da546Spatrick 
2011061da546Spatrick   if (!GenerateFunction(sstr.GetData(), user_input).Success())
2012061da546Spatrick     return false;
2013061da546Spatrick 
2014061da546Spatrick   // Store the name of the auto-generated function to be called.
2015061da546Spatrick   output.assign(auto_generated_function_name);
2016061da546Spatrick   return true;
2017061da546Spatrick }
2018061da546Spatrick 
GetScriptedSummary(const char * python_function_name,lldb::ValueObjectSP valobj,StructuredData::ObjectSP & callee_wrapper_sp,const TypeSummaryOptions & options,std::string & retval)2019061da546Spatrick bool ScriptInterpreterPythonImpl::GetScriptedSummary(
2020061da546Spatrick     const char *python_function_name, lldb::ValueObjectSP valobj,
2021061da546Spatrick     StructuredData::ObjectSP &callee_wrapper_sp,
2022061da546Spatrick     const TypeSummaryOptions &options, std::string &retval) {
2023061da546Spatrick 
2024be691f3bSpatrick   LLDB_SCOPED_TIMER();
2025061da546Spatrick 
2026061da546Spatrick   if (!valobj.get()) {
2027061da546Spatrick     retval.assign("<no object>");
2028061da546Spatrick     return false;
2029061da546Spatrick   }
2030061da546Spatrick 
2031061da546Spatrick   void *old_callee = nullptr;
2032061da546Spatrick   StructuredData::Generic *generic = nullptr;
2033061da546Spatrick   if (callee_wrapper_sp) {
2034061da546Spatrick     generic = callee_wrapper_sp->GetAsGeneric();
2035061da546Spatrick     if (generic)
2036061da546Spatrick       old_callee = generic->GetValue();
2037061da546Spatrick   }
2038061da546Spatrick   void *new_callee = old_callee;
2039061da546Spatrick 
2040061da546Spatrick   bool ret_val;
2041061da546Spatrick   if (python_function_name && *python_function_name) {
2042061da546Spatrick     {
2043061da546Spatrick       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
2044061da546Spatrick                                Locker::NoSTDIN);
2045061da546Spatrick       {
2046061da546Spatrick         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
2047061da546Spatrick 
2048061da546Spatrick         static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
2049061da546Spatrick         Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
2050061da546Spatrick         ret_val = LLDBSwigPythonCallTypeScript(
2051061da546Spatrick             python_function_name, GetSessionDictionary().get(), valobj,
2052061da546Spatrick             &new_callee, options_sp, retval);
2053061da546Spatrick       }
2054061da546Spatrick     }
2055061da546Spatrick   } else {
2056061da546Spatrick     retval.assign("<no function name>");
2057061da546Spatrick     return false;
2058061da546Spatrick   }
2059061da546Spatrick 
2060*f6aab3d8Srobert   if (new_callee && old_callee != new_callee) {
2061*f6aab3d8Srobert     Locker py_lock(this,
2062*f6aab3d8Srobert                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2063*f6aab3d8Srobert     callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
2064*f6aab3d8Srobert         PythonObject(PyRefType::Borrowed, static_cast<PyObject *>(new_callee)));
2065*f6aab3d8Srobert   }
2066061da546Spatrick 
2067061da546Spatrick   return ret_val;
2068061da546Spatrick }
2069061da546Spatrick 
FormatterCallbackFunction(const char * python_function_name,TypeImplSP type_impl_sp)2070*f6aab3d8Srobert bool ScriptInterpreterPythonImpl::FormatterCallbackFunction(
2071*f6aab3d8Srobert     const char *python_function_name, TypeImplSP type_impl_sp) {
2072*f6aab3d8Srobert   Locker py_lock(this,
2073*f6aab3d8Srobert                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2074*f6aab3d8Srobert   return LLDBSwigPythonFormatterCallbackFunction(
2075*f6aab3d8Srobert       python_function_name, m_dictionary_name.c_str(), type_impl_sp);
2076*f6aab3d8Srobert }
2077*f6aab3d8Srobert 
BreakpointCallbackFunction(void * baton,StoppointCallbackContext * context,user_id_t break_id,user_id_t break_loc_id)2078061da546Spatrick bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
2079061da546Spatrick     void *baton, StoppointCallbackContext *context, user_id_t break_id,
2080061da546Spatrick     user_id_t break_loc_id) {
2081061da546Spatrick   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
2082061da546Spatrick   const char *python_function_name = bp_option_data->script_source.c_str();
2083061da546Spatrick 
2084061da546Spatrick   if (!context)
2085061da546Spatrick     return true;
2086061da546Spatrick 
2087061da546Spatrick   ExecutionContext exe_ctx(context->exe_ctx_ref);
2088061da546Spatrick   Target *target = exe_ctx.GetTargetPtr();
2089061da546Spatrick 
2090061da546Spatrick   if (!target)
2091061da546Spatrick     return true;
2092061da546Spatrick 
2093061da546Spatrick   Debugger &debugger = target->GetDebugger();
2094061da546Spatrick   ScriptInterpreterPythonImpl *python_interpreter =
2095be691f3bSpatrick       GetPythonInterpreter(debugger);
2096061da546Spatrick 
2097be691f3bSpatrick   if (!python_interpreter)
2098061da546Spatrick     return true;
2099061da546Spatrick 
2100061da546Spatrick   if (python_function_name && python_function_name[0]) {
2101061da546Spatrick     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2102061da546Spatrick     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2103061da546Spatrick     if (breakpoint_sp) {
2104061da546Spatrick       const BreakpointLocationSP bp_loc_sp(
2105061da546Spatrick           breakpoint_sp->FindLocationByID(break_loc_id));
2106061da546Spatrick 
2107061da546Spatrick       if (stop_frame_sp && bp_loc_sp) {
2108061da546Spatrick         bool ret_val = true;
2109061da546Spatrick         {
2110061da546Spatrick           Locker py_lock(python_interpreter, Locker::AcquireLock |
2111061da546Spatrick                                                  Locker::InitSession |
2112061da546Spatrick                                                  Locker::NoSTDIN);
2113061da546Spatrick           Expected<bool> maybe_ret_val =
2114061da546Spatrick               LLDBSwigPythonBreakpointCallbackFunction(
2115061da546Spatrick                   python_function_name,
2116061da546Spatrick                   python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2117*f6aab3d8Srobert                   bp_loc_sp, bp_option_data->m_extra_args);
2118061da546Spatrick 
2119061da546Spatrick           if (!maybe_ret_val) {
2120061da546Spatrick 
2121061da546Spatrick             llvm::handleAllErrors(
2122061da546Spatrick                 maybe_ret_val.takeError(),
2123061da546Spatrick                 [&](PythonException &E) {
2124061da546Spatrick                   debugger.GetErrorStream() << E.ReadBacktrace();
2125061da546Spatrick                 },
2126061da546Spatrick                 [&](const llvm::ErrorInfoBase &E) {
2127061da546Spatrick                   debugger.GetErrorStream() << E.message();
2128061da546Spatrick                 });
2129061da546Spatrick 
2130061da546Spatrick           } else {
2131061da546Spatrick             ret_val = maybe_ret_val.get();
2132061da546Spatrick           }
2133061da546Spatrick         }
2134061da546Spatrick         return ret_val;
2135061da546Spatrick       }
2136061da546Spatrick     }
2137061da546Spatrick   }
2138061da546Spatrick   // We currently always true so we stop in case anything goes wrong when
2139061da546Spatrick   // trying to call the script function
2140061da546Spatrick   return true;
2141061da546Spatrick }
2142061da546Spatrick 
WatchpointCallbackFunction(void * baton,StoppointCallbackContext * context,user_id_t watch_id)2143061da546Spatrick bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
2144061da546Spatrick     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2145061da546Spatrick   WatchpointOptions::CommandData *wp_option_data =
2146061da546Spatrick       (WatchpointOptions::CommandData *)baton;
2147061da546Spatrick   const char *python_function_name = wp_option_data->script_source.c_str();
2148061da546Spatrick 
2149061da546Spatrick   if (!context)
2150061da546Spatrick     return true;
2151061da546Spatrick 
2152061da546Spatrick   ExecutionContext exe_ctx(context->exe_ctx_ref);
2153061da546Spatrick   Target *target = exe_ctx.GetTargetPtr();
2154061da546Spatrick 
2155061da546Spatrick   if (!target)
2156061da546Spatrick     return true;
2157061da546Spatrick 
2158061da546Spatrick   Debugger &debugger = target->GetDebugger();
2159061da546Spatrick   ScriptInterpreterPythonImpl *python_interpreter =
2160be691f3bSpatrick       GetPythonInterpreter(debugger);
2161061da546Spatrick 
2162be691f3bSpatrick   if (!python_interpreter)
2163061da546Spatrick     return true;
2164061da546Spatrick 
2165061da546Spatrick   if (python_function_name && python_function_name[0]) {
2166061da546Spatrick     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2167061da546Spatrick     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2168061da546Spatrick     if (wp_sp) {
2169061da546Spatrick       if (stop_frame_sp && wp_sp) {
2170061da546Spatrick         bool ret_val = true;
2171061da546Spatrick         {
2172061da546Spatrick           Locker py_lock(python_interpreter, Locker::AcquireLock |
2173061da546Spatrick                                                  Locker::InitSession |
2174061da546Spatrick                                                  Locker::NoSTDIN);
2175061da546Spatrick           ret_val = LLDBSwigPythonWatchpointCallbackFunction(
2176061da546Spatrick               python_function_name,
2177061da546Spatrick               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2178061da546Spatrick               wp_sp);
2179061da546Spatrick         }
2180061da546Spatrick         return ret_val;
2181061da546Spatrick       }
2182061da546Spatrick     }
2183061da546Spatrick   }
2184061da546Spatrick   // We currently always true so we stop in case anything goes wrong when
2185061da546Spatrick   // trying to call the script function
2186061da546Spatrick   return true;
2187061da546Spatrick }
2188061da546Spatrick 
CalculateNumChildren(const StructuredData::ObjectSP & implementor_sp,uint32_t max)2189061da546Spatrick size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2190061da546Spatrick     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
2191061da546Spatrick   if (!implementor_sp)
2192061da546Spatrick     return 0;
2193061da546Spatrick   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2194061da546Spatrick   if (!generic)
2195061da546Spatrick     return 0;
2196*f6aab3d8Srobert   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2197061da546Spatrick   if (!implementor)
2198061da546Spatrick     return 0;
2199061da546Spatrick 
2200061da546Spatrick   size_t ret_val = 0;
2201061da546Spatrick 
2202061da546Spatrick   {
2203061da546Spatrick     Locker py_lock(this,
2204061da546Spatrick                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2205061da546Spatrick     ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max);
2206061da546Spatrick   }
2207061da546Spatrick 
2208061da546Spatrick   return ret_val;
2209061da546Spatrick }
2210061da546Spatrick 
GetChildAtIndex(const StructuredData::ObjectSP & implementor_sp,uint32_t idx)2211061da546Spatrick lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
2212061da546Spatrick     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
2213061da546Spatrick   if (!implementor_sp)
2214061da546Spatrick     return lldb::ValueObjectSP();
2215061da546Spatrick 
2216061da546Spatrick   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2217061da546Spatrick   if (!generic)
2218061da546Spatrick     return lldb::ValueObjectSP();
2219*f6aab3d8Srobert   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2220061da546Spatrick   if (!implementor)
2221061da546Spatrick     return lldb::ValueObjectSP();
2222061da546Spatrick 
2223061da546Spatrick   lldb::ValueObjectSP ret_val;
2224061da546Spatrick   {
2225061da546Spatrick     Locker py_lock(this,
2226061da546Spatrick                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2227*f6aab3d8Srobert     PyObject *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx);
2228061da546Spatrick     if (child_ptr != nullptr && child_ptr != Py_None) {
2229061da546Spatrick       lldb::SBValue *sb_value_ptr =
2230061da546Spatrick           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2231061da546Spatrick       if (sb_value_ptr == nullptr)
2232061da546Spatrick         Py_XDECREF(child_ptr);
2233061da546Spatrick       else
2234061da546Spatrick         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2235061da546Spatrick     } else {
2236061da546Spatrick       Py_XDECREF(child_ptr);
2237061da546Spatrick     }
2238061da546Spatrick   }
2239061da546Spatrick 
2240061da546Spatrick   return ret_val;
2241061da546Spatrick }
2242061da546Spatrick 
GetIndexOfChildWithName(const StructuredData::ObjectSP & implementor_sp,const char * child_name)2243061da546Spatrick int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2244061da546Spatrick     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
2245061da546Spatrick   if (!implementor_sp)
2246061da546Spatrick     return UINT32_MAX;
2247061da546Spatrick 
2248061da546Spatrick   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2249061da546Spatrick   if (!generic)
2250061da546Spatrick     return UINT32_MAX;
2251*f6aab3d8Srobert   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2252061da546Spatrick   if (!implementor)
2253061da546Spatrick     return UINT32_MAX;
2254061da546Spatrick 
2255061da546Spatrick   int ret_val = UINT32_MAX;
2256061da546Spatrick 
2257061da546Spatrick   {
2258061da546Spatrick     Locker py_lock(this,
2259061da546Spatrick                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2260061da546Spatrick     ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
2261061da546Spatrick   }
2262061da546Spatrick 
2263061da546Spatrick   return ret_val;
2264061da546Spatrick }
2265061da546Spatrick 
UpdateSynthProviderInstance(const StructuredData::ObjectSP & implementor_sp)2266061da546Spatrick bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2267061da546Spatrick     const StructuredData::ObjectSP &implementor_sp) {
2268061da546Spatrick   bool ret_val = false;
2269061da546Spatrick 
2270061da546Spatrick   if (!implementor_sp)
2271061da546Spatrick     return ret_val;
2272061da546Spatrick 
2273061da546Spatrick   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2274061da546Spatrick   if (!generic)
2275061da546Spatrick     return ret_val;
2276*f6aab3d8Srobert   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2277061da546Spatrick   if (!implementor)
2278061da546Spatrick     return ret_val;
2279061da546Spatrick 
2280061da546Spatrick   {
2281061da546Spatrick     Locker py_lock(this,
2282061da546Spatrick                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2283061da546Spatrick     ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor);
2284061da546Spatrick   }
2285061da546Spatrick 
2286061da546Spatrick   return ret_val;
2287061da546Spatrick }
2288061da546Spatrick 
MightHaveChildrenSynthProviderInstance(const StructuredData::ObjectSP & implementor_sp)2289061da546Spatrick bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2290061da546Spatrick     const StructuredData::ObjectSP &implementor_sp) {
2291061da546Spatrick   bool ret_val = false;
2292061da546Spatrick 
2293061da546Spatrick   if (!implementor_sp)
2294061da546Spatrick     return ret_val;
2295061da546Spatrick 
2296061da546Spatrick   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2297061da546Spatrick   if (!generic)
2298061da546Spatrick     return ret_val;
2299*f6aab3d8Srobert   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2300061da546Spatrick   if (!implementor)
2301061da546Spatrick     return ret_val;
2302061da546Spatrick 
2303061da546Spatrick   {
2304061da546Spatrick     Locker py_lock(this,
2305061da546Spatrick                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2306061da546Spatrick     ret_val =
2307061da546Spatrick         LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor);
2308061da546Spatrick   }
2309061da546Spatrick 
2310061da546Spatrick   return ret_val;
2311061da546Spatrick }
2312061da546Spatrick 
GetSyntheticValue(const StructuredData::ObjectSP & implementor_sp)2313061da546Spatrick lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
2314061da546Spatrick     const StructuredData::ObjectSP &implementor_sp) {
2315061da546Spatrick   lldb::ValueObjectSP ret_val(nullptr);
2316061da546Spatrick 
2317061da546Spatrick   if (!implementor_sp)
2318061da546Spatrick     return ret_val;
2319061da546Spatrick 
2320061da546Spatrick   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2321061da546Spatrick   if (!generic)
2322061da546Spatrick     return ret_val;
2323*f6aab3d8Srobert   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2324061da546Spatrick   if (!implementor)
2325061da546Spatrick     return ret_val;
2326061da546Spatrick 
2327061da546Spatrick   {
2328061da546Spatrick     Locker py_lock(this,
2329061da546Spatrick                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2330*f6aab3d8Srobert     PyObject *child_ptr =
2331*f6aab3d8Srobert         LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2332061da546Spatrick     if (child_ptr != nullptr && child_ptr != Py_None) {
2333061da546Spatrick       lldb::SBValue *sb_value_ptr =
2334061da546Spatrick           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2335061da546Spatrick       if (sb_value_ptr == nullptr)
2336061da546Spatrick         Py_XDECREF(child_ptr);
2337061da546Spatrick       else
2338061da546Spatrick         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2339061da546Spatrick     } else {
2340061da546Spatrick       Py_XDECREF(child_ptr);
2341061da546Spatrick     }
2342061da546Spatrick   }
2343061da546Spatrick 
2344061da546Spatrick   return ret_val;
2345061da546Spatrick }
2346061da546Spatrick 
GetSyntheticTypeName(const StructuredData::ObjectSP & implementor_sp)2347061da546Spatrick ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2348061da546Spatrick     const StructuredData::ObjectSP &implementor_sp) {
2349061da546Spatrick   Locker py_lock(this,
2350061da546Spatrick                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2351061da546Spatrick 
2352*f6aab3d8Srobert   if (!implementor_sp)
2353*f6aab3d8Srobert     return {};
2354*f6aab3d8Srobert 
2355*f6aab3d8Srobert   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2356*f6aab3d8Srobert   if (!generic)
2357*f6aab3d8Srobert     return {};
2358*f6aab3d8Srobert 
2359*f6aab3d8Srobert   PythonObject implementor(PyRefType::Borrowed,
2360*f6aab3d8Srobert                            (PyObject *)generic->GetValue());
2361*f6aab3d8Srobert   if (!implementor.IsAllocated())
2362*f6aab3d8Srobert     return {};
2363*f6aab3d8Srobert 
2364*f6aab3d8Srobert   llvm::Expected<PythonObject> expected_py_return =
2365*f6aab3d8Srobert       implementor.CallMethod("get_type_name");
2366*f6aab3d8Srobert 
2367*f6aab3d8Srobert   if (!expected_py_return) {
2368*f6aab3d8Srobert     llvm::consumeError(expected_py_return.takeError());
2369*f6aab3d8Srobert     return {};
2370*f6aab3d8Srobert   }
2371*f6aab3d8Srobert 
2372*f6aab3d8Srobert   PythonObject py_return = std::move(expected_py_return.get());
2373061da546Spatrick 
2374061da546Spatrick   ConstString ret_val;
2375061da546Spatrick   bool got_string = false;
2376061da546Spatrick   std::string buffer;
2377061da546Spatrick 
2378061da546Spatrick   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2379061da546Spatrick     PythonString py_string(PyRefType::Borrowed, py_return.get());
2380061da546Spatrick     llvm::StringRef return_data(py_string.GetString());
2381061da546Spatrick     if (!return_data.empty()) {
2382061da546Spatrick       buffer.assign(return_data.data(), return_data.size());
2383061da546Spatrick       got_string = true;
2384061da546Spatrick     }
2385061da546Spatrick   }
2386061da546Spatrick 
2387061da546Spatrick   if (got_string)
2388061da546Spatrick     ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
2389061da546Spatrick 
2390061da546Spatrick   return ret_val;
2391061da546Spatrick }
2392061da546Spatrick 
RunScriptFormatKeyword(const char * impl_function,Process * process,std::string & output,Status & error)2393061da546Spatrick bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2394061da546Spatrick     const char *impl_function, Process *process, std::string &output,
2395061da546Spatrick     Status &error) {
2396061da546Spatrick   bool ret_val;
2397061da546Spatrick   if (!process) {
2398061da546Spatrick     error.SetErrorString("no process");
2399061da546Spatrick     return false;
2400061da546Spatrick   }
2401061da546Spatrick   if (!impl_function || !impl_function[0]) {
2402061da546Spatrick     error.SetErrorString("no function to execute");
2403061da546Spatrick     return false;
2404061da546Spatrick   }
2405061da546Spatrick 
2406061da546Spatrick   {
2407061da546Spatrick     Locker py_lock(this,
2408061da546Spatrick                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2409061da546Spatrick     ret_val = LLDBSWIGPythonRunScriptKeywordProcess(
2410*f6aab3d8Srobert         impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
2411*f6aab3d8Srobert         output);
2412061da546Spatrick     if (!ret_val)
2413061da546Spatrick       error.SetErrorString("python script evaluation failed");
2414061da546Spatrick   }
2415061da546Spatrick   return ret_val;
2416061da546Spatrick }
2417061da546Spatrick 
RunScriptFormatKeyword(const char * impl_function,Thread * thread,std::string & output,Status & error)2418061da546Spatrick bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2419061da546Spatrick     const char *impl_function, Thread *thread, std::string &output,
2420061da546Spatrick     Status &error) {
2421061da546Spatrick   if (!thread) {
2422061da546Spatrick     error.SetErrorString("no thread");
2423061da546Spatrick     return false;
2424061da546Spatrick   }
2425061da546Spatrick   if (!impl_function || !impl_function[0]) {
2426061da546Spatrick     error.SetErrorString("no function to execute");
2427061da546Spatrick     return false;
2428061da546Spatrick   }
2429061da546Spatrick 
2430061da546Spatrick   Locker py_lock(this,
2431061da546Spatrick                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2432*f6aab3d8Srobert   if (std::optional<std::string> result = LLDBSWIGPythonRunScriptKeywordThread(
2433*f6aab3d8Srobert           impl_function, m_dictionary_name.c_str(),
2434*f6aab3d8Srobert           thread->shared_from_this())) {
2435*f6aab3d8Srobert     output = std::move(*result);
2436*f6aab3d8Srobert     return true;
2437061da546Spatrick   }
2438*f6aab3d8Srobert   error.SetErrorString("python script evaluation failed");
2439*f6aab3d8Srobert   return false;
2440061da546Spatrick }
2441061da546Spatrick 
RunScriptFormatKeyword(const char * impl_function,Target * target,std::string & output,Status & error)2442061da546Spatrick bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2443061da546Spatrick     const char *impl_function, Target *target, std::string &output,
2444061da546Spatrick     Status &error) {
2445061da546Spatrick   bool ret_val;
2446061da546Spatrick   if (!target) {
2447061da546Spatrick     error.SetErrorString("no thread");
2448061da546Spatrick     return false;
2449061da546Spatrick   }
2450061da546Spatrick   if (!impl_function || !impl_function[0]) {
2451061da546Spatrick     error.SetErrorString("no function to execute");
2452061da546Spatrick     return false;
2453061da546Spatrick   }
2454061da546Spatrick 
2455061da546Spatrick   {
2456061da546Spatrick     TargetSP target_sp(target->shared_from_this());
2457061da546Spatrick     Locker py_lock(this,
2458061da546Spatrick                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2459061da546Spatrick     ret_val = LLDBSWIGPythonRunScriptKeywordTarget(
2460061da546Spatrick         impl_function, m_dictionary_name.c_str(), target_sp, output);
2461061da546Spatrick     if (!ret_val)
2462061da546Spatrick       error.SetErrorString("python script evaluation failed");
2463061da546Spatrick   }
2464061da546Spatrick   return ret_val;
2465061da546Spatrick }
2466061da546Spatrick 
RunScriptFormatKeyword(const char * impl_function,StackFrame * frame,std::string & output,Status & error)2467061da546Spatrick bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2468061da546Spatrick     const char *impl_function, StackFrame *frame, std::string &output,
2469061da546Spatrick     Status &error) {
2470061da546Spatrick   if (!frame) {
2471061da546Spatrick     error.SetErrorString("no frame");
2472061da546Spatrick     return false;
2473061da546Spatrick   }
2474061da546Spatrick   if (!impl_function || !impl_function[0]) {
2475061da546Spatrick     error.SetErrorString("no function to execute");
2476061da546Spatrick     return false;
2477061da546Spatrick   }
2478061da546Spatrick 
2479061da546Spatrick   Locker py_lock(this,
2480061da546Spatrick                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2481*f6aab3d8Srobert   if (std::optional<std::string> result = LLDBSWIGPythonRunScriptKeywordFrame(
2482*f6aab3d8Srobert           impl_function, m_dictionary_name.c_str(),
2483*f6aab3d8Srobert           frame->shared_from_this())) {
2484*f6aab3d8Srobert     output = std::move(*result);
2485*f6aab3d8Srobert     return true;
2486061da546Spatrick   }
2487*f6aab3d8Srobert   error.SetErrorString("python script evaluation failed");
2488*f6aab3d8Srobert   return false;
2489061da546Spatrick }
2490061da546Spatrick 
RunScriptFormatKeyword(const char * impl_function,ValueObject * value,std::string & output,Status & error)2491061da546Spatrick bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2492061da546Spatrick     const char *impl_function, ValueObject *value, std::string &output,
2493061da546Spatrick     Status &error) {
2494061da546Spatrick   bool ret_val;
2495061da546Spatrick   if (!value) {
2496061da546Spatrick     error.SetErrorString("no value");
2497061da546Spatrick     return false;
2498061da546Spatrick   }
2499061da546Spatrick   if (!impl_function || !impl_function[0]) {
2500061da546Spatrick     error.SetErrorString("no function to execute");
2501061da546Spatrick     return false;
2502061da546Spatrick   }
2503061da546Spatrick 
2504061da546Spatrick   {
2505061da546Spatrick     Locker py_lock(this,
2506061da546Spatrick                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2507061da546Spatrick     ret_val = LLDBSWIGPythonRunScriptKeywordValue(
2508*f6aab3d8Srobert         impl_function, m_dictionary_name.c_str(), value->GetSP(), output);
2509061da546Spatrick     if (!ret_val)
2510061da546Spatrick       error.SetErrorString("python script evaluation failed");
2511061da546Spatrick   }
2512061da546Spatrick   return ret_val;
2513061da546Spatrick }
2514061da546Spatrick 
replace_all(std::string & str,const std::string & oldStr,const std::string & newStr)2515061da546Spatrick uint64_t replace_all(std::string &str, const std::string &oldStr,
2516061da546Spatrick                      const std::string &newStr) {
2517061da546Spatrick   size_t pos = 0;
2518061da546Spatrick   uint64_t matches = 0;
2519061da546Spatrick   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2520061da546Spatrick     matches++;
2521061da546Spatrick     str.replace(pos, oldStr.length(), newStr);
2522061da546Spatrick     pos += newStr.length();
2523061da546Spatrick   }
2524061da546Spatrick   return matches;
2525061da546Spatrick }
2526061da546Spatrick 
LoadScriptingModule(const char * pathname,const LoadScriptOptions & options,lldb_private::Status & error,StructuredData::ObjectSP * module_sp,FileSpec extra_search_dir)2527061da546Spatrick bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2528be691f3bSpatrick     const char *pathname, const LoadScriptOptions &options,
2529be691f3bSpatrick     lldb_private::Status &error, StructuredData::ObjectSP *module_sp,
2530be691f3bSpatrick     FileSpec extra_search_dir) {
2531be691f3bSpatrick   namespace fs = llvm::sys::fs;
2532be691f3bSpatrick   namespace path = llvm::sys::path;
2533be691f3bSpatrick 
2534be691f3bSpatrick   ExecuteScriptOptions exc_options = ExecuteScriptOptions()
2535be691f3bSpatrick                                          .SetEnableIO(!options.GetSilent())
2536be691f3bSpatrick                                          .SetSetLLDBGlobals(false);
2537be691f3bSpatrick 
2538061da546Spatrick   if (!pathname || !pathname[0]) {
2539*f6aab3d8Srobert     error.SetErrorString("empty path");
2540061da546Spatrick     return false;
2541061da546Spatrick   }
2542061da546Spatrick 
2543be691f3bSpatrick   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2544be691f3bSpatrick       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2545be691f3bSpatrick           exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2546be691f3bSpatrick 
2547be691f3bSpatrick   if (!io_redirect_or_error) {
2548be691f3bSpatrick     error = io_redirect_or_error.takeError();
2549be691f3bSpatrick     return false;
2550be691f3bSpatrick   }
2551be691f3bSpatrick 
2552be691f3bSpatrick   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
2553061da546Spatrick 
2554061da546Spatrick   // Before executing Python code, lock the GIL.
2555061da546Spatrick   Locker py_lock(this,
2556061da546Spatrick                  Locker::AcquireLock |
2557be691f3bSpatrick                      (options.GetInitSession() ? Locker::InitSession : 0) |
2558061da546Spatrick                      Locker::NoSTDIN,
2559061da546Spatrick                  Locker::FreeAcquiredLock |
2560be691f3bSpatrick                      (options.GetInitSession() ? Locker::TearDownSession : 0),
2561be691f3bSpatrick                  io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2562be691f3bSpatrick                  io_redirect.GetErrorFile());
2563be691f3bSpatrick 
2564be691f3bSpatrick   auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2565be691f3bSpatrick     if (directory.empty()) {
2566be691f3bSpatrick       return llvm::make_error<llvm::StringError>(
2567be691f3bSpatrick           "invalid directory name", llvm::inconvertibleErrorCode());
2568be691f3bSpatrick     }
2569be691f3bSpatrick 
2570be691f3bSpatrick     replace_all(directory, "\\", "\\\\");
2571be691f3bSpatrick     replace_all(directory, "'", "\\'");
2572be691f3bSpatrick 
2573be691f3bSpatrick     // Make sure that Python has "directory" in the search path.
2574be691f3bSpatrick     StreamString command_stream;
2575be691f3bSpatrick     command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
2576be691f3bSpatrick                           "sys.path.insert(1,'%s');\n\n",
2577be691f3bSpatrick                           directory.c_str(), directory.c_str());
2578be691f3bSpatrick     bool syspath_retval =
2579be691f3bSpatrick         ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
2580be691f3bSpatrick     if (!syspath_retval) {
2581be691f3bSpatrick       return llvm::make_error<llvm::StringError>(
2582be691f3bSpatrick           "Python sys.path handling failed", llvm::inconvertibleErrorCode());
2583be691f3bSpatrick     }
2584be691f3bSpatrick 
2585be691f3bSpatrick     return llvm::Error::success();
2586be691f3bSpatrick   };
2587be691f3bSpatrick 
2588be691f3bSpatrick   std::string module_name(pathname);
2589be691f3bSpatrick   bool possible_package = false;
2590be691f3bSpatrick 
2591be691f3bSpatrick   if (extra_search_dir) {
2592be691f3bSpatrick     if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2593be691f3bSpatrick       error = std::move(e);
2594be691f3bSpatrick       return false;
2595be691f3bSpatrick     }
2596be691f3bSpatrick   } else {
2597be691f3bSpatrick     FileSpec module_file(pathname);
2598be691f3bSpatrick     FileSystem::Instance().Resolve(module_file);
2599be691f3bSpatrick 
2600061da546Spatrick     fs::file_status st;
2601be691f3bSpatrick     std::error_code ec = status(module_file.GetPath(), st);
2602061da546Spatrick 
2603061da546Spatrick     if (ec || st.type() == fs::file_type::status_error ||
2604061da546Spatrick         st.type() == fs::file_type::type_unknown ||
2605061da546Spatrick         st.type() == fs::file_type::file_not_found) {
2606061da546Spatrick       // if not a valid file of any sort, check if it might be a filename still
2607061da546Spatrick       // dot can't be used but / and \ can, and if either is found, reject
2608061da546Spatrick       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2609*f6aab3d8Srobert         error.SetErrorStringWithFormatv("invalid pathname '{0}'", pathname);
2610061da546Spatrick         return false;
2611061da546Spatrick       }
2612be691f3bSpatrick       // Not a filename, probably a package of some sort, let it go through.
2613be691f3bSpatrick       possible_package = true;
2614061da546Spatrick     } else if (is_directory(st) || is_regular_file(st)) {
2615be691f3bSpatrick       if (module_file.GetDirectory().IsEmpty()) {
2616*f6aab3d8Srobert         error.SetErrorStringWithFormatv("invalid directory name '{0}'", pathname);
2617061da546Spatrick         return false;
2618061da546Spatrick       }
2619be691f3bSpatrick       if (llvm::Error e =
2620be691f3bSpatrick               ExtendSysPath(module_file.GetDirectory().GetCString())) {
2621be691f3bSpatrick         error = std::move(e);
2622061da546Spatrick         return false;
2623061da546Spatrick       }
2624be691f3bSpatrick       module_name = module_file.GetFilename().GetCString();
2625061da546Spatrick     } else {
2626061da546Spatrick       error.SetErrorString("no known way to import this module specification");
2627061da546Spatrick       return false;
2628061da546Spatrick     }
2629be691f3bSpatrick   }
2630061da546Spatrick 
2631be691f3bSpatrick   // Strip .py or .pyc extension
2632be691f3bSpatrick   llvm::StringRef extension = llvm::sys::path::extension(module_name);
2633be691f3bSpatrick   if (!extension.empty()) {
2634be691f3bSpatrick     if (extension == ".py")
2635be691f3bSpatrick       module_name.resize(module_name.length() - 3);
2636be691f3bSpatrick     else if (extension == ".pyc")
2637be691f3bSpatrick       module_name.resize(module_name.length() - 4);
2638be691f3bSpatrick   }
2639be691f3bSpatrick 
2640be691f3bSpatrick   if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2641be691f3bSpatrick     error.SetErrorStringWithFormat(
2642be691f3bSpatrick         "Python does not allow dots in module names: %s", module_name.c_str());
2643be691f3bSpatrick     return false;
2644be691f3bSpatrick   }
2645be691f3bSpatrick 
2646be691f3bSpatrick   if (module_name.find('-') != llvm::StringRef::npos) {
2647be691f3bSpatrick     error.SetErrorStringWithFormat(
2648be691f3bSpatrick         "Python discourages dashes in module names: %s", module_name.c_str());
2649be691f3bSpatrick     return false;
2650be691f3bSpatrick   }
2651be691f3bSpatrick 
2652be691f3bSpatrick   // Check if the module is already imported.
2653be691f3bSpatrick   StreamString command_stream;
2654061da546Spatrick   command_stream.Clear();
2655be691f3bSpatrick   command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
2656061da546Spatrick   bool does_contain = false;
2657be691f3bSpatrick   // This call will succeed if the module was ever imported in any Debugger in
2658be691f3bSpatrick   // the lifetime of the process in which this LLDB framework is living.
2659be691f3bSpatrick   const bool does_contain_executed = ExecuteOneLineWithReturn(
2660061da546Spatrick       command_stream.GetData(),
2661be691f3bSpatrick       ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options);
2662061da546Spatrick 
2663be691f3bSpatrick   const bool was_imported_globally = does_contain_executed && does_contain;
2664be691f3bSpatrick   const bool was_imported_locally =
2665be691f3bSpatrick       GetSessionDictionary()
2666be691f3bSpatrick           .GetItemForKey(PythonString(module_name))
2667be691f3bSpatrick           .IsAllocated();
2668061da546Spatrick 
2669061da546Spatrick   // now actually do the import
2670061da546Spatrick   command_stream.Clear();
2671061da546Spatrick 
2672be691f3bSpatrick   if (was_imported_globally || was_imported_locally) {
2673061da546Spatrick     if (!was_imported_locally)
2674be691f3bSpatrick       command_stream.Printf("import %s ; reload_module(%s)",
2675be691f3bSpatrick                             module_name.c_str(), module_name.c_str());
2676061da546Spatrick     else
2677be691f3bSpatrick       command_stream.Printf("reload_module(%s)", module_name.c_str());
2678061da546Spatrick   } else
2679be691f3bSpatrick     command_stream.Printf("import %s", module_name.c_str());
2680061da546Spatrick 
2681be691f3bSpatrick   error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
2682061da546Spatrick   if (error.Fail())
2683061da546Spatrick     return false;
2684061da546Spatrick 
2685061da546Spatrick   // if we are here, everything worked
2686061da546Spatrick   // call __lldb_init_module(debugger,dict)
2687be691f3bSpatrick   if (!LLDBSwigPythonCallModuleInit(module_name.c_str(),
2688*f6aab3d8Srobert                                     m_dictionary_name.c_str(),
2689*f6aab3d8Srobert                                     m_debugger.shared_from_this())) {
2690061da546Spatrick     error.SetErrorString("calling __lldb_init_module failed");
2691061da546Spatrick     return false;
2692061da546Spatrick   }
2693061da546Spatrick 
2694061da546Spatrick   if (module_sp) {
2695061da546Spatrick     // everything went just great, now set the module object
2696061da546Spatrick     command_stream.Clear();
2697be691f3bSpatrick     command_stream.Printf("%s", module_name.c_str());
2698061da546Spatrick     void *module_pyobj = nullptr;
2699061da546Spatrick     if (ExecuteOneLineWithReturn(
2700061da546Spatrick             command_stream.GetData(),
2701be691f3bSpatrick             ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2702be691f3bSpatrick             exc_options) &&
2703061da546Spatrick         module_pyobj)
2704*f6aab3d8Srobert       *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2705*f6aab3d8Srobert           PyRefType::Owned, static_cast<PyObject *>(module_pyobj)));
2706061da546Spatrick   }
2707061da546Spatrick 
2708061da546Spatrick   return true;
2709061da546Spatrick }
2710061da546Spatrick 
IsReservedWord(const char * word)2711061da546Spatrick bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
2712061da546Spatrick   if (!word || !word[0])
2713061da546Spatrick     return false;
2714061da546Spatrick 
2715061da546Spatrick   llvm::StringRef word_sr(word);
2716061da546Spatrick 
2717061da546Spatrick   // filter out a few characters that would just confuse us and that are
2718061da546Spatrick   // clearly not keyword material anyway
2719061da546Spatrick   if (word_sr.find('"') != llvm::StringRef::npos ||
2720061da546Spatrick       word_sr.find('\'') != llvm::StringRef::npos)
2721061da546Spatrick     return false;
2722061da546Spatrick 
2723061da546Spatrick   StreamString command_stream;
2724061da546Spatrick   command_stream.Printf("keyword.iskeyword('%s')", word);
2725061da546Spatrick   bool result;
2726061da546Spatrick   ExecuteScriptOptions options;
2727061da546Spatrick   options.SetEnableIO(false);
2728061da546Spatrick   options.SetMaskoutErrors(true);
2729061da546Spatrick   options.SetSetLLDBGlobals(false);
2730061da546Spatrick   if (ExecuteOneLineWithReturn(command_stream.GetData(),
2731061da546Spatrick                                ScriptInterpreter::eScriptReturnTypeBool,
2732061da546Spatrick                                &result, options))
2733061da546Spatrick     return result;
2734061da546Spatrick   return false;
2735061da546Spatrick }
2736061da546Spatrick 
SynchronicityHandler(lldb::DebuggerSP debugger_sp,ScriptedCommandSynchronicity synchro)2737061da546Spatrick ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2738061da546Spatrick     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2739061da546Spatrick     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2740061da546Spatrick       m_old_asynch(debugger_sp->GetAsyncExecution()) {
2741061da546Spatrick   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2742061da546Spatrick     m_debugger_sp->SetAsyncExecution(false);
2743061da546Spatrick   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2744061da546Spatrick     m_debugger_sp->SetAsyncExecution(true);
2745061da546Spatrick }
2746061da546Spatrick 
~SynchronicityHandler()2747061da546Spatrick ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
2748061da546Spatrick   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2749061da546Spatrick     m_debugger_sp->SetAsyncExecution(m_old_asynch);
2750061da546Spatrick }
2751061da546Spatrick 
RunScriptBasedCommand(const char * impl_function,llvm::StringRef args,ScriptedCommandSynchronicity synchronicity,lldb_private::CommandReturnObject & cmd_retobj,Status & error,const lldb_private::ExecutionContext & exe_ctx)2752061da546Spatrick bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2753061da546Spatrick     const char *impl_function, llvm::StringRef args,
2754061da546Spatrick     ScriptedCommandSynchronicity synchronicity,
2755061da546Spatrick     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2756061da546Spatrick     const lldb_private::ExecutionContext &exe_ctx) {
2757061da546Spatrick   if (!impl_function) {
2758061da546Spatrick     error.SetErrorString("no function to execute");
2759061da546Spatrick     return false;
2760061da546Spatrick   }
2761061da546Spatrick 
2762061da546Spatrick   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2763061da546Spatrick   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2764061da546Spatrick 
2765061da546Spatrick   if (!debugger_sp.get()) {
2766061da546Spatrick     error.SetErrorString("invalid Debugger pointer");
2767061da546Spatrick     return false;
2768061da546Spatrick   }
2769061da546Spatrick 
2770061da546Spatrick   bool ret_val = false;
2771061da546Spatrick 
2772061da546Spatrick   std::string err_msg;
2773061da546Spatrick 
2774061da546Spatrick   {
2775061da546Spatrick     Locker py_lock(this,
2776061da546Spatrick                    Locker::AcquireLock | Locker::InitSession |
2777061da546Spatrick                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2778061da546Spatrick                    Locker::FreeLock | Locker::TearDownSession);
2779061da546Spatrick 
2780061da546Spatrick     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2781061da546Spatrick 
2782061da546Spatrick     std::string args_str = args.str();
2783061da546Spatrick     ret_val = LLDBSwigPythonCallCommand(
2784061da546Spatrick         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2785061da546Spatrick         cmd_retobj, exe_ctx_ref_sp);
2786061da546Spatrick   }
2787061da546Spatrick 
2788061da546Spatrick   if (!ret_val)
2789061da546Spatrick     error.SetErrorString("unable to execute script function");
2790*f6aab3d8Srobert   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2791*f6aab3d8Srobert     return false;
2792061da546Spatrick 
2793*f6aab3d8Srobert   error.Clear();
2794061da546Spatrick   return ret_val;
2795061da546Spatrick }
2796061da546Spatrick 
RunScriptBasedCommand(StructuredData::GenericSP impl_obj_sp,llvm::StringRef args,ScriptedCommandSynchronicity synchronicity,lldb_private::CommandReturnObject & cmd_retobj,Status & error,const lldb_private::ExecutionContext & exe_ctx)2797061da546Spatrick bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2798061da546Spatrick     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
2799061da546Spatrick     ScriptedCommandSynchronicity synchronicity,
2800061da546Spatrick     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2801061da546Spatrick     const lldb_private::ExecutionContext &exe_ctx) {
2802061da546Spatrick   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2803061da546Spatrick     error.SetErrorString("no function to execute");
2804061da546Spatrick     return false;
2805061da546Spatrick   }
2806061da546Spatrick 
2807061da546Spatrick   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2808061da546Spatrick   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2809061da546Spatrick 
2810061da546Spatrick   if (!debugger_sp.get()) {
2811061da546Spatrick     error.SetErrorString("invalid Debugger pointer");
2812061da546Spatrick     return false;
2813061da546Spatrick   }
2814061da546Spatrick 
2815061da546Spatrick   bool ret_val = false;
2816061da546Spatrick 
2817061da546Spatrick   std::string err_msg;
2818061da546Spatrick 
2819061da546Spatrick   {
2820061da546Spatrick     Locker py_lock(this,
2821061da546Spatrick                    Locker::AcquireLock | Locker::InitSession |
2822061da546Spatrick                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2823061da546Spatrick                    Locker::FreeLock | Locker::TearDownSession);
2824061da546Spatrick 
2825061da546Spatrick     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2826061da546Spatrick 
2827061da546Spatrick     std::string args_str = args.str();
2828*f6aab3d8Srobert     ret_val = LLDBSwigPythonCallCommandObject(
2829*f6aab3d8Srobert         static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
2830*f6aab3d8Srobert         args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
2831061da546Spatrick   }
2832061da546Spatrick 
2833061da546Spatrick   if (!ret_val)
2834061da546Spatrick     error.SetErrorString("unable to execute script function");
2835*f6aab3d8Srobert   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2836*f6aab3d8Srobert     return false;
2837061da546Spatrick 
2838*f6aab3d8Srobert   error.Clear();
2839061da546Spatrick   return ret_val;
2840061da546Spatrick }
2841061da546Spatrick 
2842dda28197Spatrick /// In Python, a special attribute __doc__ contains the docstring for an object
2843dda28197Spatrick /// (function, method, class, ...) if any is defined Otherwise, the attribute's
2844dda28197Spatrick /// value is None.
GetDocumentationForItem(const char * item,std::string & dest)2845061da546Spatrick bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
2846061da546Spatrick                                                           std::string &dest) {
2847061da546Spatrick   dest.clear();
2848dda28197Spatrick 
2849061da546Spatrick   if (!item || !*item)
2850061da546Spatrick     return false;
2851dda28197Spatrick 
2852061da546Spatrick   std::string command(item);
2853061da546Spatrick   command += ".__doc__";
2854061da546Spatrick 
2855dda28197Spatrick   // Python is going to point this to valid data if ExecuteOneLineWithReturn
2856dda28197Spatrick   // returns successfully.
2857dda28197Spatrick   char *result_ptr = nullptr;
2858061da546Spatrick 
2859061da546Spatrick   if (ExecuteOneLineWithReturn(
2860dda28197Spatrick           command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
2861061da546Spatrick           &result_ptr,
2862be691f3bSpatrick           ExecuteScriptOptions().SetEnableIO(false))) {
2863061da546Spatrick     if (result_ptr)
2864061da546Spatrick       dest.assign(result_ptr);
2865061da546Spatrick     return true;
2866061da546Spatrick   }
2867dda28197Spatrick 
2868dda28197Spatrick   StreamString str_stream;
2869dda28197Spatrick   str_stream << "Function " << item
2870dda28197Spatrick              << " was not found. Containing module might be missing.";
2871dda28197Spatrick   dest = std::string(str_stream.GetString());
2872dda28197Spatrick 
2873dda28197Spatrick   return false;
2874061da546Spatrick }
2875061da546Spatrick 
GetShortHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp,std::string & dest)2876061da546Spatrick bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
2877061da546Spatrick     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2878061da546Spatrick   dest.clear();
2879061da546Spatrick 
2880061da546Spatrick   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2881061da546Spatrick 
2882061da546Spatrick   if (!cmd_obj_sp)
2883061da546Spatrick     return false;
2884061da546Spatrick 
2885061da546Spatrick   PythonObject implementor(PyRefType::Borrowed,
2886061da546Spatrick                            (PyObject *)cmd_obj_sp->GetValue());
2887061da546Spatrick 
2888061da546Spatrick   if (!implementor.IsAllocated())
2889061da546Spatrick     return false;
2890061da546Spatrick 
2891*f6aab3d8Srobert   llvm::Expected<PythonObject> expected_py_return =
2892*f6aab3d8Srobert       implementor.CallMethod("get_short_help");
2893061da546Spatrick 
2894*f6aab3d8Srobert   if (!expected_py_return) {
2895*f6aab3d8Srobert     llvm::consumeError(expected_py_return.takeError());
2896061da546Spatrick     return false;
2897061da546Spatrick   }
2898061da546Spatrick 
2899*f6aab3d8Srobert   PythonObject py_return = std::move(expected_py_return.get());
2900061da546Spatrick 
2901061da546Spatrick   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2902061da546Spatrick     PythonString py_string(PyRefType::Borrowed, py_return.get());
2903061da546Spatrick     llvm::StringRef return_data(py_string.GetString());
2904061da546Spatrick     dest.assign(return_data.data(), return_data.size());
2905dda28197Spatrick     return true;
2906061da546Spatrick   }
2907dda28197Spatrick 
2908dda28197Spatrick   return false;
2909061da546Spatrick }
2910061da546Spatrick 
GetFlagsForCommandObject(StructuredData::GenericSP cmd_obj_sp)2911061da546Spatrick uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
2912061da546Spatrick     StructuredData::GenericSP cmd_obj_sp) {
2913061da546Spatrick   uint32_t result = 0;
2914061da546Spatrick 
2915061da546Spatrick   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2916061da546Spatrick 
2917061da546Spatrick   static char callee_name[] = "get_flags";
2918061da546Spatrick 
2919061da546Spatrick   if (!cmd_obj_sp)
2920061da546Spatrick     return result;
2921061da546Spatrick 
2922061da546Spatrick   PythonObject implementor(PyRefType::Borrowed,
2923061da546Spatrick                            (PyObject *)cmd_obj_sp->GetValue());
2924061da546Spatrick 
2925061da546Spatrick   if (!implementor.IsAllocated())
2926061da546Spatrick     return result;
2927061da546Spatrick 
2928061da546Spatrick   PythonObject pmeth(PyRefType::Owned,
2929061da546Spatrick                      PyObject_GetAttrString(implementor.get(), callee_name));
2930061da546Spatrick 
2931061da546Spatrick   if (PyErr_Occurred())
2932061da546Spatrick     PyErr_Clear();
2933061da546Spatrick 
2934061da546Spatrick   if (!pmeth.IsAllocated())
2935061da546Spatrick     return result;
2936061da546Spatrick 
2937061da546Spatrick   if (PyCallable_Check(pmeth.get()) == 0) {
2938061da546Spatrick     if (PyErr_Occurred())
2939061da546Spatrick       PyErr_Clear();
2940061da546Spatrick     return result;
2941061da546Spatrick   }
2942061da546Spatrick 
2943061da546Spatrick   if (PyErr_Occurred())
2944061da546Spatrick     PyErr_Clear();
2945061da546Spatrick 
2946dda28197Spatrick   long long py_return = unwrapOrSetPythonException(
2947dda28197Spatrick       As<long long>(implementor.CallMethod(callee_name)));
2948061da546Spatrick 
2949061da546Spatrick   // if it fails, print the error but otherwise go on
2950061da546Spatrick   if (PyErr_Occurred()) {
2951061da546Spatrick     PyErr_Print();
2952061da546Spatrick     PyErr_Clear();
2953dda28197Spatrick   } else {
2954dda28197Spatrick     result = py_return;
2955061da546Spatrick   }
2956061da546Spatrick 
2957061da546Spatrick   return result;
2958061da546Spatrick }
2959061da546Spatrick 
GetLongHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp,std::string & dest)2960061da546Spatrick bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
2961061da546Spatrick     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2962061da546Spatrick   dest.clear();
2963061da546Spatrick 
2964061da546Spatrick   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2965061da546Spatrick 
2966061da546Spatrick   if (!cmd_obj_sp)
2967061da546Spatrick     return false;
2968061da546Spatrick 
2969061da546Spatrick   PythonObject implementor(PyRefType::Borrowed,
2970061da546Spatrick                            (PyObject *)cmd_obj_sp->GetValue());
2971061da546Spatrick 
2972061da546Spatrick   if (!implementor.IsAllocated())
2973061da546Spatrick     return false;
2974061da546Spatrick 
2975*f6aab3d8Srobert   llvm::Expected<PythonObject> expected_py_return =
2976*f6aab3d8Srobert       implementor.CallMethod("get_long_help");
2977061da546Spatrick 
2978*f6aab3d8Srobert   if (!expected_py_return) {
2979*f6aab3d8Srobert     llvm::consumeError(expected_py_return.takeError());
2980061da546Spatrick     return false;
2981061da546Spatrick   }
2982061da546Spatrick 
2983*f6aab3d8Srobert   PythonObject py_return = std::move(expected_py_return.get());
2984061da546Spatrick 
2985*f6aab3d8Srobert   bool got_string = false;
2986061da546Spatrick   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2987061da546Spatrick     PythonString str(PyRefType::Borrowed, py_return.get());
2988061da546Spatrick     llvm::StringRef str_data(str.GetString());
2989061da546Spatrick     dest.assign(str_data.data(), str_data.size());
2990061da546Spatrick     got_string = true;
2991061da546Spatrick   }
2992061da546Spatrick 
2993061da546Spatrick   return got_string;
2994061da546Spatrick }
2995061da546Spatrick 
2996061da546Spatrick std::unique_ptr<ScriptInterpreterLocker>
AcquireInterpreterLock()2997061da546Spatrick ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
2998061da546Spatrick   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
2999061da546Spatrick       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3000061da546Spatrick       Locker::FreeLock | Locker::TearDownSession));
3001061da546Spatrick   return py_lock;
3002061da546Spatrick }
3003061da546Spatrick 
Initialize()3004*f6aab3d8Srobert void ScriptInterpreterPythonImpl::Initialize() {
3005be691f3bSpatrick   LLDB_SCOPED_TIMER();
3006061da546Spatrick 
3007061da546Spatrick   // RAII-based initialization which correctly handles multiple-initialization,
3008061da546Spatrick   // version- specific differences among Python 2 and Python 3, and saving and
3009061da546Spatrick   // restoring various other pieces of state that can get mucked with during
3010061da546Spatrick   // initialization.
3011061da546Spatrick   InitializePythonRAII initialize_guard;
3012061da546Spatrick 
3013061da546Spatrick   LLDBSwigPyInit();
3014061da546Spatrick 
3015061da546Spatrick   // Update the path python uses to search for modules to include the current
3016061da546Spatrick   // directory.
3017061da546Spatrick 
3018061da546Spatrick   PyRun_SimpleString("import sys");
3019061da546Spatrick   AddToSysPath(AddLocation::End, ".");
3020061da546Spatrick 
3021061da546Spatrick   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
3022061da546Spatrick   // that use a backslash as the path separator, this will result in executing
3023061da546Spatrick   // python code containing paths with unescaped backslashes.  But Python also
3024061da546Spatrick   // accepts forward slashes, so to make life easier we just use that.
3025061da546Spatrick   if (FileSpec file_spec = GetPythonDir())
3026061da546Spatrick     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3027061da546Spatrick   if (FileSpec file_spec = HostInfo::GetShlibDir())
3028061da546Spatrick     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3029061da546Spatrick 
3030061da546Spatrick   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3031061da546Spatrick                      "lldb.embedded_interpreter; from "
3032061da546Spatrick                      "lldb.embedded_interpreter import run_python_interpreter; "
3033061da546Spatrick                      "from lldb.embedded_interpreter import run_one_line");
3034*f6aab3d8Srobert 
3035*f6aab3d8Srobert #if LLDB_USE_PYTHON_SET_INTERRUPT
3036*f6aab3d8Srobert   // Python will not just overwrite its internal SIGINT handler but also the
3037*f6aab3d8Srobert   // one from the process. Backup the current SIGINT handler to prevent that
3038*f6aab3d8Srobert   // Python deletes it.
3039*f6aab3d8Srobert   RestoreSignalHandlerScope save_sigint(SIGINT);
3040*f6aab3d8Srobert 
3041*f6aab3d8Srobert   // Setup a default SIGINT signal handler that works the same way as the
3042*f6aab3d8Srobert   // normal Python REPL signal handler which raises a KeyboardInterrupt.
3043*f6aab3d8Srobert   // Also make sure to not pollute the user's REPL with the signal module nor
3044*f6aab3d8Srobert   // our utility function.
3045*f6aab3d8Srobert   PyRun_SimpleString("def lldb_setup_sigint_handler():\n"
3046*f6aab3d8Srobert                      "  import signal;\n"
3047*f6aab3d8Srobert                      "  def signal_handler(sig, frame):\n"
3048*f6aab3d8Srobert                      "    raise KeyboardInterrupt()\n"
3049*f6aab3d8Srobert                      "  signal.signal(signal.SIGINT, signal_handler);\n"
3050*f6aab3d8Srobert                      "lldb_setup_sigint_handler();\n"
3051*f6aab3d8Srobert                      "del lldb_setup_sigint_handler\n");
3052*f6aab3d8Srobert #endif
3053061da546Spatrick }
3054061da546Spatrick 
AddToSysPath(AddLocation location,std::string path)3055061da546Spatrick void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3056061da546Spatrick                                                std::string path) {
3057061da546Spatrick   std::string path_copy;
3058061da546Spatrick 
3059061da546Spatrick   std::string statement;
3060061da546Spatrick   if (location == AddLocation::Beginning) {
3061061da546Spatrick     statement.assign("sys.path.insert(0,\"");
3062061da546Spatrick     statement.append(path);
3063061da546Spatrick     statement.append("\")");
3064061da546Spatrick   } else {
3065061da546Spatrick     statement.assign("sys.path.append(\"");
3066061da546Spatrick     statement.append(path);
3067061da546Spatrick     statement.append("\")");
3068061da546Spatrick   }
3069061da546Spatrick   PyRun_SimpleString(statement.c_str());
3070061da546Spatrick }
3071061da546Spatrick 
3072061da546Spatrick // We are intentionally NOT calling Py_Finalize here (this would be the logical
3073061da546Spatrick // place to call it).  Calling Py_Finalize here causes test suite runs to seg
3074061da546Spatrick // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
3075061da546Spatrick // be called 'at_exit'.  When the test suite Python harness finishes up, it
3076061da546Spatrick // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3077061da546Spatrick // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3078061da546Spatrick // which calls ScriptInterpreter::Terminate, which calls
3079061da546Spatrick // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
3080061da546Spatrick // end up with Py_Finalize being called from within Py_Finalize, which results
3081061da546Spatrick // in a seg fault. Since this function only gets called when lldb is shutting
3082061da546Spatrick // down and going away anyway, the fact that we don't actually call Py_Finalize
3083061da546Spatrick // should not cause any problems (everything should shut down/go away anyway
3084061da546Spatrick // when the process exits).
3085061da546Spatrick //
3086061da546Spatrick // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3087061da546Spatrick 
3088061da546Spatrick #endif
3089