15ffd83dbSDimitry Andric //===-- ScriptInterpreterPython.cpp ---------------------------------------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric 
9480093f4SDimitry Andric #include "lldb/Host/Config.h"
10e8d8bef9SDimitry Andric #include "lldb/lldb-enumerations.h"
11*0b57cec5SDimitry Andric 
12480093f4SDimitry Andric #if LLDB_ENABLE_PYTHON
13*0b57cec5SDimitry Andric 
14*0b57cec5SDimitry Andric // LLDB Python header must be included first
15*0b57cec5SDimitry Andric #include "lldb-python.h"
16*0b57cec5SDimitry Andric 
17*0b57cec5SDimitry Andric #include "PythonDataObjects.h"
18c14a5a88SDimitry Andric #include "PythonReadline.h"
19fe6060f1SDimitry Andric #include "SWIGPythonBridge.h"
20*0b57cec5SDimitry Andric #include "ScriptInterpreterPythonImpl.h"
21bdd1243dSDimitry Andric #include "ScriptedPlatformPythonInterface.h"
22fe6060f1SDimitry Andric #include "ScriptedProcessPythonInterface.h"
23fe6060f1SDimitry Andric 
24fe6060f1SDimitry Andric #include "lldb/API/SBError.h"
25*0b57cec5SDimitry Andric #include "lldb/API/SBFrame.h"
26*0b57cec5SDimitry Andric #include "lldb/API/SBValue.h"
27*0b57cec5SDimitry Andric #include "lldb/Breakpoint/StoppointCallbackContext.h"
28*0b57cec5SDimitry Andric #include "lldb/Breakpoint/WatchpointOptions.h"
29*0b57cec5SDimitry Andric #include "lldb/Core/Debugger.h"
30*0b57cec5SDimitry Andric #include "lldb/Core/PluginManager.h"
31bdd1243dSDimitry Andric #include "lldb/Core/ThreadedCommunication.h"
32*0b57cec5SDimitry Andric #include "lldb/Core/ValueObject.h"
33*0b57cec5SDimitry Andric #include "lldb/DataFormatters/TypeSummary.h"
34*0b57cec5SDimitry Andric #include "lldb/Host/FileSystem.h"
35*0b57cec5SDimitry Andric #include "lldb/Host/HostInfo.h"
36*0b57cec5SDimitry Andric #include "lldb/Host/Pipe.h"
37*0b57cec5SDimitry Andric #include "lldb/Interpreter/CommandInterpreter.h"
38*0b57cec5SDimitry Andric #include "lldb/Interpreter/CommandReturnObject.h"
39*0b57cec5SDimitry Andric #include "lldb/Target/Thread.h"
40*0b57cec5SDimitry Andric #include "lldb/Target/ThreadPlan.h"
4104eeddc0SDimitry Andric #include "lldb/Utility/Instrumentation.h"
4281ad6265SDimitry Andric #include "lldb/Utility/LLDBLog.h"
43*0b57cec5SDimitry Andric #include "lldb/Utility/Timer.h"
44*0b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
45*0b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
465ffd83dbSDimitry Andric #include "llvm/Support/Error.h"
47*0b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
489dba64beSDimitry Andric #include "llvm/Support/FormatAdapters.h"
49*0b57cec5SDimitry Andric 
50fe6060f1SDimitry Andric #include <cstdio>
51fe6060f1SDimitry Andric #include <cstdlib>
52*0b57cec5SDimitry Andric #include <memory>
53*0b57cec5SDimitry Andric #include <mutex>
54bdd1243dSDimitry Andric #include <optional>
55*0b57cec5SDimitry Andric #include <string>
56*0b57cec5SDimitry Andric 
57*0b57cec5SDimitry Andric using namespace lldb;
58*0b57cec5SDimitry Andric using namespace lldb_private;
599dba64beSDimitry Andric using namespace lldb_private::python;
609dba64beSDimitry Andric using llvm::Expected;
61*0b57cec5SDimitry Andric 
625ffd83dbSDimitry Andric LLDB_PLUGIN_DEFINE(ScriptInterpreterPython)
635ffd83dbSDimitry Andric 
64*0b57cec5SDimitry Andric // Defined in the SWIG source file
65*0b57cec5SDimitry Andric extern "C" PyObject *PyInit__lldb(void);
66*0b57cec5SDimitry Andric 
67*0b57cec5SDimitry Andric #define LLDBSwigPyInit PyInit__lldb
68*0b57cec5SDimitry Andric 
6904eeddc0SDimitry Andric #if defined(_WIN32)
7004eeddc0SDimitry Andric // Don't mess with the signal handlers on Windows.
7104eeddc0SDimitry Andric #define LLDB_USE_PYTHON_SET_INTERRUPT 0
7204eeddc0SDimitry Andric #else
7304eeddc0SDimitry Andric // PyErr_SetInterrupt was introduced in 3.2.
7404eeddc0SDimitry Andric #define LLDB_USE_PYTHON_SET_INTERRUPT                                          \
7504eeddc0SDimitry Andric   (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
7604eeddc0SDimitry Andric #endif
77*0b57cec5SDimitry Andric 
78e8d8bef9SDimitry Andric static ScriptInterpreterPythonImpl *GetPythonInterpreter(Debugger &debugger) {
79e8d8bef9SDimitry Andric   ScriptInterpreter *script_interpreter =
80e8d8bef9SDimitry Andric       debugger.GetScriptInterpreter(true, lldb::eScriptLanguagePython);
81e8d8bef9SDimitry Andric   return static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
82e8d8bef9SDimitry Andric }
83e8d8bef9SDimitry Andric 
84*0b57cec5SDimitry Andric namespace {
85*0b57cec5SDimitry Andric 
86*0b57cec5SDimitry Andric // Initializing Python is not a straightforward process.  We cannot control
87*0b57cec5SDimitry Andric // what external code may have done before getting to this point in LLDB,
88*0b57cec5SDimitry Andric // including potentially having already initialized Python, so we need to do a
89*0b57cec5SDimitry Andric // lot of work to ensure that the existing state of the system is maintained
90*0b57cec5SDimitry Andric // across our initialization.  We do this by using an RAII pattern where we
91*0b57cec5SDimitry Andric // save off initial state at the beginning, and restore it at the end
92*0b57cec5SDimitry Andric struct InitializePythonRAII {
93*0b57cec5SDimitry Andric public:
94fe6060f1SDimitry Andric   InitializePythonRAII() {
95*0b57cec5SDimitry Andric     InitializePythonHome();
96*0b57cec5SDimitry Andric 
97c14a5a88SDimitry Andric #ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
98c14a5a88SDimitry Andric     // Python's readline is incompatible with libedit being linked into lldb.
99c14a5a88SDimitry Andric     // Provide a patched version local to the embedded interpreter.
100c14a5a88SDimitry Andric     bool ReadlinePatched = false;
101bdd1243dSDimitry Andric     for (auto *p = PyImport_Inittab; p->name != nullptr; p++) {
102c14a5a88SDimitry Andric       if (strcmp(p->name, "readline") == 0) {
103c14a5a88SDimitry Andric         p->initfunc = initlldb_readline;
104c14a5a88SDimitry Andric         break;
105c14a5a88SDimitry Andric       }
106c14a5a88SDimitry Andric     }
107c14a5a88SDimitry Andric     if (!ReadlinePatched) {
108c14a5a88SDimitry Andric       PyImport_AppendInittab("readline", initlldb_readline);
109c14a5a88SDimitry Andric       ReadlinePatched = true;
110c14a5a88SDimitry Andric     }
111c14a5a88SDimitry Andric #endif
112c14a5a88SDimitry Andric 
113*0b57cec5SDimitry Andric     // Register _lldb as a built-in module.
114*0b57cec5SDimitry Andric     PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
115*0b57cec5SDimitry Andric 
116*0b57cec5SDimitry Andric // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
117*0b57cec5SDimitry Andric // calling `Py_Initialize` and `PyEval_InitThreads`.  < 3.2 requires that you
118*0b57cec5SDimitry Andric // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
119*0b57cec5SDimitry Andric #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
120*0b57cec5SDimitry Andric     Py_InitializeEx(0);
121*0b57cec5SDimitry Andric     InitializeThreadsPrivate();
122*0b57cec5SDimitry Andric #else
123*0b57cec5SDimitry Andric     InitializeThreadsPrivate();
124*0b57cec5SDimitry Andric     Py_InitializeEx(0);
125*0b57cec5SDimitry Andric #endif
126*0b57cec5SDimitry Andric   }
127*0b57cec5SDimitry Andric 
128*0b57cec5SDimitry Andric   ~InitializePythonRAII() {
129*0b57cec5SDimitry Andric     if (m_was_already_initialized) {
13081ad6265SDimitry Andric       Log *log = GetLog(LLDBLog::Script);
131*0b57cec5SDimitry Andric       LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
132*0b57cec5SDimitry Andric                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
133*0b57cec5SDimitry Andric       PyGILState_Release(m_gil_state);
134*0b57cec5SDimitry Andric     } else {
135*0b57cec5SDimitry Andric       // We initialized the threads in this function, just unlock the GIL.
136*0b57cec5SDimitry Andric       PyEval_SaveThread();
137*0b57cec5SDimitry Andric     }
138*0b57cec5SDimitry Andric   }
139*0b57cec5SDimitry Andric 
140*0b57cec5SDimitry Andric private:
141*0b57cec5SDimitry Andric   void InitializePythonHome() {
1425ffd83dbSDimitry Andric #if LLDB_EMBED_PYTHON_HOME
1435ffd83dbSDimitry Andric     typedef wchar_t *str_type;
1445ffd83dbSDimitry Andric     static str_type g_python_home = []() -> str_type {
1455ffd83dbSDimitry Andric       const char *lldb_python_home = LLDB_PYTHON_HOME;
1465ffd83dbSDimitry Andric       const char *absolute_python_home = nullptr;
1475ffd83dbSDimitry Andric       llvm::SmallString<64> path;
1485ffd83dbSDimitry Andric       if (llvm::sys::path::is_absolute(lldb_python_home)) {
1495ffd83dbSDimitry Andric         absolute_python_home = lldb_python_home;
1505ffd83dbSDimitry Andric       } else {
1515ffd83dbSDimitry Andric         FileSpec spec = HostInfo::GetShlibDir();
1525ffd83dbSDimitry Andric         if (!spec)
1535ffd83dbSDimitry Andric           return nullptr;
1545ffd83dbSDimitry Andric         spec.GetPath(path);
1555ffd83dbSDimitry Andric         llvm::sys::path::append(path, lldb_python_home);
1565ffd83dbSDimitry Andric         absolute_python_home = path.c_str();
1575ffd83dbSDimitry Andric       }
158*0b57cec5SDimitry Andric       size_t size = 0;
1595ffd83dbSDimitry Andric       return Py_DecodeLocale(absolute_python_home, &size);
1605ffd83dbSDimitry Andric     }();
1615ffd83dbSDimitry Andric     if (g_python_home != nullptr) {
162*0b57cec5SDimitry Andric       Py_SetPythonHome(g_python_home);
1635ffd83dbSDimitry Andric     }
164*0b57cec5SDimitry Andric #endif
165*0b57cec5SDimitry Andric   }
166*0b57cec5SDimitry Andric 
167*0b57cec5SDimitry Andric   void InitializeThreadsPrivate() {
168*0b57cec5SDimitry Andric // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself,
169*0b57cec5SDimitry Andric // so there is no way to determine whether the embedded interpreter
170*0b57cec5SDimitry Andric // was already initialized by some external code. `PyEval_ThreadsInitialized`
171*0b57cec5SDimitry Andric // would always return `true` and `PyGILState_Ensure/Release` flow would be
172*0b57cec5SDimitry Andric // executed instead of unlocking GIL with `PyEval_SaveThread`. When
173*0b57cec5SDimitry Andric // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock.
174*0b57cec5SDimitry Andric #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3)
175*0b57cec5SDimitry Andric     // The only case we should go further and acquire the GIL: it is unlocked.
176*0b57cec5SDimitry Andric     if (PyGILState_Check())
177*0b57cec5SDimitry Andric       return;
178*0b57cec5SDimitry Andric #endif
179*0b57cec5SDimitry Andric 
180*0b57cec5SDimitry Andric     if (PyEval_ThreadsInitialized()) {
18181ad6265SDimitry Andric       Log *log = GetLog(LLDBLog::Script);
182*0b57cec5SDimitry Andric 
183*0b57cec5SDimitry Andric       m_was_already_initialized = true;
184*0b57cec5SDimitry Andric       m_gil_state = PyGILState_Ensure();
185*0b57cec5SDimitry Andric       LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n",
186*0b57cec5SDimitry Andric                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
187*0b57cec5SDimitry Andric       return;
188*0b57cec5SDimitry Andric     }
189*0b57cec5SDimitry Andric 
190*0b57cec5SDimitry Andric     // InitThreads acquires the GIL if it hasn't been called before.
191*0b57cec5SDimitry Andric     PyEval_InitThreads();
192*0b57cec5SDimitry Andric   }
193*0b57cec5SDimitry Andric 
194fe6060f1SDimitry Andric   PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
195fe6060f1SDimitry Andric   bool m_was_already_initialized = false;
196*0b57cec5SDimitry Andric };
19704eeddc0SDimitry Andric 
19804eeddc0SDimitry Andric #if LLDB_USE_PYTHON_SET_INTERRUPT
19904eeddc0SDimitry Andric /// Saves the current signal handler for the specified signal and restores
20004eeddc0SDimitry Andric /// it at the end of the current scope.
20104eeddc0SDimitry Andric struct RestoreSignalHandlerScope {
20204eeddc0SDimitry Andric   /// The signal handler.
20304eeddc0SDimitry Andric   struct sigaction m_prev_handler;
20404eeddc0SDimitry Andric   int m_signal_code;
20504eeddc0SDimitry Andric   RestoreSignalHandlerScope(int signal_code) : m_signal_code(signal_code) {
20604eeddc0SDimitry Andric     // Initialize sigaction to their default state.
20704eeddc0SDimitry Andric     std::memset(&m_prev_handler, 0, sizeof(m_prev_handler));
20804eeddc0SDimitry Andric     // Don't install a new handler, just read back the old one.
20904eeddc0SDimitry Andric     struct sigaction *new_handler = nullptr;
21004eeddc0SDimitry Andric     int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler);
21104eeddc0SDimitry Andric     lldbassert(signal_err == 0 && "sigaction failed to read handler");
21204eeddc0SDimitry Andric   }
21304eeddc0SDimitry Andric   ~RestoreSignalHandlerScope() {
21404eeddc0SDimitry Andric     int signal_err = ::sigaction(m_signal_code, &m_prev_handler, nullptr);
21504eeddc0SDimitry Andric     lldbassert(signal_err == 0 && "sigaction failed to restore old handler");
21604eeddc0SDimitry Andric   }
21704eeddc0SDimitry Andric };
21804eeddc0SDimitry Andric #endif
219*0b57cec5SDimitry Andric } // namespace
220*0b57cec5SDimitry Andric 
221*0b57cec5SDimitry Andric void ScriptInterpreterPython::ComputePythonDirForApple(
222*0b57cec5SDimitry Andric     llvm::SmallVectorImpl<char> &path) {
223*0b57cec5SDimitry Andric   auto style = llvm::sys::path::Style::posix;
224*0b57cec5SDimitry Andric 
225*0b57cec5SDimitry Andric   llvm::StringRef path_ref(path.begin(), path.size());
226*0b57cec5SDimitry Andric   auto rbegin = llvm::sys::path::rbegin(path_ref, style);
227*0b57cec5SDimitry Andric   auto rend = llvm::sys::path::rend(path_ref);
228*0b57cec5SDimitry Andric   auto framework = std::find(rbegin, rend, "LLDB.framework");
229*0b57cec5SDimitry Andric   if (framework == rend) {
2309dba64beSDimitry Andric     ComputePythonDir(path);
231*0b57cec5SDimitry Andric     return;
232*0b57cec5SDimitry Andric   }
233*0b57cec5SDimitry Andric   path.resize(framework - rend);
234*0b57cec5SDimitry Andric   llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
235*0b57cec5SDimitry Andric }
236*0b57cec5SDimitry Andric 
2379dba64beSDimitry Andric void ScriptInterpreterPython::ComputePythonDir(
238*0b57cec5SDimitry Andric     llvm::SmallVectorImpl<char> &path) {
239*0b57cec5SDimitry Andric   // Build the path by backing out of the lib dir, then building with whatever
240*0b57cec5SDimitry Andric   // the real python interpreter uses.  (e.g. lib for most, lib64 on RHEL
2419dba64beSDimitry Andric   // x86_64, or bin on Windows).
2429dba64beSDimitry Andric   llvm::sys::path::remove_filename(path);
2439dba64beSDimitry Andric   llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
244*0b57cec5SDimitry Andric 
2459dba64beSDimitry Andric #if defined(_WIN32)
246bdd1243dSDimitry Andric   // This will be injected directly through FileSpec.SetDirectory(),
247*0b57cec5SDimitry Andric   // so we need to normalize manually.
248*0b57cec5SDimitry Andric   std::replace(path.begin(), path.end(), '\\', '/');
2499dba64beSDimitry Andric #endif
250*0b57cec5SDimitry Andric }
251*0b57cec5SDimitry Andric 
252*0b57cec5SDimitry Andric FileSpec ScriptInterpreterPython::GetPythonDir() {
253*0b57cec5SDimitry Andric   static FileSpec g_spec = []() {
254*0b57cec5SDimitry Andric     FileSpec spec = HostInfo::GetShlibDir();
255*0b57cec5SDimitry Andric     if (!spec)
256*0b57cec5SDimitry Andric       return FileSpec();
257*0b57cec5SDimitry Andric     llvm::SmallString<64> path;
258*0b57cec5SDimitry Andric     spec.GetPath(path);
259*0b57cec5SDimitry Andric 
260*0b57cec5SDimitry Andric #if defined(__APPLE__)
261*0b57cec5SDimitry Andric     ComputePythonDirForApple(path);
262*0b57cec5SDimitry Andric #else
2639dba64beSDimitry Andric     ComputePythonDir(path);
264*0b57cec5SDimitry Andric #endif
265bdd1243dSDimitry Andric     spec.SetDirectory(path);
266*0b57cec5SDimitry Andric     return spec;
267*0b57cec5SDimitry Andric   }();
268*0b57cec5SDimitry Andric   return g_spec;
269*0b57cec5SDimitry Andric }
270*0b57cec5SDimitry Andric 
271349cc55cSDimitry Andric static const char GetInterpreterInfoScript[] = R"(
272349cc55cSDimitry Andric import os
273349cc55cSDimitry Andric import sys
274349cc55cSDimitry Andric 
275349cc55cSDimitry Andric def main(lldb_python_dir, python_exe_relative_path):
276349cc55cSDimitry Andric   info = {
277349cc55cSDimitry Andric     "lldb-pythonpath": lldb_python_dir,
278349cc55cSDimitry Andric     "language": "python",
279349cc55cSDimitry Andric     "prefix": sys.prefix,
280349cc55cSDimitry Andric     "executable": os.path.join(sys.prefix, python_exe_relative_path)
281349cc55cSDimitry Andric   }
282349cc55cSDimitry Andric   return info
283349cc55cSDimitry Andric )";
284349cc55cSDimitry Andric 
285349cc55cSDimitry Andric static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH;
286349cc55cSDimitry Andric 
287349cc55cSDimitry Andric StructuredData::DictionarySP ScriptInterpreterPython::GetInterpreterInfo() {
288349cc55cSDimitry Andric   GIL gil;
289349cc55cSDimitry Andric   FileSpec python_dir_spec = GetPythonDir();
290349cc55cSDimitry Andric   if (!python_dir_spec)
291349cc55cSDimitry Andric     return nullptr;
292349cc55cSDimitry Andric   PythonScript get_info(GetInterpreterInfoScript);
293349cc55cSDimitry Andric   auto info_json = unwrapIgnoringErrors(
294349cc55cSDimitry Andric       As<PythonDictionary>(get_info(PythonString(python_dir_spec.GetPath()),
295349cc55cSDimitry Andric                                     PythonString(python_exe_relative_path))));
296349cc55cSDimitry Andric   if (!info_json)
297349cc55cSDimitry Andric     return nullptr;
298349cc55cSDimitry Andric   return info_json.CreateStructuredDictionary();
299349cc55cSDimitry Andric }
300349cc55cSDimitry Andric 
301fe6060f1SDimitry Andric void ScriptInterpreterPython::SharedLibraryDirectoryHelper(
302fe6060f1SDimitry Andric     FileSpec &this_file) {
303fe6060f1SDimitry Andric   // When we're loaded from python, this_file will point to the file inside the
304fe6060f1SDimitry Andric   // python package directory. Replace it with the one in the lib directory.
305fe6060f1SDimitry Andric #ifdef _WIN32
306fe6060f1SDimitry Andric   // On windows, we need to manually back out of the python tree, and go into
307fe6060f1SDimitry Andric   // the bin directory. This is pretty much the inverse of what ComputePythonDir
308fe6060f1SDimitry Andric   // does.
309fe6060f1SDimitry Andric   if (this_file.GetFileNameExtension() == ConstString(".pyd")) {
310fe6060f1SDimitry Andric     this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd
311fe6060f1SDimitry Andric     this_file.RemoveLastPathComponent(); // lldb
312fe6060f1SDimitry Andric     llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
313fe6060f1SDimitry Andric     for (auto it = llvm::sys::path::begin(libdir),
314fe6060f1SDimitry Andric               end = llvm::sys::path::end(libdir);
315fe6060f1SDimitry Andric          it != end; ++it)
316fe6060f1SDimitry Andric       this_file.RemoveLastPathComponent();
317fe6060f1SDimitry Andric     this_file.AppendPathComponent("bin");
318fe6060f1SDimitry Andric     this_file.AppendPathComponent("liblldb.dll");
319fe6060f1SDimitry Andric   }
320fe6060f1SDimitry Andric #else
321fe6060f1SDimitry Andric   // The python file is a symlink, so we can find the real library by resolving
322fe6060f1SDimitry Andric   // it. We can do this unconditionally.
323fe6060f1SDimitry Andric   FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
324fe6060f1SDimitry Andric #endif
325fe6060f1SDimitry Andric }
326fe6060f1SDimitry Andric 
327349cc55cSDimitry Andric llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() {
328*0b57cec5SDimitry Andric   return "Embedded Python interpreter";
329*0b57cec5SDimitry Andric }
330*0b57cec5SDimitry Andric 
331*0b57cec5SDimitry Andric void ScriptInterpreterPython::Initialize() {
332*0b57cec5SDimitry Andric   static llvm::once_flag g_once_flag;
333*0b57cec5SDimitry Andric   llvm::call_once(g_once_flag, []() {
334*0b57cec5SDimitry Andric     PluginManager::RegisterPlugin(GetPluginNameStatic(),
335*0b57cec5SDimitry Andric                                   GetPluginDescriptionStatic(),
336*0b57cec5SDimitry Andric                                   lldb::eScriptLanguagePython,
337*0b57cec5SDimitry Andric                                   ScriptInterpreterPythonImpl::CreateInstance);
33804eeddc0SDimitry Andric     ScriptInterpreterPythonImpl::Initialize();
339*0b57cec5SDimitry Andric   });
340*0b57cec5SDimitry Andric }
341*0b57cec5SDimitry Andric 
342*0b57cec5SDimitry Andric void ScriptInterpreterPython::Terminate() {}
343*0b57cec5SDimitry Andric 
344*0b57cec5SDimitry Andric ScriptInterpreterPythonImpl::Locker::Locker(
345*0b57cec5SDimitry Andric     ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
3469dba64beSDimitry Andric     uint16_t on_leave, FileSP in, FileSP out, FileSP err)
347*0b57cec5SDimitry Andric     : ScriptInterpreterLocker(),
348*0b57cec5SDimitry Andric       m_teardown_session((on_leave & TearDownSession) == TearDownSession),
349*0b57cec5SDimitry Andric       m_python_interpreter(py_interpreter) {
350*0b57cec5SDimitry Andric   DoAcquireLock();
351*0b57cec5SDimitry Andric   if ((on_entry & InitSession) == InitSession) {
352*0b57cec5SDimitry Andric     if (!DoInitSession(on_entry, in, out, err)) {
353*0b57cec5SDimitry Andric       // Don't teardown the session if we didn't init it.
354*0b57cec5SDimitry Andric       m_teardown_session = false;
355*0b57cec5SDimitry Andric     }
356*0b57cec5SDimitry Andric   }
357*0b57cec5SDimitry Andric }
358*0b57cec5SDimitry Andric 
359*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
36081ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Script);
361*0b57cec5SDimitry Andric   m_GILState = PyGILState_Ensure();
362*0b57cec5SDimitry Andric   LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked",
363*0b57cec5SDimitry Andric             m_GILState == PyGILState_UNLOCKED ? "un" : "");
364*0b57cec5SDimitry Andric 
365*0b57cec5SDimitry Andric   // we need to save the thread state when we first start the command because
366*0b57cec5SDimitry Andric   // we might decide to interrupt it while some action is taking place outside
367*0b57cec5SDimitry Andric   // of Python (e.g. printing to screen, waiting for the network, ...) in that
368*0b57cec5SDimitry Andric   // case, _PyThreadState_Current will be NULL - and we would be unable to set
369*0b57cec5SDimitry Andric   // the asynchronous exception - not a desirable situation
370*0b57cec5SDimitry Andric   m_python_interpreter->SetThreadState(PyThreadState_Get());
371*0b57cec5SDimitry Andric   m_python_interpreter->IncrementLockCount();
372*0b57cec5SDimitry Andric   return true;
373*0b57cec5SDimitry Andric }
374*0b57cec5SDimitry Andric 
375*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
3769dba64beSDimitry Andric                                                         FileSP in, FileSP out,
3779dba64beSDimitry Andric                                                         FileSP err) {
378*0b57cec5SDimitry Andric   if (!m_python_interpreter)
379*0b57cec5SDimitry Andric     return false;
380*0b57cec5SDimitry Andric   return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
381*0b57cec5SDimitry Andric }
382*0b57cec5SDimitry Andric 
383*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
38481ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Script);
385*0b57cec5SDimitry Andric   LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
386*0b57cec5SDimitry Andric             m_GILState == PyGILState_UNLOCKED ? "un" : "");
387*0b57cec5SDimitry Andric   PyGILState_Release(m_GILState);
388*0b57cec5SDimitry Andric   m_python_interpreter->DecrementLockCount();
389*0b57cec5SDimitry Andric   return true;
390*0b57cec5SDimitry Andric }
391*0b57cec5SDimitry Andric 
392*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
393*0b57cec5SDimitry Andric   if (!m_python_interpreter)
394*0b57cec5SDimitry Andric     return false;
395*0b57cec5SDimitry Andric   m_python_interpreter->LeaveSession();
396*0b57cec5SDimitry Andric   return true;
397*0b57cec5SDimitry Andric }
398*0b57cec5SDimitry Andric 
399*0b57cec5SDimitry Andric ScriptInterpreterPythonImpl::Locker::~Locker() {
400*0b57cec5SDimitry Andric   if (m_teardown_session)
401*0b57cec5SDimitry Andric     DoTearDownSession();
402*0b57cec5SDimitry Andric   DoFreeLock();
403*0b57cec5SDimitry Andric }
404*0b57cec5SDimitry Andric 
405*0b57cec5SDimitry Andric ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger)
406*0b57cec5SDimitry Andric     : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
407*0b57cec5SDimitry Andric       m_saved_stderr(), m_main_module(),
408*0b57cec5SDimitry Andric       m_session_dict(PyInitialValue::Invalid),
409*0b57cec5SDimitry Andric       m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(),
410*0b57cec5SDimitry Andric       m_run_one_line_str_global(),
411*0b57cec5SDimitry Andric       m_dictionary_name(m_debugger.GetInstanceName().AsCString()),
4129dba64beSDimitry Andric       m_active_io_handler(eIOHandlerNone), m_session_is_active(false),
4135ffd83dbSDimitry Andric       m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
4149dba64beSDimitry Andric       m_command_thread_state(nullptr) {
415fe6060f1SDimitry Andric   m_scripted_process_interface_up =
416fe6060f1SDimitry Andric       std::make_unique<ScriptedProcessPythonInterface>(*this);
417bdd1243dSDimitry Andric   m_scripted_platform_interface_up =
418bdd1243dSDimitry Andric       std::make_unique<ScriptedPlatformPythonInterface>(*this);
419fe6060f1SDimitry Andric 
420*0b57cec5SDimitry Andric   m_dictionary_name.append("_dict");
421*0b57cec5SDimitry Andric   StreamString run_string;
422*0b57cec5SDimitry Andric   run_string.Printf("%s = dict()", m_dictionary_name.c_str());
423*0b57cec5SDimitry Andric 
424*0b57cec5SDimitry Andric   Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock);
425*0b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
426*0b57cec5SDimitry Andric 
427*0b57cec5SDimitry Andric   run_string.Clear();
428*0b57cec5SDimitry Andric   run_string.Printf(
429*0b57cec5SDimitry Andric       "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
430*0b57cec5SDimitry Andric       m_dictionary_name.c_str());
431*0b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
432*0b57cec5SDimitry Andric 
433*0b57cec5SDimitry Andric   // Reloading modules requires a different syntax in Python 2 and Python 3.
434*0b57cec5SDimitry Andric   // This provides a consistent syntax no matter what version of Python.
435*0b57cec5SDimitry Andric   run_string.Clear();
436bdd1243dSDimitry Andric   run_string.Printf("run_one_line (%s, 'from importlib import reload as reload_module')",
437*0b57cec5SDimitry Andric                     m_dictionary_name.c_str());
438*0b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
439*0b57cec5SDimitry Andric 
440*0b57cec5SDimitry Andric   // WARNING: temporary code that loads Cocoa formatters - this should be done
441*0b57cec5SDimitry Andric   // on a per-platform basis rather than loading the whole set and letting the
442*0b57cec5SDimitry Andric   // individual formatter classes exploit APIs to check whether they can/cannot
443*0b57cec5SDimitry Andric   // do their task
444*0b57cec5SDimitry Andric   run_string.Clear();
445*0b57cec5SDimitry Andric   run_string.Printf(
446*0b57cec5SDimitry Andric       "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')",
447*0b57cec5SDimitry Andric       m_dictionary_name.c_str());
448*0b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
449*0b57cec5SDimitry Andric   run_string.Clear();
450*0b57cec5SDimitry Andric 
451*0b57cec5SDimitry Andric   run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
452*0b57cec5SDimitry Andric                     "lldb.embedded_interpreter import run_python_interpreter; "
453*0b57cec5SDimitry Andric                     "from lldb.embedded_interpreter import run_one_line')",
454*0b57cec5SDimitry Andric                     m_dictionary_name.c_str());
455*0b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
456*0b57cec5SDimitry Andric   run_string.Clear();
457*0b57cec5SDimitry Andric 
458*0b57cec5SDimitry Andric   run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
459*0b57cec5SDimitry Andric                     "; pydoc.pager = pydoc.plainpager')",
460*0b57cec5SDimitry Andric                     m_dictionary_name.c_str(), m_debugger.GetID());
461*0b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
462*0b57cec5SDimitry Andric }
463*0b57cec5SDimitry Andric 
464*0b57cec5SDimitry Andric ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
465*0b57cec5SDimitry Andric   // the session dictionary may hold objects with complex state which means
466*0b57cec5SDimitry Andric   // that they may need to be torn down with some level of smarts and that, in
467*0b57cec5SDimitry Andric   // turn, requires a valid thread state force Python to procure itself such a
468*0b57cec5SDimitry Andric   // thread state, nuke the session dictionary and then release it for others
469*0b57cec5SDimitry Andric   // to use and proceed with the rest of the shutdown
470*0b57cec5SDimitry Andric   auto gil_state = PyGILState_Ensure();
471*0b57cec5SDimitry Andric   m_session_dict.Reset();
472*0b57cec5SDimitry Andric   PyGILState_Release(gil_state);
473*0b57cec5SDimitry Andric }
474*0b57cec5SDimitry Andric 
475*0b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler,
476*0b57cec5SDimitry Andric                                                      bool interactive) {
477*0b57cec5SDimitry Andric   const char *instructions = nullptr;
478*0b57cec5SDimitry Andric 
479*0b57cec5SDimitry Andric   switch (m_active_io_handler) {
480*0b57cec5SDimitry Andric   case eIOHandlerNone:
481*0b57cec5SDimitry Andric     break;
482*0b57cec5SDimitry Andric   case eIOHandlerBreakpoint:
483*0b57cec5SDimitry Andric     instructions = R"(Enter your Python command(s). Type 'DONE' to end.
484*0b57cec5SDimitry Andric def function (frame, bp_loc, internal_dict):
485*0b57cec5SDimitry Andric     """frame: the lldb.SBFrame for the location at which you stopped
486*0b57cec5SDimitry Andric        bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
487*0b57cec5SDimitry Andric        internal_dict: an LLDB support object not to be used"""
488*0b57cec5SDimitry Andric )";
489*0b57cec5SDimitry Andric     break;
490*0b57cec5SDimitry Andric   case eIOHandlerWatchpoint:
491*0b57cec5SDimitry Andric     instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
492*0b57cec5SDimitry Andric     break;
493*0b57cec5SDimitry Andric   }
494*0b57cec5SDimitry Andric 
495*0b57cec5SDimitry Andric   if (instructions) {
4969dba64beSDimitry Andric     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
497*0b57cec5SDimitry Andric     if (output_sp && interactive) {
498*0b57cec5SDimitry Andric       output_sp->PutCString(instructions);
499*0b57cec5SDimitry Andric       output_sp->Flush();
500*0b57cec5SDimitry Andric     }
501*0b57cec5SDimitry Andric   }
502*0b57cec5SDimitry Andric }
503*0b57cec5SDimitry Andric 
504*0b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler,
505*0b57cec5SDimitry Andric                                                          std::string &data) {
506*0b57cec5SDimitry Andric   io_handler.SetIsDone(true);
507*0b57cec5SDimitry Andric   bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
508*0b57cec5SDimitry Andric 
509*0b57cec5SDimitry Andric   switch (m_active_io_handler) {
510*0b57cec5SDimitry Andric   case eIOHandlerNone:
511*0b57cec5SDimitry Andric     break;
512*0b57cec5SDimitry Andric   case eIOHandlerBreakpoint: {
513fe6060f1SDimitry Andric     std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
514fe6060f1SDimitry Andric         (std::vector<std::reference_wrapper<BreakpointOptions>> *)
515fe6060f1SDimitry Andric             io_handler.GetUserData();
516fe6060f1SDimitry Andric     for (BreakpointOptions &bp_options : *bp_options_vec) {
517*0b57cec5SDimitry Andric 
5189dba64beSDimitry Andric       auto data_up = std::make_unique<CommandDataPython>();
519*0b57cec5SDimitry Andric       if (!data_up)
520*0b57cec5SDimitry Andric         break;
521*0b57cec5SDimitry Andric       data_up->user_source.SplitIntoLines(data);
522*0b57cec5SDimitry Andric 
523480093f4SDimitry Andric       StructuredData::ObjectSP empty_args_sp;
524*0b57cec5SDimitry Andric       if (GenerateBreakpointCommandCallbackData(data_up->user_source,
525480093f4SDimitry Andric                                                 data_up->script_source,
526480093f4SDimitry Andric                                                 false)
527*0b57cec5SDimitry Andric               .Success()) {
528*0b57cec5SDimitry Andric         auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
529*0b57cec5SDimitry Andric             std::move(data_up));
530fe6060f1SDimitry Andric         bp_options.SetCallback(
531*0b57cec5SDimitry Andric             ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
532*0b57cec5SDimitry Andric       } else if (!batch_mode) {
5339dba64beSDimitry Andric         StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
534*0b57cec5SDimitry Andric         if (error_sp) {
535*0b57cec5SDimitry Andric           error_sp->Printf("Warning: No command attached to breakpoint.\n");
536*0b57cec5SDimitry Andric           error_sp->Flush();
537*0b57cec5SDimitry Andric         }
538*0b57cec5SDimitry Andric       }
539*0b57cec5SDimitry Andric     }
540*0b57cec5SDimitry Andric     m_active_io_handler = eIOHandlerNone;
541*0b57cec5SDimitry Andric   } break;
542*0b57cec5SDimitry Andric   case eIOHandlerWatchpoint: {
543*0b57cec5SDimitry Andric     WatchpointOptions *wp_options =
544*0b57cec5SDimitry Andric         (WatchpointOptions *)io_handler.GetUserData();
5459dba64beSDimitry Andric     auto data_up = std::make_unique<WatchpointOptions::CommandData>();
546*0b57cec5SDimitry Andric     data_up->user_source.SplitIntoLines(data);
547*0b57cec5SDimitry Andric 
548*0b57cec5SDimitry Andric     if (GenerateWatchpointCommandCallbackData(data_up->user_source,
549*0b57cec5SDimitry Andric                                               data_up->script_source)) {
550*0b57cec5SDimitry Andric       auto baton_sp =
551*0b57cec5SDimitry Andric           std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
552*0b57cec5SDimitry Andric       wp_options->SetCallback(
553*0b57cec5SDimitry Andric           ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
554*0b57cec5SDimitry Andric     } else if (!batch_mode) {
5559dba64beSDimitry Andric       StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
556*0b57cec5SDimitry Andric       if (error_sp) {
557*0b57cec5SDimitry Andric         error_sp->Printf("Warning: No command attached to breakpoint.\n");
558*0b57cec5SDimitry Andric         error_sp->Flush();
559*0b57cec5SDimitry Andric       }
560*0b57cec5SDimitry Andric     }
561*0b57cec5SDimitry Andric     m_active_io_handler = eIOHandlerNone;
562*0b57cec5SDimitry Andric   } break;
563*0b57cec5SDimitry Andric   }
564*0b57cec5SDimitry Andric }
565*0b57cec5SDimitry Andric 
566*0b57cec5SDimitry Andric lldb::ScriptInterpreterSP
567*0b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) {
568*0b57cec5SDimitry Andric   return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
569*0b57cec5SDimitry Andric }
570*0b57cec5SDimitry Andric 
571*0b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::LeaveSession() {
57281ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Script);
573*0b57cec5SDimitry Andric   if (log)
574*0b57cec5SDimitry Andric     log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
575*0b57cec5SDimitry Andric 
5769dba64beSDimitry Andric   // Unset the LLDB global variables.
5779dba64beSDimitry Andric   PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
5789dba64beSDimitry Andric                      "= None; lldb.thread = None; lldb.frame = None");
5799dba64beSDimitry Andric 
580*0b57cec5SDimitry Andric   // checking that we have a valid thread state - since we use our own
581*0b57cec5SDimitry Andric   // threading and locking in some (rare) cases during cleanup Python may end
582*0b57cec5SDimitry Andric   // up believing we have no thread state and PyImport_AddModule will crash if
583*0b57cec5SDimitry Andric   // that is the case - since that seems to only happen when destroying the
584*0b57cec5SDimitry Andric   // SBDebugger, we can make do without clearing up stdout and stderr
585*0b57cec5SDimitry Andric 
586*0b57cec5SDimitry Andric   // rdar://problem/11292882
587*0b57cec5SDimitry Andric   // When the current thread state is NULL, PyThreadState_Get() issues a fatal
588*0b57cec5SDimitry Andric   // error.
589*0b57cec5SDimitry Andric   if (PyThreadState_GetDict()) {
590*0b57cec5SDimitry Andric     PythonDictionary &sys_module_dict = GetSysModuleDictionary();
591*0b57cec5SDimitry Andric     if (sys_module_dict.IsValid()) {
592*0b57cec5SDimitry Andric       if (m_saved_stdin.IsValid()) {
593*0b57cec5SDimitry Andric         sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
594*0b57cec5SDimitry Andric         m_saved_stdin.Reset();
595*0b57cec5SDimitry Andric       }
596*0b57cec5SDimitry Andric       if (m_saved_stdout.IsValid()) {
597*0b57cec5SDimitry Andric         sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
598*0b57cec5SDimitry Andric         m_saved_stdout.Reset();
599*0b57cec5SDimitry Andric       }
600*0b57cec5SDimitry Andric       if (m_saved_stderr.IsValid()) {
601*0b57cec5SDimitry Andric         sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
602*0b57cec5SDimitry Andric         m_saved_stderr.Reset();
603*0b57cec5SDimitry Andric       }
604*0b57cec5SDimitry Andric     }
605*0b57cec5SDimitry Andric   }
606*0b57cec5SDimitry Andric 
607*0b57cec5SDimitry Andric   m_session_is_active = false;
608*0b57cec5SDimitry Andric }
609*0b57cec5SDimitry Andric 
6109dba64beSDimitry Andric bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp,
6119dba64beSDimitry Andric                                                const char *py_name,
6129dba64beSDimitry Andric                                                PythonObject &save_file,
613*0b57cec5SDimitry Andric                                                const char *mode) {
6149dba64beSDimitry Andric   if (!file_sp || !*file_sp) {
6159dba64beSDimitry Andric     save_file.Reset();
6169dba64beSDimitry Andric     return false;
6179dba64beSDimitry Andric   }
6189dba64beSDimitry Andric   File &file = *file_sp;
6199dba64beSDimitry Andric 
620*0b57cec5SDimitry Andric   // Flush the file before giving it to python to avoid interleaved output.
621*0b57cec5SDimitry Andric   file.Flush();
622*0b57cec5SDimitry Andric 
623*0b57cec5SDimitry Andric   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
624*0b57cec5SDimitry Andric 
6259dba64beSDimitry Andric   auto new_file = PythonFile::FromFile(file, mode);
6269dba64beSDimitry Andric   if (!new_file) {
6279dba64beSDimitry Andric     llvm::consumeError(new_file.takeError());
628*0b57cec5SDimitry Andric     return false;
629*0b57cec5SDimitry Andric   }
630*0b57cec5SDimitry Andric 
6319dba64beSDimitry Andric   save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
6329dba64beSDimitry Andric 
6339dba64beSDimitry Andric   sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
6349dba64beSDimitry Andric   return true;
6359dba64beSDimitry Andric }
6369dba64beSDimitry Andric 
637*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
6389dba64beSDimitry Andric                                                FileSP in_sp, FileSP out_sp,
6399dba64beSDimitry Andric                                                FileSP err_sp) {
640*0b57cec5SDimitry Andric   // If we have already entered the session, without having officially 'left'
641*0b57cec5SDimitry Andric   // it, then there is no need to 'enter' it again.
64281ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Script);
643*0b57cec5SDimitry Andric   if (m_session_is_active) {
6449dba64beSDimitry Andric     LLDB_LOGF(
6459dba64beSDimitry Andric         log,
646*0b57cec5SDimitry Andric         "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
647*0b57cec5SDimitry Andric         ") session is already active, returning without doing anything",
648*0b57cec5SDimitry Andric         on_entry_flags);
649*0b57cec5SDimitry Andric     return false;
650*0b57cec5SDimitry Andric   }
651*0b57cec5SDimitry Andric 
6529dba64beSDimitry Andric   LLDB_LOGF(
6539dba64beSDimitry Andric       log,
6549dba64beSDimitry Andric       "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
655*0b57cec5SDimitry Andric       on_entry_flags);
656*0b57cec5SDimitry Andric 
657*0b57cec5SDimitry Andric   m_session_is_active = true;
658*0b57cec5SDimitry Andric 
659*0b57cec5SDimitry Andric   StreamString run_string;
660*0b57cec5SDimitry Andric 
661*0b57cec5SDimitry Andric   if (on_entry_flags & Locker::InitGlobals) {
662*0b57cec5SDimitry Andric     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
663*0b57cec5SDimitry Andric                       m_dictionary_name.c_str(), m_debugger.GetID());
664*0b57cec5SDimitry Andric     run_string.Printf(
665*0b57cec5SDimitry Andric         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
666*0b57cec5SDimitry Andric         m_debugger.GetID());
667*0b57cec5SDimitry Andric     run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
668*0b57cec5SDimitry Andric     run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
669*0b57cec5SDimitry Andric     run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
670*0b57cec5SDimitry Andric     run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
671*0b57cec5SDimitry Andric     run_string.PutCString("')");
672*0b57cec5SDimitry Andric   } else {
673*0b57cec5SDimitry Andric     // If we aren't initing the globals, we should still always set the
674*0b57cec5SDimitry Andric     // debugger (since that is always unique.)
675*0b57cec5SDimitry Andric     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
676*0b57cec5SDimitry Andric                       m_dictionary_name.c_str(), m_debugger.GetID());
677*0b57cec5SDimitry Andric     run_string.Printf(
678*0b57cec5SDimitry Andric         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
679*0b57cec5SDimitry Andric         m_debugger.GetID());
680*0b57cec5SDimitry Andric     run_string.PutCString("')");
681*0b57cec5SDimitry Andric   }
682*0b57cec5SDimitry Andric 
683*0b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
684*0b57cec5SDimitry Andric   run_string.Clear();
685*0b57cec5SDimitry Andric 
686*0b57cec5SDimitry Andric   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
687*0b57cec5SDimitry Andric   if (sys_module_dict.IsValid()) {
6889dba64beSDimitry Andric     lldb::FileSP top_in_sp;
6899dba64beSDimitry Andric     lldb::StreamFileSP top_out_sp, top_err_sp;
6909dba64beSDimitry Andric     if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
6919dba64beSDimitry Andric       m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
6929dba64beSDimitry Andric                                                  top_err_sp);
693*0b57cec5SDimitry Andric 
694*0b57cec5SDimitry Andric     if (on_entry_flags & Locker::NoSTDIN) {
695*0b57cec5SDimitry Andric       m_saved_stdin.Reset();
696*0b57cec5SDimitry Andric     } else {
6979dba64beSDimitry Andric       if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
6989dba64beSDimitry Andric         if (top_in_sp)
6999dba64beSDimitry Andric           SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
700*0b57cec5SDimitry Andric       }
701*0b57cec5SDimitry Andric     }
702*0b57cec5SDimitry Andric 
7039dba64beSDimitry Andric     if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
7049dba64beSDimitry Andric       if (top_out_sp)
7059dba64beSDimitry Andric         SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w");
706*0b57cec5SDimitry Andric     }
707*0b57cec5SDimitry Andric 
7089dba64beSDimitry Andric     if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
7099dba64beSDimitry Andric       if (top_err_sp)
7109dba64beSDimitry Andric         SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w");
711*0b57cec5SDimitry Andric     }
712*0b57cec5SDimitry Andric   }
713*0b57cec5SDimitry Andric 
714*0b57cec5SDimitry Andric   if (PyErr_Occurred())
715*0b57cec5SDimitry Andric     PyErr_Clear();
716*0b57cec5SDimitry Andric 
717*0b57cec5SDimitry Andric   return true;
718*0b57cec5SDimitry Andric }
719*0b57cec5SDimitry Andric 
7209dba64beSDimitry Andric PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
721*0b57cec5SDimitry Andric   if (!m_main_module.IsValid())
7229dba64beSDimitry Andric     m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__"));
723*0b57cec5SDimitry Andric   return m_main_module;
724*0b57cec5SDimitry Andric }
725*0b57cec5SDimitry Andric 
726*0b57cec5SDimitry Andric PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
727*0b57cec5SDimitry Andric   if (m_session_dict.IsValid())
728*0b57cec5SDimitry Andric     return m_session_dict;
729*0b57cec5SDimitry Andric 
730*0b57cec5SDimitry Andric   PythonObject &main_module = GetMainModule();
731*0b57cec5SDimitry Andric   if (!main_module.IsValid())
732*0b57cec5SDimitry Andric     return m_session_dict;
733*0b57cec5SDimitry Andric 
734*0b57cec5SDimitry Andric   PythonDictionary main_dict(PyRefType::Borrowed,
735*0b57cec5SDimitry Andric                              PyModule_GetDict(main_module.get()));
736*0b57cec5SDimitry Andric   if (!main_dict.IsValid())
737*0b57cec5SDimitry Andric     return m_session_dict;
738*0b57cec5SDimitry Andric 
7399dba64beSDimitry Andric   m_session_dict = unwrapIgnoringErrors(
7409dba64beSDimitry Andric       As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
741*0b57cec5SDimitry Andric   return m_session_dict;
742*0b57cec5SDimitry Andric }
743*0b57cec5SDimitry Andric 
744*0b57cec5SDimitry Andric PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
745*0b57cec5SDimitry Andric   if (m_sys_module_dict.IsValid())
746*0b57cec5SDimitry Andric     return m_sys_module_dict;
7479dba64beSDimitry Andric   PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys"));
7489dba64beSDimitry Andric   m_sys_module_dict = sys_module.GetDictionary();
749*0b57cec5SDimitry Andric   return m_sys_module_dict;
750*0b57cec5SDimitry Andric }
751*0b57cec5SDimitry Andric 
752480093f4SDimitry Andric llvm::Expected<unsigned>
753480093f4SDimitry Andric ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
754480093f4SDimitry Andric     const llvm::StringRef &callable_name) {
755480093f4SDimitry Andric   if (callable_name.empty()) {
756480093f4SDimitry Andric     return llvm::createStringError(
757480093f4SDimitry Andric         llvm::inconvertibleErrorCode(),
758480093f4SDimitry Andric         "called with empty callable name.");
759480093f4SDimitry Andric   }
760480093f4SDimitry Andric   Locker py_lock(this, Locker::AcquireLock |
761480093f4SDimitry Andric                  Locker::InitSession |
762480093f4SDimitry Andric                  Locker::NoSTDIN);
763480093f4SDimitry Andric   auto dict = PythonModule::MainModule()
764480093f4SDimitry Andric       .ResolveName<PythonDictionary>(m_dictionary_name);
765480093f4SDimitry Andric   auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
766480093f4SDimitry Andric       callable_name, dict);
767480093f4SDimitry Andric   if (!pfunc.IsAllocated()) {
768480093f4SDimitry Andric     return llvm::createStringError(
769480093f4SDimitry Andric         llvm::inconvertibleErrorCode(),
770480093f4SDimitry Andric         "can't find callable: %s", callable_name.str().c_str());
771480093f4SDimitry Andric   }
772480093f4SDimitry Andric   llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
773480093f4SDimitry Andric   if (!arg_info)
774480093f4SDimitry Andric     return arg_info.takeError();
775480093f4SDimitry Andric   return arg_info.get().max_positional_args;
776480093f4SDimitry Andric }
777480093f4SDimitry Andric 
778*0b57cec5SDimitry Andric static std::string GenerateUniqueName(const char *base_name_wanted,
779*0b57cec5SDimitry Andric                                       uint32_t &functions_counter,
780*0b57cec5SDimitry Andric                                       const void *name_token = nullptr) {
781*0b57cec5SDimitry Andric   StreamString sstr;
782*0b57cec5SDimitry Andric 
783*0b57cec5SDimitry Andric   if (!base_name_wanted)
784*0b57cec5SDimitry Andric     return std::string();
785*0b57cec5SDimitry Andric 
786*0b57cec5SDimitry Andric   if (!name_token)
787*0b57cec5SDimitry Andric     sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
788*0b57cec5SDimitry Andric   else
789*0b57cec5SDimitry Andric     sstr.Printf("%s_%p", base_name_wanted, name_token);
790*0b57cec5SDimitry Andric 
7915ffd83dbSDimitry Andric   return std::string(sstr.GetString());
792*0b57cec5SDimitry Andric }
793*0b57cec5SDimitry Andric 
794*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
795*0b57cec5SDimitry Andric   if (m_run_one_line_function.IsValid())
796*0b57cec5SDimitry Andric     return true;
797*0b57cec5SDimitry Andric 
798*0b57cec5SDimitry Andric   PythonObject module(PyRefType::Borrowed,
799*0b57cec5SDimitry Andric                       PyImport_AddModule("lldb.embedded_interpreter"));
800*0b57cec5SDimitry Andric   if (!module.IsValid())
801*0b57cec5SDimitry Andric     return false;
802*0b57cec5SDimitry Andric 
803*0b57cec5SDimitry Andric   PythonDictionary module_dict(PyRefType::Borrowed,
804*0b57cec5SDimitry Andric                                PyModule_GetDict(module.get()));
805*0b57cec5SDimitry Andric   if (!module_dict.IsValid())
806*0b57cec5SDimitry Andric     return false;
807*0b57cec5SDimitry Andric 
808*0b57cec5SDimitry Andric   m_run_one_line_function =
809*0b57cec5SDimitry Andric       module_dict.GetItemForKey(PythonString("run_one_line"));
810*0b57cec5SDimitry Andric   m_run_one_line_str_global =
811*0b57cec5SDimitry Andric       module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
812*0b57cec5SDimitry Andric   return m_run_one_line_function.IsValid();
813*0b57cec5SDimitry Andric }
814*0b57cec5SDimitry Andric 
815*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ExecuteOneLine(
816*0b57cec5SDimitry Andric     llvm::StringRef command, CommandReturnObject *result,
817*0b57cec5SDimitry Andric     const ExecuteScriptOptions &options) {
818*0b57cec5SDimitry Andric   std::string command_str = command.str();
819*0b57cec5SDimitry Andric 
820*0b57cec5SDimitry Andric   if (!m_valid_session)
821*0b57cec5SDimitry Andric     return false;
822*0b57cec5SDimitry Andric 
823*0b57cec5SDimitry Andric   if (!command.empty()) {
824*0b57cec5SDimitry Andric     // We want to call run_one_line, passing in the dictionary and the command
825*0b57cec5SDimitry Andric     // string.  We cannot do this through PyRun_SimpleString here because the
826*0b57cec5SDimitry Andric     // command string may contain escaped characters, and putting it inside
827*0b57cec5SDimitry Andric     // another string to pass to PyRun_SimpleString messes up the escaping.  So
828*0b57cec5SDimitry Andric     // we use the following more complicated method to pass the command string
829*0b57cec5SDimitry Andric     // directly down to Python.
8305ffd83dbSDimitry Andric     llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
8315ffd83dbSDimitry Andric         io_redirect_or_error = ScriptInterpreterIORedirect::Create(
8325ffd83dbSDimitry Andric             options.GetEnableIO(), m_debugger, result);
8335ffd83dbSDimitry Andric     if (!io_redirect_or_error) {
8345ffd83dbSDimitry Andric       if (result)
8355ffd83dbSDimitry Andric         result->AppendErrorWithFormatv(
8365ffd83dbSDimitry Andric             "failed to redirect I/O: {0}\n",
8375ffd83dbSDimitry Andric             llvm::fmt_consume(io_redirect_or_error.takeError()));
8385ffd83dbSDimitry Andric       else
8395ffd83dbSDimitry Andric         llvm::consumeError(io_redirect_or_error.takeError());
8409dba64beSDimitry Andric       return false;
8419dba64beSDimitry Andric     }
8425ffd83dbSDimitry Andric 
8435ffd83dbSDimitry Andric     ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
844*0b57cec5SDimitry Andric 
845*0b57cec5SDimitry Andric     bool success = false;
846*0b57cec5SDimitry Andric     {
847*0b57cec5SDimitry Andric       // WARNING!  It's imperative that this RAII scope be as tight as
848*0b57cec5SDimitry Andric       // possible. In particular, the scope must end *before* we try to join
849*0b57cec5SDimitry Andric       // the read thread.  The reason for this is that a pre-requisite for
850*0b57cec5SDimitry Andric       // joining the read thread is that we close the write handle (to break
851*0b57cec5SDimitry Andric       // the pipe and cause it to wake up and exit).  But acquiring the GIL as
852*0b57cec5SDimitry Andric       // below will redirect Python's stdio to use this same handle.  If we
853*0b57cec5SDimitry Andric       // close the handle while Python is still using it, bad things will
854*0b57cec5SDimitry Andric       // happen.
855*0b57cec5SDimitry Andric       Locker locker(
856*0b57cec5SDimitry Andric           this,
857*0b57cec5SDimitry Andric           Locker::AcquireLock | Locker::InitSession |
858*0b57cec5SDimitry Andric               (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
859*0b57cec5SDimitry Andric               ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
8605ffd83dbSDimitry Andric           Locker::FreeAcquiredLock | Locker::TearDownSession,
8615ffd83dbSDimitry Andric           io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
8625ffd83dbSDimitry Andric           io_redirect.GetErrorFile());
863*0b57cec5SDimitry Andric 
864*0b57cec5SDimitry Andric       // Find the correct script interpreter dictionary in the main module.
865*0b57cec5SDimitry Andric       PythonDictionary &session_dict = GetSessionDictionary();
866*0b57cec5SDimitry Andric       if (session_dict.IsValid()) {
867*0b57cec5SDimitry Andric         if (GetEmbeddedInterpreterModuleObjects()) {
868*0b57cec5SDimitry Andric           if (PyCallable_Check(m_run_one_line_function.get())) {
869*0b57cec5SDimitry Andric             PythonObject pargs(
870*0b57cec5SDimitry Andric                 PyRefType::Owned,
871*0b57cec5SDimitry Andric                 Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
872*0b57cec5SDimitry Andric             if (pargs.IsValid()) {
873*0b57cec5SDimitry Andric               PythonObject return_value(
874*0b57cec5SDimitry Andric                   PyRefType::Owned,
875*0b57cec5SDimitry Andric                   PyObject_CallObject(m_run_one_line_function.get(),
876*0b57cec5SDimitry Andric                                       pargs.get()));
877*0b57cec5SDimitry Andric               if (return_value.IsValid())
878*0b57cec5SDimitry Andric                 success = true;
879*0b57cec5SDimitry Andric               else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
880*0b57cec5SDimitry Andric                 PyErr_Print();
881*0b57cec5SDimitry Andric                 PyErr_Clear();
882*0b57cec5SDimitry Andric               }
883*0b57cec5SDimitry Andric             }
884*0b57cec5SDimitry Andric           }
885*0b57cec5SDimitry Andric         }
886*0b57cec5SDimitry Andric       }
887*0b57cec5SDimitry Andric 
8885ffd83dbSDimitry Andric       io_redirect.Flush();
889*0b57cec5SDimitry Andric     }
890*0b57cec5SDimitry Andric 
891*0b57cec5SDimitry Andric     if (success)
892*0b57cec5SDimitry Andric       return true;
893*0b57cec5SDimitry Andric 
894*0b57cec5SDimitry Andric     // The one-liner failed.  Append the error message.
895*0b57cec5SDimitry Andric     if (result) {
896*0b57cec5SDimitry Andric       result->AppendErrorWithFormat(
897*0b57cec5SDimitry Andric           "python failed attempting to evaluate '%s'\n", command_str.c_str());
898*0b57cec5SDimitry Andric     }
899*0b57cec5SDimitry Andric     return false;
900*0b57cec5SDimitry Andric   }
901*0b57cec5SDimitry Andric 
902*0b57cec5SDimitry Andric   if (result)
903*0b57cec5SDimitry Andric     result->AppendError("empty command passed to python\n");
904*0b57cec5SDimitry Andric   return false;
905*0b57cec5SDimitry Andric }
906*0b57cec5SDimitry Andric 
907*0b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
908e8d8bef9SDimitry Andric   LLDB_SCOPED_TIMER();
909*0b57cec5SDimitry Andric 
910*0b57cec5SDimitry Andric   Debugger &debugger = m_debugger;
911*0b57cec5SDimitry Andric 
912*0b57cec5SDimitry Andric   // At the moment, the only time the debugger does not have an input file
913*0b57cec5SDimitry Andric   // handle is when this is called directly from Python, in which case it is
914*0b57cec5SDimitry Andric   // both dangerous and unnecessary (not to mention confusing) to try to embed
915*0b57cec5SDimitry Andric   // a running interpreter loop inside the already running Python interpreter
916*0b57cec5SDimitry Andric   // loop, so we won't do it.
917*0b57cec5SDimitry Andric 
9189dba64beSDimitry Andric   if (!debugger.GetInputFile().IsValid())
919*0b57cec5SDimitry Andric     return;
920*0b57cec5SDimitry Andric 
921*0b57cec5SDimitry Andric   IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
922*0b57cec5SDimitry Andric   if (io_handler_sp) {
9235ffd83dbSDimitry Andric     debugger.RunIOHandlerAsync(io_handler_sp);
924*0b57cec5SDimitry Andric   }
925*0b57cec5SDimitry Andric }
926*0b57cec5SDimitry Andric 
927*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Interrupt() {
92804eeddc0SDimitry Andric #if LLDB_USE_PYTHON_SET_INTERRUPT
92904eeddc0SDimitry Andric   // If the interpreter isn't evaluating any Python at the moment then return
93004eeddc0SDimitry Andric   // false to signal that this function didn't handle the interrupt and the
93104eeddc0SDimitry Andric   // next component should try handling it.
93204eeddc0SDimitry Andric   if (!IsExecutingPython())
93304eeddc0SDimitry Andric     return false;
93404eeddc0SDimitry Andric 
93504eeddc0SDimitry Andric   // Tell Python that it should pretend to have received a SIGINT.
93604eeddc0SDimitry Andric   PyErr_SetInterrupt();
93704eeddc0SDimitry Andric   // PyErr_SetInterrupt has no way to return an error so we can only pretend the
93804eeddc0SDimitry Andric   // signal got successfully handled and return true.
93904eeddc0SDimitry Andric   // Python 3.10 introduces PyErr_SetInterruptEx that could return an error, but
94004eeddc0SDimitry Andric   // the error handling is limited to checking the arguments which would be
94104eeddc0SDimitry Andric   // just our (hardcoded) input signal code SIGINT, so that's not useful at all.
94204eeddc0SDimitry Andric   return true;
94304eeddc0SDimitry Andric #else
94481ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Script);
945*0b57cec5SDimitry Andric 
946*0b57cec5SDimitry Andric   if (IsExecutingPython()) {
947*0b57cec5SDimitry Andric     PyThreadState *state = PyThreadState_GET();
948*0b57cec5SDimitry Andric     if (!state)
949*0b57cec5SDimitry Andric       state = GetThreadState();
950*0b57cec5SDimitry Andric     if (state) {
951*0b57cec5SDimitry Andric       long tid = state->thread_id;
952*0b57cec5SDimitry Andric       PyThreadState_Swap(state);
953*0b57cec5SDimitry Andric       int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
9549dba64beSDimitry Andric       LLDB_LOGF(log,
9559dba64beSDimitry Andric                 "ScriptInterpreterPythonImpl::Interrupt() sending "
956*0b57cec5SDimitry Andric                 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
957*0b57cec5SDimitry Andric                 tid, num_threads);
958*0b57cec5SDimitry Andric       return true;
959*0b57cec5SDimitry Andric     }
960*0b57cec5SDimitry Andric   }
9619dba64beSDimitry Andric   LLDB_LOGF(log,
962*0b57cec5SDimitry Andric             "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
963*0b57cec5SDimitry Andric             "can't interrupt");
964*0b57cec5SDimitry Andric   return false;
96504eeddc0SDimitry Andric #endif
966*0b57cec5SDimitry Andric }
9679dba64beSDimitry Andric 
968*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
969*0b57cec5SDimitry Andric     llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
970*0b57cec5SDimitry Andric     void *ret_value, const ExecuteScriptOptions &options) {
971*0b57cec5SDimitry Andric 
972fe6060f1SDimitry Andric   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
973fe6060f1SDimitry Andric       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
974fe6060f1SDimitry Andric           options.GetEnableIO(), m_debugger, /*result=*/nullptr);
975fe6060f1SDimitry Andric 
976fe6060f1SDimitry Andric   if (!io_redirect_or_error) {
977fe6060f1SDimitry Andric     llvm::consumeError(io_redirect_or_error.takeError());
978fe6060f1SDimitry Andric     return false;
979fe6060f1SDimitry Andric   }
980fe6060f1SDimitry Andric 
981fe6060f1SDimitry Andric   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
982fe6060f1SDimitry Andric 
983*0b57cec5SDimitry Andric   Locker locker(this,
984*0b57cec5SDimitry Andric                 Locker::AcquireLock | Locker::InitSession |
985*0b57cec5SDimitry Andric                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
986*0b57cec5SDimitry Andric                     Locker::NoSTDIN,
987fe6060f1SDimitry Andric                 Locker::FreeAcquiredLock | Locker::TearDownSession,
988fe6060f1SDimitry Andric                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
989fe6060f1SDimitry Andric                 io_redirect.GetErrorFile());
990*0b57cec5SDimitry Andric 
9919dba64beSDimitry Andric   PythonModule &main_module = GetMainModule();
9929dba64beSDimitry Andric   PythonDictionary globals = main_module.GetDictionary();
993*0b57cec5SDimitry Andric 
994*0b57cec5SDimitry Andric   PythonDictionary locals = GetSessionDictionary();
9959dba64beSDimitry Andric   if (!locals.IsValid())
9969dba64beSDimitry Andric     locals = unwrapIgnoringErrors(
9979dba64beSDimitry Andric         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
998*0b57cec5SDimitry Andric   if (!locals.IsValid())
999*0b57cec5SDimitry Andric     locals = globals;
1000*0b57cec5SDimitry Andric 
10019dba64beSDimitry Andric   Expected<PythonObject> maybe_py_return =
10029dba64beSDimitry Andric       runStringOneLine(in_string, globals, locals);
1003*0b57cec5SDimitry Andric 
10049dba64beSDimitry Andric   if (!maybe_py_return) {
10059dba64beSDimitry Andric     llvm::handleAllErrors(
10069dba64beSDimitry Andric         maybe_py_return.takeError(),
10079dba64beSDimitry Andric         [&](PythonException &E) {
10089dba64beSDimitry Andric           E.Restore();
10099dba64beSDimitry Andric           if (options.GetMaskoutErrors()) {
10109dba64beSDimitry Andric             if (E.Matches(PyExc_SyntaxError)) {
10119dba64beSDimitry Andric               PyErr_Print();
1012*0b57cec5SDimitry Andric             }
10139dba64beSDimitry Andric             PyErr_Clear();
10149dba64beSDimitry Andric           }
10159dba64beSDimitry Andric         },
10169dba64beSDimitry Andric         [](const llvm::ErrorInfoBase &E) {});
10179dba64beSDimitry Andric     return false;
1018*0b57cec5SDimitry Andric   }
1019*0b57cec5SDimitry Andric 
10209dba64beSDimitry Andric   PythonObject py_return = std::move(maybe_py_return.get());
10219dba64beSDimitry Andric   assert(py_return.IsValid());
10229dba64beSDimitry Andric 
1023*0b57cec5SDimitry Andric   switch (return_type) {
1024*0b57cec5SDimitry Andric   case eScriptReturnTypeCharPtr: // "char *"
1025*0b57cec5SDimitry Andric   {
1026*0b57cec5SDimitry Andric     const char format[3] = "s#";
10279dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
1028*0b57cec5SDimitry Andric   }
1029*0b57cec5SDimitry Andric   case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
1030*0b57cec5SDimitry Andric                                        // Py_None
1031*0b57cec5SDimitry Andric   {
1032*0b57cec5SDimitry Andric     const char format[3] = "z";
10339dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
1034*0b57cec5SDimitry Andric   }
1035*0b57cec5SDimitry Andric   case eScriptReturnTypeBool: {
1036*0b57cec5SDimitry Andric     const char format[2] = "b";
10379dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
1038*0b57cec5SDimitry Andric   }
1039*0b57cec5SDimitry Andric   case eScriptReturnTypeShortInt: {
1040*0b57cec5SDimitry Andric     const char format[2] = "h";
10419dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (short *)ret_value);
1042*0b57cec5SDimitry Andric   }
1043*0b57cec5SDimitry Andric   case eScriptReturnTypeShortIntUnsigned: {
1044*0b57cec5SDimitry Andric     const char format[2] = "H";
10459dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
1046*0b57cec5SDimitry Andric   }
1047*0b57cec5SDimitry Andric   case eScriptReturnTypeInt: {
1048*0b57cec5SDimitry Andric     const char format[2] = "i";
10499dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (int *)ret_value);
1050*0b57cec5SDimitry Andric   }
1051*0b57cec5SDimitry Andric   case eScriptReturnTypeIntUnsigned: {
1052*0b57cec5SDimitry Andric     const char format[2] = "I";
10539dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
1054*0b57cec5SDimitry Andric   }
1055*0b57cec5SDimitry Andric   case eScriptReturnTypeLongInt: {
1056*0b57cec5SDimitry Andric     const char format[2] = "l";
10579dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (long *)ret_value);
1058*0b57cec5SDimitry Andric   }
1059*0b57cec5SDimitry Andric   case eScriptReturnTypeLongIntUnsigned: {
1060*0b57cec5SDimitry Andric     const char format[2] = "k";
10619dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
1062*0b57cec5SDimitry Andric   }
1063*0b57cec5SDimitry Andric   case eScriptReturnTypeLongLong: {
1064*0b57cec5SDimitry Andric     const char format[2] = "L";
10659dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
1066*0b57cec5SDimitry Andric   }
1067*0b57cec5SDimitry Andric   case eScriptReturnTypeLongLongUnsigned: {
1068*0b57cec5SDimitry Andric     const char format[2] = "K";
10699dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format,
10709dba64beSDimitry Andric                        (unsigned long long *)ret_value);
1071*0b57cec5SDimitry Andric   }
1072*0b57cec5SDimitry Andric   case eScriptReturnTypeFloat: {
1073*0b57cec5SDimitry Andric     const char format[2] = "f";
10749dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (float *)ret_value);
1075*0b57cec5SDimitry Andric   }
1076*0b57cec5SDimitry Andric   case eScriptReturnTypeDouble: {
1077*0b57cec5SDimitry Andric     const char format[2] = "d";
10789dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (double *)ret_value);
1079*0b57cec5SDimitry Andric   }
1080*0b57cec5SDimitry Andric   case eScriptReturnTypeChar: {
1081*0b57cec5SDimitry Andric     const char format[2] = "c";
10829dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (char *)ret_value);
1083*0b57cec5SDimitry Andric   }
1084*0b57cec5SDimitry Andric   case eScriptReturnTypeOpaqueObject: {
10859dba64beSDimitry Andric     *((PyObject **)ret_value) = py_return.release();
10869dba64beSDimitry Andric     return true;
1087*0b57cec5SDimitry Andric   }
1088*0b57cec5SDimitry Andric   }
1089480093f4SDimitry Andric   llvm_unreachable("Fully covered switch!");
1090*0b57cec5SDimitry Andric }
1091*0b57cec5SDimitry Andric 
1092*0b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1093*0b57cec5SDimitry Andric     const char *in_string, const ExecuteScriptOptions &options) {
10949dba64beSDimitry Andric 
10959dba64beSDimitry Andric   if (in_string == nullptr)
10969dba64beSDimitry Andric     return Status();
1097*0b57cec5SDimitry Andric 
1098fe6060f1SDimitry Andric   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1099fe6060f1SDimitry Andric       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1100fe6060f1SDimitry Andric           options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1101fe6060f1SDimitry Andric 
1102fe6060f1SDimitry Andric   if (!io_redirect_or_error)
1103fe6060f1SDimitry Andric     return Status(io_redirect_or_error.takeError());
1104fe6060f1SDimitry Andric 
1105fe6060f1SDimitry Andric   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1106fe6060f1SDimitry Andric 
1107*0b57cec5SDimitry Andric   Locker locker(this,
1108*0b57cec5SDimitry Andric                 Locker::AcquireLock | Locker::InitSession |
1109*0b57cec5SDimitry Andric                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1110*0b57cec5SDimitry Andric                     Locker::NoSTDIN,
1111fe6060f1SDimitry Andric                 Locker::FreeAcquiredLock | Locker::TearDownSession,
1112fe6060f1SDimitry Andric                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1113fe6060f1SDimitry Andric                 io_redirect.GetErrorFile());
1114*0b57cec5SDimitry Andric 
11159dba64beSDimitry Andric   PythonModule &main_module = GetMainModule();
11169dba64beSDimitry Andric   PythonDictionary globals = main_module.GetDictionary();
1117*0b57cec5SDimitry Andric 
1118*0b57cec5SDimitry Andric   PythonDictionary locals = GetSessionDictionary();
1119*0b57cec5SDimitry Andric   if (!locals.IsValid())
11209dba64beSDimitry Andric     locals = unwrapIgnoringErrors(
11219dba64beSDimitry Andric         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1122*0b57cec5SDimitry Andric   if (!locals.IsValid())
1123*0b57cec5SDimitry Andric     locals = globals;
1124*0b57cec5SDimitry Andric 
11259dba64beSDimitry Andric   Expected<PythonObject> return_value =
11269dba64beSDimitry Andric       runStringMultiLine(in_string, globals, locals);
1127*0b57cec5SDimitry Andric 
11289dba64beSDimitry Andric   if (!return_value) {
11299dba64beSDimitry Andric     llvm::Error error =
11309dba64beSDimitry Andric         llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
11319dba64beSDimitry Andric           llvm::Error error = llvm::createStringError(
11329dba64beSDimitry Andric               llvm::inconvertibleErrorCode(), E.ReadBacktrace());
11339dba64beSDimitry Andric           if (!options.GetMaskoutErrors())
11349dba64beSDimitry Andric             E.Restore();
1135*0b57cec5SDimitry Andric           return error;
11369dba64beSDimitry Andric         });
11379dba64beSDimitry Andric     return Status(std::move(error));
11389dba64beSDimitry Andric   }
11399dba64beSDimitry Andric 
11409dba64beSDimitry Andric   return Status();
1141*0b57cec5SDimitry Andric }
1142*0b57cec5SDimitry Andric 
1143*0b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1144fe6060f1SDimitry Andric     std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1145*0b57cec5SDimitry Andric     CommandReturnObject &result) {
1146*0b57cec5SDimitry Andric   m_active_io_handler = eIOHandlerBreakpoint;
1147*0b57cec5SDimitry Andric   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1148480093f4SDimitry Andric       "    ", *this, &bp_options_vec);
1149*0b57cec5SDimitry Andric }
1150*0b57cec5SDimitry Andric 
1151*0b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1152*0b57cec5SDimitry Andric     WatchpointOptions *wp_options, CommandReturnObject &result) {
1153*0b57cec5SDimitry Andric   m_active_io_handler = eIOHandlerWatchpoint;
1154*0b57cec5SDimitry Andric   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1155480093f4SDimitry Andric       "    ", *this, wp_options);
1156*0b57cec5SDimitry Andric }
1157*0b57cec5SDimitry Andric 
1158480093f4SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1159fe6060f1SDimitry Andric     BreakpointOptions &bp_options, const char *function_name,
1160480093f4SDimitry Andric     StructuredData::ObjectSP extra_args_sp) {
1161480093f4SDimitry Andric   Status error;
1162*0b57cec5SDimitry Andric   // For now just cons up a oneliner that calls the provided function.
1163*0b57cec5SDimitry Andric   std::string oneliner("return ");
1164*0b57cec5SDimitry Andric   oneliner += function_name;
1165480093f4SDimitry Andric 
1166480093f4SDimitry Andric   llvm::Expected<unsigned> maybe_args =
1167480093f4SDimitry Andric       GetMaxPositionalArgumentsForCallable(function_name);
1168480093f4SDimitry Andric   if (!maybe_args) {
1169480093f4SDimitry Andric     error.SetErrorStringWithFormat(
1170480093f4SDimitry Andric         "could not get num args: %s",
1171480093f4SDimitry Andric         llvm::toString(maybe_args.takeError()).c_str());
1172480093f4SDimitry Andric     return error;
1173480093f4SDimitry Andric   }
1174480093f4SDimitry Andric   size_t max_args = *maybe_args;
1175480093f4SDimitry Andric 
1176480093f4SDimitry Andric   bool uses_extra_args = false;
1177480093f4SDimitry Andric   if (max_args >= 4) {
1178480093f4SDimitry Andric     uses_extra_args = true;
1179480093f4SDimitry Andric     oneliner += "(frame, bp_loc, extra_args, internal_dict)";
1180480093f4SDimitry Andric   } else if (max_args >= 3) {
1181480093f4SDimitry Andric     if (extra_args_sp) {
1182480093f4SDimitry Andric       error.SetErrorString("cannot pass extra_args to a three argument callback"
1183480093f4SDimitry Andric                           );
1184480093f4SDimitry Andric       return error;
1185480093f4SDimitry Andric     }
1186480093f4SDimitry Andric     uses_extra_args = false;
1187*0b57cec5SDimitry Andric     oneliner += "(frame, bp_loc, internal_dict)";
1188480093f4SDimitry Andric   } else {
1189480093f4SDimitry Andric     error.SetErrorStringWithFormat("expected 3 or 4 argument "
1190480093f4SDimitry Andric                                    "function, %s can only take %zu",
1191480093f4SDimitry Andric                                    function_name, max_args);
1192480093f4SDimitry Andric     return error;
1193480093f4SDimitry Andric   }
1194480093f4SDimitry Andric 
1195480093f4SDimitry Andric   SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp,
1196480093f4SDimitry Andric                                uses_extra_args);
1197480093f4SDimitry Andric   return error;
1198*0b57cec5SDimitry Andric }
1199*0b57cec5SDimitry Andric 
1200*0b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1201fe6060f1SDimitry Andric     BreakpointOptions &bp_options,
1202*0b57cec5SDimitry Andric     std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
1203*0b57cec5SDimitry Andric   Status error;
1204*0b57cec5SDimitry Andric   error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1205480093f4SDimitry Andric                                                 cmd_data_up->script_source,
1206480093f4SDimitry Andric                                                 false);
1207*0b57cec5SDimitry Andric   if (error.Fail()) {
1208*0b57cec5SDimitry Andric     return error;
1209*0b57cec5SDimitry Andric   }
1210*0b57cec5SDimitry Andric   auto baton_sp =
1211*0b57cec5SDimitry Andric       std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1212fe6060f1SDimitry Andric   bp_options.SetCallback(
1213*0b57cec5SDimitry Andric       ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1214*0b57cec5SDimitry Andric   return error;
1215*0b57cec5SDimitry Andric }
1216*0b57cec5SDimitry Andric 
1217*0b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1218fe6060f1SDimitry Andric     BreakpointOptions &bp_options, const char *command_body_text) {
1219480093f4SDimitry Andric   return SetBreakpointCommandCallback(bp_options, command_body_text, {},false);
1220480093f4SDimitry Andric }
1221*0b57cec5SDimitry Andric 
1222480093f4SDimitry Andric // Set a Python one-liner as the callback for the breakpoint.
1223480093f4SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1224fe6060f1SDimitry Andric     BreakpointOptions &bp_options, const char *command_body_text,
1225fe6060f1SDimitry Andric     StructuredData::ObjectSP extra_args_sp, bool uses_extra_args) {
1226480093f4SDimitry Andric   auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1227*0b57cec5SDimitry Andric   // Split the command_body_text into lines, and pass that to
1228*0b57cec5SDimitry Andric   // GenerateBreakpointCommandCallbackData.  That will wrap the body in an
1229*0b57cec5SDimitry Andric   // auto-generated function, and return the function name in script_source.
1230*0b57cec5SDimitry Andric   // That is what the callback will actually invoke.
1231*0b57cec5SDimitry Andric 
1232*0b57cec5SDimitry Andric   data_up->user_source.SplitIntoLines(command_body_text);
1233*0b57cec5SDimitry Andric   Status error = GenerateBreakpointCommandCallbackData(data_up->user_source,
1234480093f4SDimitry Andric                                                        data_up->script_source,
1235480093f4SDimitry Andric                                                        uses_extra_args);
1236*0b57cec5SDimitry Andric   if (error.Success()) {
1237*0b57cec5SDimitry Andric     auto baton_sp =
1238*0b57cec5SDimitry Andric         std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1239fe6060f1SDimitry Andric     bp_options.SetCallback(
1240*0b57cec5SDimitry Andric         ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1241*0b57cec5SDimitry Andric     return error;
12425ffd83dbSDimitry Andric   }
1243*0b57cec5SDimitry Andric   return error;
1244*0b57cec5SDimitry Andric }
1245*0b57cec5SDimitry Andric 
1246*0b57cec5SDimitry Andric // Set a Python one-liner as the callback for the watchpoint.
1247*0b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1248*0b57cec5SDimitry Andric     WatchpointOptions *wp_options, const char *oneliner) {
12499dba64beSDimitry Andric   auto data_up = std::make_unique<WatchpointOptions::CommandData>();
1250*0b57cec5SDimitry Andric 
1251*0b57cec5SDimitry Andric   // It's necessary to set both user_source and script_source to the oneliner.
1252*0b57cec5SDimitry Andric   // The former is used to generate callback description (as in watchpoint
1253*0b57cec5SDimitry Andric   // command list) while the latter is used for Python to interpret during the
1254*0b57cec5SDimitry Andric   // actual callback.
1255*0b57cec5SDimitry Andric 
1256*0b57cec5SDimitry Andric   data_up->user_source.AppendString(oneliner);
1257*0b57cec5SDimitry Andric   data_up->script_source.assign(oneliner);
1258*0b57cec5SDimitry Andric 
1259*0b57cec5SDimitry Andric   if (GenerateWatchpointCommandCallbackData(data_up->user_source,
1260*0b57cec5SDimitry Andric                                             data_up->script_source)) {
1261*0b57cec5SDimitry Andric     auto baton_sp =
1262*0b57cec5SDimitry Andric         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
1263*0b57cec5SDimitry Andric     wp_options->SetCallback(
1264*0b57cec5SDimitry Andric         ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
1265*0b57cec5SDimitry Andric   }
1266*0b57cec5SDimitry Andric }
1267*0b57cec5SDimitry Andric 
1268*0b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1269*0b57cec5SDimitry Andric     StringList &function_def) {
1270*0b57cec5SDimitry Andric   // Convert StringList to one long, newline delimited, const char *.
1271*0b57cec5SDimitry Andric   std::string function_def_string(function_def.CopyList());
1272*0b57cec5SDimitry Andric 
1273*0b57cec5SDimitry Andric   Status error = ExecuteMultipleLines(
1274*0b57cec5SDimitry Andric       function_def_string.c_str(),
1275fe6060f1SDimitry Andric       ExecuteScriptOptions().SetEnableIO(false));
1276*0b57cec5SDimitry Andric   return error;
1277*0b57cec5SDimitry Andric }
1278*0b57cec5SDimitry Andric 
1279*0b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature,
1280*0b57cec5SDimitry Andric                                                      const StringList &input) {
1281*0b57cec5SDimitry Andric   Status error;
1282*0b57cec5SDimitry Andric   int num_lines = input.GetSize();
1283*0b57cec5SDimitry Andric   if (num_lines == 0) {
1284*0b57cec5SDimitry Andric     error.SetErrorString("No input data.");
1285*0b57cec5SDimitry Andric     return error;
1286*0b57cec5SDimitry Andric   }
1287*0b57cec5SDimitry Andric 
1288*0b57cec5SDimitry Andric   if (!signature || *signature == 0) {
1289*0b57cec5SDimitry Andric     error.SetErrorString("No output function name.");
1290*0b57cec5SDimitry Andric     return error;
1291*0b57cec5SDimitry Andric   }
1292*0b57cec5SDimitry Andric 
1293*0b57cec5SDimitry Andric   StreamString sstr;
1294*0b57cec5SDimitry Andric   StringList auto_generated_function;
1295*0b57cec5SDimitry Andric   auto_generated_function.AppendString(signature);
1296*0b57cec5SDimitry Andric   auto_generated_function.AppendString(
1297*0b57cec5SDimitry Andric       "     global_dict = globals()"); // Grab the global dictionary
1298*0b57cec5SDimitry Andric   auto_generated_function.AppendString(
1299*0b57cec5SDimitry Andric       "     new_keys = internal_dict.keys()"); // Make a list of keys in the
1300*0b57cec5SDimitry Andric                                                // session dict
1301*0b57cec5SDimitry Andric   auto_generated_function.AppendString(
1302*0b57cec5SDimitry Andric       "     old_keys = global_dict.keys()"); // Save list of keys in global dict
1303*0b57cec5SDimitry Andric   auto_generated_function.AppendString(
1304*0b57cec5SDimitry Andric       "     global_dict.update (internal_dict)"); // Add the session dictionary
1305*0b57cec5SDimitry Andric                                                   // to the
1306*0b57cec5SDimitry Andric   // global dictionary.
1307*0b57cec5SDimitry Andric 
1308*0b57cec5SDimitry Andric   // Wrap everything up inside the function, increasing the indentation.
1309*0b57cec5SDimitry Andric 
1310*0b57cec5SDimitry Andric   auto_generated_function.AppendString("     if True:");
1311*0b57cec5SDimitry Andric   for (int i = 0; i < num_lines; ++i) {
1312*0b57cec5SDimitry Andric     sstr.Clear();
1313*0b57cec5SDimitry Andric     sstr.Printf("       %s", input.GetStringAtIndex(i));
1314*0b57cec5SDimitry Andric     auto_generated_function.AppendString(sstr.GetData());
1315*0b57cec5SDimitry Andric   }
1316*0b57cec5SDimitry Andric   auto_generated_function.AppendString(
1317*0b57cec5SDimitry Andric       "     for key in new_keys:"); // Iterate over all the keys from session
1318*0b57cec5SDimitry Andric                                     // dict
1319*0b57cec5SDimitry Andric   auto_generated_function.AppendString(
1320*0b57cec5SDimitry Andric       "         internal_dict[key] = global_dict[key]"); // Update session dict
1321*0b57cec5SDimitry Andric                                                          // values
1322*0b57cec5SDimitry Andric   auto_generated_function.AppendString(
1323*0b57cec5SDimitry Andric       "         if key not in old_keys:"); // If key was not originally in
1324*0b57cec5SDimitry Andric                                            // global dict
1325*0b57cec5SDimitry Andric   auto_generated_function.AppendString(
1326*0b57cec5SDimitry Andric       "             del global_dict[key]"); //  ...then remove key/value from
1327*0b57cec5SDimitry Andric                                             //  global dict
1328*0b57cec5SDimitry Andric 
1329*0b57cec5SDimitry Andric   // Verify that the results are valid Python.
1330*0b57cec5SDimitry Andric 
1331*0b57cec5SDimitry Andric   error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
1332*0b57cec5SDimitry Andric 
1333*0b57cec5SDimitry Andric   return error;
1334*0b57cec5SDimitry Andric }
1335*0b57cec5SDimitry Andric 
1336*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1337*0b57cec5SDimitry Andric     StringList &user_input, std::string &output, const void *name_token) {
1338*0b57cec5SDimitry Andric   static uint32_t num_created_functions = 0;
1339*0b57cec5SDimitry Andric   user_input.RemoveBlankLines();
1340*0b57cec5SDimitry Andric   StreamString sstr;
1341*0b57cec5SDimitry Andric 
1342*0b57cec5SDimitry Andric   // Check to see if we have any data; if not, just return.
1343*0b57cec5SDimitry Andric   if (user_input.GetSize() == 0)
1344*0b57cec5SDimitry Andric     return false;
1345*0b57cec5SDimitry Andric 
1346*0b57cec5SDimitry Andric   // Take what the user wrote, wrap it all up inside one big auto-generated
1347*0b57cec5SDimitry Andric   // Python function, passing in the ValueObject as parameter to the function.
1348*0b57cec5SDimitry Andric 
1349*0b57cec5SDimitry Andric   std::string auto_generated_function_name(
1350*0b57cec5SDimitry Andric       GenerateUniqueName("lldb_autogen_python_type_print_func",
1351*0b57cec5SDimitry Andric                          num_created_functions, name_token));
1352*0b57cec5SDimitry Andric   sstr.Printf("def %s (valobj, internal_dict):",
1353*0b57cec5SDimitry Andric               auto_generated_function_name.c_str());
1354*0b57cec5SDimitry Andric 
1355*0b57cec5SDimitry Andric   if (!GenerateFunction(sstr.GetData(), user_input).Success())
1356*0b57cec5SDimitry Andric     return false;
1357*0b57cec5SDimitry Andric 
1358*0b57cec5SDimitry Andric   // Store the name of the auto-generated function to be called.
1359*0b57cec5SDimitry Andric   output.assign(auto_generated_function_name);
1360*0b57cec5SDimitry Andric   return true;
1361*0b57cec5SDimitry Andric }
1362*0b57cec5SDimitry Andric 
1363*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1364*0b57cec5SDimitry Andric     StringList &user_input, std::string &output) {
1365*0b57cec5SDimitry Andric   static uint32_t num_created_functions = 0;
1366*0b57cec5SDimitry Andric   user_input.RemoveBlankLines();
1367*0b57cec5SDimitry Andric   StreamString sstr;
1368*0b57cec5SDimitry Andric 
1369*0b57cec5SDimitry Andric   // Check to see if we have any data; if not, just return.
1370*0b57cec5SDimitry Andric   if (user_input.GetSize() == 0)
1371*0b57cec5SDimitry Andric     return false;
1372*0b57cec5SDimitry Andric 
1373*0b57cec5SDimitry Andric   std::string auto_generated_function_name(GenerateUniqueName(
1374*0b57cec5SDimitry Andric       "lldb_autogen_python_cmd_alias_func", num_created_functions));
1375*0b57cec5SDimitry Andric 
1376bdd1243dSDimitry Andric   sstr.Printf("def %s (debugger, args, exe_ctx, result, internal_dict):",
1377*0b57cec5SDimitry Andric               auto_generated_function_name.c_str());
1378*0b57cec5SDimitry Andric 
1379*0b57cec5SDimitry Andric   if (!GenerateFunction(sstr.GetData(), user_input).Success())
1380*0b57cec5SDimitry Andric     return false;
1381*0b57cec5SDimitry Andric 
1382*0b57cec5SDimitry Andric   // Store the name of the auto-generated function to be called.
1383*0b57cec5SDimitry Andric   output.assign(auto_generated_function_name);
1384*0b57cec5SDimitry Andric   return true;
1385*0b57cec5SDimitry Andric }
1386*0b57cec5SDimitry Andric 
1387*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1388*0b57cec5SDimitry Andric     StringList &user_input, std::string &output, const void *name_token) {
1389*0b57cec5SDimitry Andric   static uint32_t num_created_classes = 0;
1390*0b57cec5SDimitry Andric   user_input.RemoveBlankLines();
1391*0b57cec5SDimitry Andric   int num_lines = user_input.GetSize();
1392*0b57cec5SDimitry Andric   StreamString sstr;
1393*0b57cec5SDimitry Andric 
1394*0b57cec5SDimitry Andric   // Check to see if we have any data; if not, just return.
1395*0b57cec5SDimitry Andric   if (user_input.GetSize() == 0)
1396*0b57cec5SDimitry Andric     return false;
1397*0b57cec5SDimitry Andric 
1398*0b57cec5SDimitry Andric   // Wrap all user input into a Python class
1399*0b57cec5SDimitry Andric 
1400*0b57cec5SDimitry Andric   std::string auto_generated_class_name(GenerateUniqueName(
1401*0b57cec5SDimitry Andric       "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1402*0b57cec5SDimitry Andric 
1403*0b57cec5SDimitry Andric   StringList auto_generated_class;
1404*0b57cec5SDimitry Andric 
1405*0b57cec5SDimitry Andric   // Create the function name & definition string.
1406*0b57cec5SDimitry Andric 
1407*0b57cec5SDimitry Andric   sstr.Printf("class %s:", auto_generated_class_name.c_str());
1408*0b57cec5SDimitry Andric   auto_generated_class.AppendString(sstr.GetString());
1409*0b57cec5SDimitry Andric 
1410*0b57cec5SDimitry Andric   // Wrap everything up inside the class, increasing the indentation. we don't
1411*0b57cec5SDimitry Andric   // need to play any fancy indentation tricks here because there is no
1412*0b57cec5SDimitry Andric   // surrounding code whose indentation we need to honor
1413*0b57cec5SDimitry Andric   for (int i = 0; i < num_lines; ++i) {
1414*0b57cec5SDimitry Andric     sstr.Clear();
1415*0b57cec5SDimitry Andric     sstr.Printf("     %s", user_input.GetStringAtIndex(i));
1416*0b57cec5SDimitry Andric     auto_generated_class.AppendString(sstr.GetString());
1417*0b57cec5SDimitry Andric   }
1418*0b57cec5SDimitry Andric 
1419*0b57cec5SDimitry Andric   // Verify that the results are valid Python. (even though the method is
1420*0b57cec5SDimitry Andric   // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1421*0b57cec5SDimitry Andric   // (TODO: rename that method to ExportDefinitionToInterpreter)
1422*0b57cec5SDimitry Andric   if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
1423*0b57cec5SDimitry Andric     return false;
1424*0b57cec5SDimitry Andric 
1425*0b57cec5SDimitry Andric   // Store the name of the auto-generated class
1426*0b57cec5SDimitry Andric 
1427*0b57cec5SDimitry Andric   output.assign(auto_generated_class_name);
1428*0b57cec5SDimitry Andric   return true;
1429*0b57cec5SDimitry Andric }
1430*0b57cec5SDimitry Andric 
1431*0b57cec5SDimitry Andric StructuredData::GenericSP
1432*0b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
1433*0b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
1434*0b57cec5SDimitry Andric     return StructuredData::GenericSP();
1435*0b57cec5SDimitry Andric 
143604eeddc0SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
143704eeddc0SDimitry Andric   PythonObject ret_val = LLDBSWIGPython_CreateFrameRecognizer(
143804eeddc0SDimitry Andric       class_name, m_dictionary_name.c_str());
1439*0b57cec5SDimitry Andric 
144004eeddc0SDimitry Andric   return StructuredData::GenericSP(
144104eeddc0SDimitry Andric       new StructuredPythonObject(std::move(ret_val)));
1442*0b57cec5SDimitry Andric }
1443*0b57cec5SDimitry Andric 
1444*0b57cec5SDimitry Andric lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
1445*0b57cec5SDimitry Andric     const StructuredData::ObjectSP &os_plugin_object_sp,
1446*0b57cec5SDimitry Andric     lldb::StackFrameSP frame_sp) {
1447*0b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1448*0b57cec5SDimitry Andric 
1449*0b57cec5SDimitry Andric   if (!os_plugin_object_sp)
1450*0b57cec5SDimitry Andric     return ValueObjectListSP();
1451*0b57cec5SDimitry Andric 
1452*0b57cec5SDimitry Andric   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1453*0b57cec5SDimitry Andric   if (!generic)
1454*0b57cec5SDimitry Andric     return nullptr;
1455*0b57cec5SDimitry Andric 
1456*0b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
1457*0b57cec5SDimitry Andric                            (PyObject *)generic->GetValue());
1458*0b57cec5SDimitry Andric 
1459*0b57cec5SDimitry Andric   if (!implementor.IsAllocated())
1460*0b57cec5SDimitry Andric     return ValueObjectListSP();
1461*0b57cec5SDimitry Andric 
14624824e7fdSDimitry Andric   PythonObject py_return(
14634824e7fdSDimitry Andric       PyRefType::Owned,
14644824e7fdSDimitry Andric       LLDBSwigPython_GetRecognizedArguments(implementor.get(), frame_sp));
1465*0b57cec5SDimitry Andric 
1466*0b57cec5SDimitry Andric   // if it fails, print the error but otherwise go on
1467*0b57cec5SDimitry Andric   if (PyErr_Occurred()) {
1468*0b57cec5SDimitry Andric     PyErr_Print();
1469*0b57cec5SDimitry Andric     PyErr_Clear();
1470*0b57cec5SDimitry Andric   }
1471*0b57cec5SDimitry Andric   if (py_return.get()) {
1472*0b57cec5SDimitry Andric     PythonList result_list(PyRefType::Borrowed, py_return.get());
1473*0b57cec5SDimitry Andric     ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
1474*0b57cec5SDimitry Andric     for (size_t i = 0; i < result_list.GetSize(); i++) {
1475*0b57cec5SDimitry Andric       PyObject *item = result_list.GetItemAtIndex(i).get();
1476*0b57cec5SDimitry Andric       lldb::SBValue *sb_value_ptr =
1477*0b57cec5SDimitry Andric           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
1478*0b57cec5SDimitry Andric       auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
1479*0b57cec5SDimitry Andric       if (valobj_sp)
1480*0b57cec5SDimitry Andric         result->Append(valobj_sp);
1481*0b57cec5SDimitry Andric     }
1482*0b57cec5SDimitry Andric     return result;
1483*0b57cec5SDimitry Andric   }
1484*0b57cec5SDimitry Andric   return ValueObjectListSP();
1485*0b57cec5SDimitry Andric }
1486*0b57cec5SDimitry Andric 
1487*0b57cec5SDimitry Andric StructuredData::GenericSP
1488*0b57cec5SDimitry Andric ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject(
1489*0b57cec5SDimitry Andric     const char *class_name, lldb::ProcessSP process_sp) {
1490*0b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
1491*0b57cec5SDimitry Andric     return StructuredData::GenericSP();
1492*0b57cec5SDimitry Andric 
1493*0b57cec5SDimitry Andric   if (!process_sp)
1494*0b57cec5SDimitry Andric     return StructuredData::GenericSP();
1495*0b57cec5SDimitry Andric 
149604eeddc0SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
149704eeddc0SDimitry Andric   PythonObject ret_val = LLDBSWIGPythonCreateOSPlugin(
1498*0b57cec5SDimitry Andric       class_name, m_dictionary_name.c_str(), process_sp);
1499*0b57cec5SDimitry Andric 
150004eeddc0SDimitry Andric   return StructuredData::GenericSP(
150104eeddc0SDimitry Andric       new StructuredPythonObject(std::move(ret_val)));
1502*0b57cec5SDimitry Andric }
1503*0b57cec5SDimitry Andric 
1504*0b57cec5SDimitry Andric StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo(
1505*0b57cec5SDimitry Andric     StructuredData::ObjectSP os_plugin_object_sp) {
1506*0b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1507*0b57cec5SDimitry Andric 
1508*0b57cec5SDimitry Andric   if (!os_plugin_object_sp)
1509bdd1243dSDimitry Andric     return {};
1510*0b57cec5SDimitry Andric 
1511*0b57cec5SDimitry Andric   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1512*0b57cec5SDimitry Andric   if (!generic)
1513bdd1243dSDimitry Andric     return {};
1514*0b57cec5SDimitry Andric 
1515*0b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
1516*0b57cec5SDimitry Andric                            (PyObject *)generic->GetValue());
1517*0b57cec5SDimitry Andric 
1518*0b57cec5SDimitry Andric   if (!implementor.IsAllocated())
1519bdd1243dSDimitry Andric     return {};
1520*0b57cec5SDimitry Andric 
1521bdd1243dSDimitry Andric   llvm::Expected<PythonObject> expected_py_return =
1522bdd1243dSDimitry Andric       implementor.CallMethod("get_register_info");
1523*0b57cec5SDimitry Andric 
1524bdd1243dSDimitry Andric   if (!expected_py_return) {
1525bdd1243dSDimitry Andric     llvm::consumeError(expected_py_return.takeError());
1526bdd1243dSDimitry Andric     return {};
1527*0b57cec5SDimitry Andric   }
1528*0b57cec5SDimitry Andric 
1529bdd1243dSDimitry Andric   PythonObject py_return = std::move(expected_py_return.get());
1530*0b57cec5SDimitry Andric 
1531*0b57cec5SDimitry Andric   if (py_return.get()) {
1532*0b57cec5SDimitry Andric     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1533*0b57cec5SDimitry Andric     return result_dict.CreateStructuredDictionary();
1534*0b57cec5SDimitry Andric   }
1535*0b57cec5SDimitry Andric   return StructuredData::DictionarySP();
1536*0b57cec5SDimitry Andric }
1537*0b57cec5SDimitry Andric 
1538*0b57cec5SDimitry Andric StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo(
1539*0b57cec5SDimitry Andric     StructuredData::ObjectSP os_plugin_object_sp) {
1540*0b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1541*0b57cec5SDimitry Andric   if (!os_plugin_object_sp)
1542bdd1243dSDimitry Andric     return {};
1543*0b57cec5SDimitry Andric 
1544*0b57cec5SDimitry Andric   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1545*0b57cec5SDimitry Andric   if (!generic)
1546bdd1243dSDimitry Andric     return {};
1547*0b57cec5SDimitry Andric 
1548*0b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
1549*0b57cec5SDimitry Andric                            (PyObject *)generic->GetValue());
1550*0b57cec5SDimitry Andric 
1551*0b57cec5SDimitry Andric   if (!implementor.IsAllocated())
1552bdd1243dSDimitry Andric     return {};
1553*0b57cec5SDimitry Andric 
1554bdd1243dSDimitry Andric   llvm::Expected<PythonObject> expected_py_return =
1555bdd1243dSDimitry Andric       implementor.CallMethod("get_thread_info");
1556*0b57cec5SDimitry Andric 
1557bdd1243dSDimitry Andric   if (!expected_py_return) {
1558bdd1243dSDimitry Andric     llvm::consumeError(expected_py_return.takeError());
1559bdd1243dSDimitry Andric     return {};
1560*0b57cec5SDimitry Andric   }
1561*0b57cec5SDimitry Andric 
1562bdd1243dSDimitry Andric   PythonObject py_return = std::move(expected_py_return.get());
1563*0b57cec5SDimitry Andric 
1564*0b57cec5SDimitry Andric   if (py_return.get()) {
1565*0b57cec5SDimitry Andric     PythonList result_list(PyRefType::Borrowed, py_return.get());
1566*0b57cec5SDimitry Andric     return result_list.CreateStructuredArray();
1567*0b57cec5SDimitry Andric   }
1568*0b57cec5SDimitry Andric   return StructuredData::ArraySP();
1569*0b57cec5SDimitry Andric }
1570*0b57cec5SDimitry Andric 
1571*0b57cec5SDimitry Andric StructuredData::StringSP
1572*0b57cec5SDimitry Andric ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData(
1573*0b57cec5SDimitry Andric     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
1574*0b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1575*0b57cec5SDimitry Andric 
1576*0b57cec5SDimitry Andric   if (!os_plugin_object_sp)
1577bdd1243dSDimitry Andric     return {};
1578*0b57cec5SDimitry Andric 
1579*0b57cec5SDimitry Andric   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1580*0b57cec5SDimitry Andric   if (!generic)
1581bdd1243dSDimitry Andric     return {};
1582*0b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
1583*0b57cec5SDimitry Andric                            (PyObject *)generic->GetValue());
1584*0b57cec5SDimitry Andric 
1585*0b57cec5SDimitry Andric   if (!implementor.IsAllocated())
1586bdd1243dSDimitry Andric     return {};
1587*0b57cec5SDimitry Andric 
1588bdd1243dSDimitry Andric   llvm::Expected<PythonObject> expected_py_return =
1589bdd1243dSDimitry Andric       implementor.CallMethod("get_register_data", tid);
1590*0b57cec5SDimitry Andric 
1591bdd1243dSDimitry Andric   if (!expected_py_return) {
1592bdd1243dSDimitry Andric     llvm::consumeError(expected_py_return.takeError());
1593bdd1243dSDimitry Andric     return {};
1594*0b57cec5SDimitry Andric   }
1595*0b57cec5SDimitry Andric 
1596bdd1243dSDimitry Andric   PythonObject py_return = std::move(expected_py_return.get());
1597*0b57cec5SDimitry Andric 
1598*0b57cec5SDimitry Andric   if (py_return.get()) {
1599*0b57cec5SDimitry Andric     PythonBytes result(PyRefType::Borrowed, py_return.get());
1600*0b57cec5SDimitry Andric     return result.CreateStructuredString();
1601*0b57cec5SDimitry Andric   }
1602bdd1243dSDimitry Andric   return {};
1603*0b57cec5SDimitry Andric }
1604*0b57cec5SDimitry Andric 
1605*0b57cec5SDimitry Andric StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread(
1606*0b57cec5SDimitry Andric     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
1607*0b57cec5SDimitry Andric     lldb::addr_t context) {
1608*0b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1609*0b57cec5SDimitry Andric 
1610*0b57cec5SDimitry Andric   if (!os_plugin_object_sp)
1611bdd1243dSDimitry Andric     return {};
1612*0b57cec5SDimitry Andric 
1613*0b57cec5SDimitry Andric   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1614*0b57cec5SDimitry Andric   if (!generic)
1615bdd1243dSDimitry Andric     return {};
1616*0b57cec5SDimitry Andric 
1617*0b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
1618*0b57cec5SDimitry Andric                            (PyObject *)generic->GetValue());
1619*0b57cec5SDimitry Andric 
1620*0b57cec5SDimitry Andric   if (!implementor.IsAllocated())
1621bdd1243dSDimitry Andric     return {};
1622*0b57cec5SDimitry Andric 
1623bdd1243dSDimitry Andric   llvm::Expected<PythonObject> expected_py_return =
1624bdd1243dSDimitry Andric       implementor.CallMethod("create_thread", tid, context);
1625*0b57cec5SDimitry Andric 
1626bdd1243dSDimitry Andric   if (!expected_py_return) {
1627bdd1243dSDimitry Andric     llvm::consumeError(expected_py_return.takeError());
1628bdd1243dSDimitry Andric     return {};
1629*0b57cec5SDimitry Andric   }
1630*0b57cec5SDimitry Andric 
1631bdd1243dSDimitry Andric   PythonObject py_return = std::move(expected_py_return.get());
1632*0b57cec5SDimitry Andric 
1633*0b57cec5SDimitry Andric   if (py_return.get()) {
1634*0b57cec5SDimitry Andric     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1635*0b57cec5SDimitry Andric     return result_dict.CreateStructuredDictionary();
1636*0b57cec5SDimitry Andric   }
1637*0b57cec5SDimitry Andric   return StructuredData::DictionarySP();
1638*0b57cec5SDimitry Andric }
1639*0b57cec5SDimitry Andric 
1640*0b57cec5SDimitry Andric StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan(
16410eae32dcSDimitry Andric     const char *class_name, const StructuredDataImpl &args_data,
1642480093f4SDimitry Andric     std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) {
1643*0b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
1644*0b57cec5SDimitry Andric     return StructuredData::ObjectSP();
1645*0b57cec5SDimitry Andric 
1646*0b57cec5SDimitry Andric   if (!thread_plan_sp.get())
16479dba64beSDimitry Andric     return {};
1648*0b57cec5SDimitry Andric 
1649*0b57cec5SDimitry Andric   Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
1650*0b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
1651e8d8bef9SDimitry Andric       GetPythonInterpreter(debugger);
1652*0b57cec5SDimitry Andric 
1653e8d8bef9SDimitry Andric   if (!python_interpreter)
16549dba64beSDimitry Andric     return {};
1655*0b57cec5SDimitry Andric 
1656*0b57cec5SDimitry Andric   Locker py_lock(this,
1657*0b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
165804eeddc0SDimitry Andric   PythonObject ret_val = LLDBSwigPythonCreateScriptedThreadPlan(
165904eeddc0SDimitry Andric       class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
166004eeddc0SDimitry Andric       error_str, thread_plan_sp);
16619dba64beSDimitry Andric   if (!ret_val)
16629dba64beSDimitry Andric     return {};
1663*0b57cec5SDimitry Andric 
166404eeddc0SDimitry Andric   return StructuredData::ObjectSP(
166504eeddc0SDimitry Andric       new StructuredPythonObject(std::move(ret_val)));
1666*0b57cec5SDimitry Andric }
1667*0b57cec5SDimitry Andric 
1668*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop(
1669*0b57cec5SDimitry Andric     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1670*0b57cec5SDimitry Andric   bool explains_stop = true;
1671*0b57cec5SDimitry Andric   StructuredData::Generic *generic = nullptr;
1672*0b57cec5SDimitry Andric   if (implementor_sp)
1673*0b57cec5SDimitry Andric     generic = implementor_sp->GetAsGeneric();
1674*0b57cec5SDimitry Andric   if (generic) {
1675*0b57cec5SDimitry Andric     Locker py_lock(this,
1676*0b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1677*0b57cec5SDimitry Andric     explains_stop = LLDBSWIGPythonCallThreadPlan(
1678*0b57cec5SDimitry Andric         generic->GetValue(), "explains_stop", event, script_error);
1679*0b57cec5SDimitry Andric     if (script_error)
1680*0b57cec5SDimitry Andric       return true;
1681*0b57cec5SDimitry Andric   }
1682*0b57cec5SDimitry Andric   return explains_stop;
1683*0b57cec5SDimitry Andric }
1684*0b57cec5SDimitry Andric 
1685*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop(
1686*0b57cec5SDimitry Andric     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1687*0b57cec5SDimitry Andric   bool should_stop = true;
1688*0b57cec5SDimitry Andric   StructuredData::Generic *generic = nullptr;
1689*0b57cec5SDimitry Andric   if (implementor_sp)
1690*0b57cec5SDimitry Andric     generic = implementor_sp->GetAsGeneric();
1691*0b57cec5SDimitry Andric   if (generic) {
1692*0b57cec5SDimitry Andric     Locker py_lock(this,
1693*0b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1694*0b57cec5SDimitry Andric     should_stop = LLDBSWIGPythonCallThreadPlan(
1695*0b57cec5SDimitry Andric         generic->GetValue(), "should_stop", event, script_error);
1696*0b57cec5SDimitry Andric     if (script_error)
1697*0b57cec5SDimitry Andric       return true;
1698*0b57cec5SDimitry Andric   }
1699*0b57cec5SDimitry Andric   return should_stop;
1700*0b57cec5SDimitry Andric }
1701*0b57cec5SDimitry Andric 
1702*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale(
1703*0b57cec5SDimitry Andric     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1704*0b57cec5SDimitry Andric   bool is_stale = true;
1705*0b57cec5SDimitry Andric   StructuredData::Generic *generic = nullptr;
1706*0b57cec5SDimitry Andric   if (implementor_sp)
1707*0b57cec5SDimitry Andric     generic = implementor_sp->GetAsGeneric();
1708*0b57cec5SDimitry Andric   if (generic) {
1709*0b57cec5SDimitry Andric     Locker py_lock(this,
1710*0b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1711*0b57cec5SDimitry Andric     is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale",
1712*0b57cec5SDimitry Andric                                             nullptr, script_error);
1713*0b57cec5SDimitry Andric     if (script_error)
1714*0b57cec5SDimitry Andric       return true;
1715*0b57cec5SDimitry Andric   }
1716*0b57cec5SDimitry Andric   return is_stale;
1717*0b57cec5SDimitry Andric }
1718*0b57cec5SDimitry Andric 
1719*0b57cec5SDimitry Andric lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState(
1720*0b57cec5SDimitry Andric     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1721*0b57cec5SDimitry Andric   bool should_step = false;
1722*0b57cec5SDimitry Andric   StructuredData::Generic *generic = nullptr;
1723*0b57cec5SDimitry Andric   if (implementor_sp)
1724*0b57cec5SDimitry Andric     generic = implementor_sp->GetAsGeneric();
1725*0b57cec5SDimitry Andric   if (generic) {
1726*0b57cec5SDimitry Andric     Locker py_lock(this,
1727*0b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1728*0b57cec5SDimitry Andric     should_step = LLDBSWIGPythonCallThreadPlan(
1729*0b57cec5SDimitry Andric         generic->GetValue(), "should_step", nullptr, script_error);
1730*0b57cec5SDimitry Andric     if (script_error)
1731*0b57cec5SDimitry Andric       should_step = true;
1732*0b57cec5SDimitry Andric   }
1733*0b57cec5SDimitry Andric   if (should_step)
1734*0b57cec5SDimitry Andric     return lldb::eStateStepping;
1735*0b57cec5SDimitry Andric   return lldb::eStateRunning;
1736*0b57cec5SDimitry Andric }
1737*0b57cec5SDimitry Andric 
1738*0b57cec5SDimitry Andric StructuredData::GenericSP
1739*0b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
17400eae32dcSDimitry Andric     const char *class_name, const StructuredDataImpl &args_data,
1741*0b57cec5SDimitry Andric     lldb::BreakpointSP &bkpt_sp) {
1742*0b57cec5SDimitry Andric 
1743*0b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
1744*0b57cec5SDimitry Andric     return StructuredData::GenericSP();
1745*0b57cec5SDimitry Andric 
1746*0b57cec5SDimitry Andric   if (!bkpt_sp.get())
1747*0b57cec5SDimitry Andric     return StructuredData::GenericSP();
1748*0b57cec5SDimitry Andric 
1749*0b57cec5SDimitry Andric   Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
1750*0b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
1751e8d8bef9SDimitry Andric       GetPythonInterpreter(debugger);
1752*0b57cec5SDimitry Andric 
1753e8d8bef9SDimitry Andric   if (!python_interpreter)
1754*0b57cec5SDimitry Andric     return StructuredData::GenericSP();
1755*0b57cec5SDimitry Andric 
1756*0b57cec5SDimitry Andric   Locker py_lock(this,
1757*0b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1758*0b57cec5SDimitry Andric 
175904eeddc0SDimitry Andric   PythonObject ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver(
1760*0b57cec5SDimitry Andric       class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
1761*0b57cec5SDimitry Andric       bkpt_sp);
1762*0b57cec5SDimitry Andric 
176304eeddc0SDimitry Andric   return StructuredData::GenericSP(
176404eeddc0SDimitry Andric       new StructuredPythonObject(std::move(ret_val)));
1765*0b57cec5SDimitry Andric }
1766*0b57cec5SDimitry Andric 
1767*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
1768*0b57cec5SDimitry Andric     StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
1769*0b57cec5SDimitry Andric   bool should_continue = false;
1770*0b57cec5SDimitry Andric 
1771*0b57cec5SDimitry Andric   if (implementor_sp) {
1772*0b57cec5SDimitry Andric     Locker py_lock(this,
1773*0b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1774*0b57cec5SDimitry Andric     should_continue = LLDBSwigPythonCallBreakpointResolver(
1775*0b57cec5SDimitry Andric         implementor_sp->GetValue(), "__callback__", sym_ctx);
1776*0b57cec5SDimitry Andric     if (PyErr_Occurred()) {
1777*0b57cec5SDimitry Andric       PyErr_Print();
1778*0b57cec5SDimitry Andric       PyErr_Clear();
1779*0b57cec5SDimitry Andric     }
1780*0b57cec5SDimitry Andric   }
1781*0b57cec5SDimitry Andric   return should_continue;
1782*0b57cec5SDimitry Andric }
1783*0b57cec5SDimitry Andric 
1784*0b57cec5SDimitry Andric lldb::SearchDepth
1785*0b57cec5SDimitry Andric ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
1786*0b57cec5SDimitry Andric     StructuredData::GenericSP implementor_sp) {
1787*0b57cec5SDimitry Andric   int depth_as_int = lldb::eSearchDepthModule;
1788*0b57cec5SDimitry Andric   if (implementor_sp) {
1789*0b57cec5SDimitry Andric     Locker py_lock(this,
1790*0b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1791*0b57cec5SDimitry Andric     depth_as_int = LLDBSwigPythonCallBreakpointResolver(
1792*0b57cec5SDimitry Andric         implementor_sp->GetValue(), "__get_depth__", nullptr);
1793*0b57cec5SDimitry Andric     if (PyErr_Occurred()) {
1794*0b57cec5SDimitry Andric       PyErr_Print();
1795*0b57cec5SDimitry Andric       PyErr_Clear();
1796*0b57cec5SDimitry Andric     }
1797*0b57cec5SDimitry Andric   }
1798*0b57cec5SDimitry Andric   if (depth_as_int == lldb::eSearchDepthInvalid)
1799*0b57cec5SDimitry Andric     return lldb::eSearchDepthModule;
1800*0b57cec5SDimitry Andric 
1801*0b57cec5SDimitry Andric   if (depth_as_int <= lldb::kLastSearchDepthKind)
1802*0b57cec5SDimitry Andric     return (lldb::SearchDepth)depth_as_int;
1803*0b57cec5SDimitry Andric   return lldb::eSearchDepthModule;
1804*0b57cec5SDimitry Andric }
1805*0b57cec5SDimitry Andric 
1806e8d8bef9SDimitry Andric StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
18070eae32dcSDimitry Andric     TargetSP target_sp, const char *class_name,
18080eae32dcSDimitry Andric     const StructuredDataImpl &args_data, Status &error) {
1809e8d8bef9SDimitry Andric 
1810e8d8bef9SDimitry Andric   if (!target_sp) {
1811e8d8bef9SDimitry Andric     error.SetErrorString("No target for scripted stop-hook.");
1812e8d8bef9SDimitry Andric     return StructuredData::GenericSP();
1813e8d8bef9SDimitry Andric   }
1814e8d8bef9SDimitry Andric 
1815e8d8bef9SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0') {
1816e8d8bef9SDimitry Andric     error.SetErrorString("No class name for scripted stop-hook.");
1817e8d8bef9SDimitry Andric     return StructuredData::GenericSP();
1818e8d8bef9SDimitry Andric   }
1819e8d8bef9SDimitry Andric 
1820e8d8bef9SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
1821e8d8bef9SDimitry Andric       GetPythonInterpreter(m_debugger);
1822e8d8bef9SDimitry Andric 
1823e8d8bef9SDimitry Andric   if (!python_interpreter) {
1824e8d8bef9SDimitry Andric     error.SetErrorString("No script interpreter for scripted stop-hook.");
1825e8d8bef9SDimitry Andric     return StructuredData::GenericSP();
1826e8d8bef9SDimitry Andric   }
1827e8d8bef9SDimitry Andric 
1828e8d8bef9SDimitry Andric   Locker py_lock(this,
1829e8d8bef9SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1830e8d8bef9SDimitry Andric 
183104eeddc0SDimitry Andric   PythonObject ret_val = LLDBSwigPythonCreateScriptedStopHook(
1832e8d8bef9SDimitry Andric       target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
1833e8d8bef9SDimitry Andric       args_data, error);
1834e8d8bef9SDimitry Andric 
183504eeddc0SDimitry Andric   return StructuredData::GenericSP(
183604eeddc0SDimitry Andric       new StructuredPythonObject(std::move(ret_val)));
1837e8d8bef9SDimitry Andric }
1838e8d8bef9SDimitry Andric 
1839e8d8bef9SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
1840e8d8bef9SDimitry Andric     StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
1841e8d8bef9SDimitry Andric     lldb::StreamSP stream_sp) {
1842e8d8bef9SDimitry Andric   assert(implementor_sp &&
1843e8d8bef9SDimitry Andric          "can't call a stop hook with an invalid implementor");
1844e8d8bef9SDimitry Andric   assert(stream_sp && "can't call a stop hook with an invalid stream");
1845e8d8bef9SDimitry Andric 
1846e8d8bef9SDimitry Andric   Locker py_lock(this,
1847e8d8bef9SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1848e8d8bef9SDimitry Andric 
1849e8d8bef9SDimitry Andric   lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
1850e8d8bef9SDimitry Andric 
1851e8d8bef9SDimitry Andric   bool ret_val = LLDBSwigPythonStopHookCallHandleStop(
1852e8d8bef9SDimitry Andric       implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
1853e8d8bef9SDimitry Andric   return ret_val;
1854e8d8bef9SDimitry Andric }
1855e8d8bef9SDimitry Andric 
1856*0b57cec5SDimitry Andric StructuredData::ObjectSP
1857*0b57cec5SDimitry Andric ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
1858*0b57cec5SDimitry Andric                                               lldb_private::Status &error) {
1859*0b57cec5SDimitry Andric   if (!FileSystem::Instance().Exists(file_spec)) {
1860*0b57cec5SDimitry Andric     error.SetErrorString("no such file");
1861*0b57cec5SDimitry Andric     return StructuredData::ObjectSP();
1862*0b57cec5SDimitry Andric   }
1863*0b57cec5SDimitry Andric 
1864*0b57cec5SDimitry Andric   StructuredData::ObjectSP module_sp;
1865*0b57cec5SDimitry Andric 
1866fe6060f1SDimitry Andric   LoadScriptOptions load_script_options =
1867fe6060f1SDimitry Andric       LoadScriptOptions().SetInitSession(true).SetSilent(false);
1868fe6060f1SDimitry Andric   if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1869fe6060f1SDimitry Andric                           error, &module_sp))
1870*0b57cec5SDimitry Andric     return module_sp;
1871*0b57cec5SDimitry Andric 
1872*0b57cec5SDimitry Andric   return StructuredData::ObjectSP();
1873*0b57cec5SDimitry Andric }
1874*0b57cec5SDimitry Andric 
1875*0b57cec5SDimitry Andric StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
1876*0b57cec5SDimitry Andric     StructuredData::ObjectSP plugin_module_sp, Target *target,
1877*0b57cec5SDimitry Andric     const char *setting_name, lldb_private::Status &error) {
1878*0b57cec5SDimitry Andric   if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
1879*0b57cec5SDimitry Andric     return StructuredData::DictionarySP();
1880*0b57cec5SDimitry Andric   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
1881*0b57cec5SDimitry Andric   if (!generic)
1882*0b57cec5SDimitry Andric     return StructuredData::DictionarySP();
1883*0b57cec5SDimitry Andric 
1884*0b57cec5SDimitry Andric   Locker py_lock(this,
1885*0b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1886*0b57cec5SDimitry Andric   TargetSP target_sp(target->shared_from_this());
1887*0b57cec5SDimitry Andric 
18889dba64beSDimitry Andric   auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting(
18899dba64beSDimitry Andric       generic->GetValue(), setting_name, target_sp);
18909dba64beSDimitry Andric 
18919dba64beSDimitry Andric   if (!setting)
18929dba64beSDimitry Andric     return StructuredData::DictionarySP();
18939dba64beSDimitry Andric 
18949dba64beSDimitry Andric   PythonDictionary py_dict =
18959dba64beSDimitry Andric       unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
18969dba64beSDimitry Andric 
18979dba64beSDimitry Andric   if (!py_dict)
18989dba64beSDimitry Andric     return StructuredData::DictionarySP();
18999dba64beSDimitry Andric 
1900*0b57cec5SDimitry Andric   return py_dict.CreateStructuredDictionary();
1901*0b57cec5SDimitry Andric }
1902*0b57cec5SDimitry Andric 
1903*0b57cec5SDimitry Andric StructuredData::ObjectSP
1904*0b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
1905*0b57cec5SDimitry Andric     const char *class_name, lldb::ValueObjectSP valobj) {
1906*0b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
1907*0b57cec5SDimitry Andric     return StructuredData::ObjectSP();
1908*0b57cec5SDimitry Andric 
1909*0b57cec5SDimitry Andric   if (!valobj.get())
1910*0b57cec5SDimitry Andric     return StructuredData::ObjectSP();
1911*0b57cec5SDimitry Andric 
1912*0b57cec5SDimitry Andric   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
1913*0b57cec5SDimitry Andric   Target *target = exe_ctx.GetTargetPtr();
1914*0b57cec5SDimitry Andric 
1915*0b57cec5SDimitry Andric   if (!target)
1916*0b57cec5SDimitry Andric     return StructuredData::ObjectSP();
1917*0b57cec5SDimitry Andric 
1918*0b57cec5SDimitry Andric   Debugger &debugger = target->GetDebugger();
1919*0b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
1920e8d8bef9SDimitry Andric       GetPythonInterpreter(debugger);
1921*0b57cec5SDimitry Andric 
1922e8d8bef9SDimitry Andric   if (!python_interpreter)
1923*0b57cec5SDimitry Andric     return StructuredData::ObjectSP();
1924*0b57cec5SDimitry Andric 
1925*0b57cec5SDimitry Andric   Locker py_lock(this,
1926*0b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
192704eeddc0SDimitry Andric   PythonObject ret_val = LLDBSwigPythonCreateSyntheticProvider(
1928*0b57cec5SDimitry Andric       class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
1929*0b57cec5SDimitry Andric 
193004eeddc0SDimitry Andric   return StructuredData::ObjectSP(
193104eeddc0SDimitry Andric       new StructuredPythonObject(std::move(ret_val)));
1932*0b57cec5SDimitry Andric }
1933*0b57cec5SDimitry Andric 
1934*0b57cec5SDimitry Andric StructuredData::GenericSP
1935*0b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
1936*0b57cec5SDimitry Andric   DebuggerSP debugger_sp(m_debugger.shared_from_this());
1937*0b57cec5SDimitry Andric 
1938*0b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
1939*0b57cec5SDimitry Andric     return StructuredData::GenericSP();
1940*0b57cec5SDimitry Andric 
1941*0b57cec5SDimitry Andric   if (!debugger_sp.get())
1942*0b57cec5SDimitry Andric     return StructuredData::GenericSP();
1943*0b57cec5SDimitry Andric 
1944*0b57cec5SDimitry Andric   Locker py_lock(this,
1945*0b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
194604eeddc0SDimitry Andric   PythonObject ret_val = LLDBSwigPythonCreateCommandObject(
1947*0b57cec5SDimitry Andric       class_name, m_dictionary_name.c_str(), debugger_sp);
1948*0b57cec5SDimitry Andric 
194904eeddc0SDimitry Andric   return StructuredData::GenericSP(
195004eeddc0SDimitry Andric       new StructuredPythonObject(std::move(ret_val)));
1951*0b57cec5SDimitry Andric }
1952*0b57cec5SDimitry Andric 
1953*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1954*0b57cec5SDimitry Andric     const char *oneliner, std::string &output, const void *name_token) {
1955*0b57cec5SDimitry Andric   StringList input;
1956*0b57cec5SDimitry Andric   input.SplitIntoLines(oneliner, strlen(oneliner));
1957*0b57cec5SDimitry Andric   return GenerateTypeScriptFunction(input, output, name_token);
1958*0b57cec5SDimitry Andric }
1959*0b57cec5SDimitry Andric 
1960*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1961*0b57cec5SDimitry Andric     const char *oneliner, std::string &output, const void *name_token) {
1962*0b57cec5SDimitry Andric   StringList input;
1963*0b57cec5SDimitry Andric   input.SplitIntoLines(oneliner, strlen(oneliner));
1964*0b57cec5SDimitry Andric   return GenerateTypeSynthClass(input, output, name_token);
1965*0b57cec5SDimitry Andric }
1966*0b57cec5SDimitry Andric 
1967*0b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
1968480093f4SDimitry Andric     StringList &user_input, std::string &output,
1969480093f4SDimitry Andric     bool has_extra_args) {
1970*0b57cec5SDimitry Andric   static uint32_t num_created_functions = 0;
1971*0b57cec5SDimitry Andric   user_input.RemoveBlankLines();
1972*0b57cec5SDimitry Andric   StreamString sstr;
1973*0b57cec5SDimitry Andric   Status error;
1974*0b57cec5SDimitry Andric   if (user_input.GetSize() == 0) {
1975*0b57cec5SDimitry Andric     error.SetErrorString("No input data.");
1976*0b57cec5SDimitry Andric     return error;
1977*0b57cec5SDimitry Andric   }
1978*0b57cec5SDimitry Andric 
1979*0b57cec5SDimitry Andric   std::string auto_generated_function_name(GenerateUniqueName(
1980*0b57cec5SDimitry Andric       "lldb_autogen_python_bp_callback_func_", num_created_functions));
1981480093f4SDimitry Andric   if (has_extra_args)
1982480093f4SDimitry Andric     sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
1983480093f4SDimitry Andric                 auto_generated_function_name.c_str());
1984480093f4SDimitry Andric   else
1985*0b57cec5SDimitry Andric     sstr.Printf("def %s (frame, bp_loc, internal_dict):",
1986*0b57cec5SDimitry Andric                 auto_generated_function_name.c_str());
1987*0b57cec5SDimitry Andric 
1988*0b57cec5SDimitry Andric   error = GenerateFunction(sstr.GetData(), user_input);
1989*0b57cec5SDimitry Andric   if (!error.Success())
1990*0b57cec5SDimitry Andric     return error;
1991*0b57cec5SDimitry Andric 
1992*0b57cec5SDimitry Andric   // Store the name of the auto-generated function to be called.
1993*0b57cec5SDimitry Andric   output.assign(auto_generated_function_name);
1994*0b57cec5SDimitry Andric   return error;
1995*0b57cec5SDimitry Andric }
1996*0b57cec5SDimitry Andric 
1997*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
1998*0b57cec5SDimitry Andric     StringList &user_input, std::string &output) {
1999*0b57cec5SDimitry Andric   static uint32_t num_created_functions = 0;
2000*0b57cec5SDimitry Andric   user_input.RemoveBlankLines();
2001*0b57cec5SDimitry Andric   StreamString sstr;
2002*0b57cec5SDimitry Andric 
2003*0b57cec5SDimitry Andric   if (user_input.GetSize() == 0)
2004*0b57cec5SDimitry Andric     return false;
2005*0b57cec5SDimitry Andric 
2006*0b57cec5SDimitry Andric   std::string auto_generated_function_name(GenerateUniqueName(
2007*0b57cec5SDimitry Andric       "lldb_autogen_python_wp_callback_func_", num_created_functions));
2008*0b57cec5SDimitry Andric   sstr.Printf("def %s (frame, wp, internal_dict):",
2009*0b57cec5SDimitry Andric               auto_generated_function_name.c_str());
2010*0b57cec5SDimitry Andric 
2011*0b57cec5SDimitry Andric   if (!GenerateFunction(sstr.GetData(), user_input).Success())
2012*0b57cec5SDimitry Andric     return false;
2013*0b57cec5SDimitry Andric 
2014*0b57cec5SDimitry Andric   // Store the name of the auto-generated function to be called.
2015*0b57cec5SDimitry Andric   output.assign(auto_generated_function_name);
2016*0b57cec5SDimitry Andric   return true;
2017*0b57cec5SDimitry Andric }
2018*0b57cec5SDimitry Andric 
2019*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetScriptedSummary(
2020*0b57cec5SDimitry Andric     const char *python_function_name, lldb::ValueObjectSP valobj,
2021*0b57cec5SDimitry Andric     StructuredData::ObjectSP &callee_wrapper_sp,
2022*0b57cec5SDimitry Andric     const TypeSummaryOptions &options, std::string &retval) {
2023*0b57cec5SDimitry Andric 
2024e8d8bef9SDimitry Andric   LLDB_SCOPED_TIMER();
2025*0b57cec5SDimitry Andric 
2026*0b57cec5SDimitry Andric   if (!valobj.get()) {
2027*0b57cec5SDimitry Andric     retval.assign("<no object>");
2028*0b57cec5SDimitry Andric     return false;
2029*0b57cec5SDimitry Andric   }
2030*0b57cec5SDimitry Andric 
2031*0b57cec5SDimitry Andric   void *old_callee = nullptr;
2032*0b57cec5SDimitry Andric   StructuredData::Generic *generic = nullptr;
2033*0b57cec5SDimitry Andric   if (callee_wrapper_sp) {
2034*0b57cec5SDimitry Andric     generic = callee_wrapper_sp->GetAsGeneric();
2035*0b57cec5SDimitry Andric     if (generic)
2036*0b57cec5SDimitry Andric       old_callee = generic->GetValue();
2037*0b57cec5SDimitry Andric   }
2038*0b57cec5SDimitry Andric   void *new_callee = old_callee;
2039*0b57cec5SDimitry Andric 
2040*0b57cec5SDimitry Andric   bool ret_val;
2041*0b57cec5SDimitry Andric   if (python_function_name && *python_function_name) {
2042*0b57cec5SDimitry Andric     {
2043*0b57cec5SDimitry Andric       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
2044*0b57cec5SDimitry Andric                                Locker::NoSTDIN);
2045*0b57cec5SDimitry Andric       {
2046*0b57cec5SDimitry Andric         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
2047*0b57cec5SDimitry Andric 
2048*0b57cec5SDimitry Andric         static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
2049*0b57cec5SDimitry Andric         Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
2050*0b57cec5SDimitry Andric         ret_val = LLDBSwigPythonCallTypeScript(
2051*0b57cec5SDimitry Andric             python_function_name, GetSessionDictionary().get(), valobj,
2052*0b57cec5SDimitry Andric             &new_callee, options_sp, retval);
2053*0b57cec5SDimitry Andric       }
2054*0b57cec5SDimitry Andric     }
2055*0b57cec5SDimitry Andric   } else {
2056*0b57cec5SDimitry Andric     retval.assign("<no function name>");
2057*0b57cec5SDimitry Andric     return false;
2058*0b57cec5SDimitry Andric   }
2059*0b57cec5SDimitry Andric 
206004eeddc0SDimitry Andric   if (new_callee && old_callee != new_callee) {
206104eeddc0SDimitry Andric     Locker py_lock(this,
206204eeddc0SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
206304eeddc0SDimitry Andric     callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
206404eeddc0SDimitry Andric         PythonObject(PyRefType::Borrowed, static_cast<PyObject *>(new_callee)));
206504eeddc0SDimitry Andric   }
2066*0b57cec5SDimitry Andric 
2067*0b57cec5SDimitry Andric   return ret_val;
2068*0b57cec5SDimitry Andric }
2069*0b57cec5SDimitry Andric 
2070bdd1243dSDimitry Andric bool ScriptInterpreterPythonImpl::FormatterCallbackFunction(
2071bdd1243dSDimitry Andric     const char *python_function_name, TypeImplSP type_impl_sp) {
2072bdd1243dSDimitry Andric   Locker py_lock(this,
2073bdd1243dSDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2074bdd1243dSDimitry Andric   return LLDBSwigPythonFormatterCallbackFunction(
2075bdd1243dSDimitry Andric       python_function_name, m_dictionary_name.c_str(), type_impl_sp);
2076bdd1243dSDimitry Andric }
2077bdd1243dSDimitry Andric 
2078*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
2079*0b57cec5SDimitry Andric     void *baton, StoppointCallbackContext *context, user_id_t break_id,
2080*0b57cec5SDimitry Andric     user_id_t break_loc_id) {
2081*0b57cec5SDimitry Andric   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
2082*0b57cec5SDimitry Andric   const char *python_function_name = bp_option_data->script_source.c_str();
2083*0b57cec5SDimitry Andric 
2084*0b57cec5SDimitry Andric   if (!context)
2085*0b57cec5SDimitry Andric     return true;
2086*0b57cec5SDimitry Andric 
2087*0b57cec5SDimitry Andric   ExecutionContext exe_ctx(context->exe_ctx_ref);
2088*0b57cec5SDimitry Andric   Target *target = exe_ctx.GetTargetPtr();
2089*0b57cec5SDimitry Andric 
2090*0b57cec5SDimitry Andric   if (!target)
2091*0b57cec5SDimitry Andric     return true;
2092*0b57cec5SDimitry Andric 
2093*0b57cec5SDimitry Andric   Debugger &debugger = target->GetDebugger();
2094*0b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
2095e8d8bef9SDimitry Andric       GetPythonInterpreter(debugger);
2096*0b57cec5SDimitry Andric 
2097e8d8bef9SDimitry Andric   if (!python_interpreter)
2098*0b57cec5SDimitry Andric     return true;
2099*0b57cec5SDimitry Andric 
2100*0b57cec5SDimitry Andric   if (python_function_name && python_function_name[0]) {
2101*0b57cec5SDimitry Andric     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2102*0b57cec5SDimitry Andric     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2103*0b57cec5SDimitry Andric     if (breakpoint_sp) {
2104*0b57cec5SDimitry Andric       const BreakpointLocationSP bp_loc_sp(
2105*0b57cec5SDimitry Andric           breakpoint_sp->FindLocationByID(break_loc_id));
2106*0b57cec5SDimitry Andric 
2107*0b57cec5SDimitry Andric       if (stop_frame_sp && bp_loc_sp) {
2108*0b57cec5SDimitry Andric         bool ret_val = true;
2109*0b57cec5SDimitry Andric         {
2110*0b57cec5SDimitry Andric           Locker py_lock(python_interpreter, Locker::AcquireLock |
2111*0b57cec5SDimitry Andric                                                  Locker::InitSession |
2112*0b57cec5SDimitry Andric                                                  Locker::NoSTDIN);
2113480093f4SDimitry Andric           Expected<bool> maybe_ret_val =
2114480093f4SDimitry Andric               LLDBSwigPythonBreakpointCallbackFunction(
2115*0b57cec5SDimitry Andric                   python_function_name,
2116*0b57cec5SDimitry Andric                   python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
21170eae32dcSDimitry Andric                   bp_loc_sp, bp_option_data->m_extra_args);
2118480093f4SDimitry Andric 
2119480093f4SDimitry Andric           if (!maybe_ret_val) {
2120480093f4SDimitry Andric 
2121480093f4SDimitry Andric             llvm::handleAllErrors(
2122480093f4SDimitry Andric                 maybe_ret_val.takeError(),
2123480093f4SDimitry Andric                 [&](PythonException &E) {
2124480093f4SDimitry Andric                   debugger.GetErrorStream() << E.ReadBacktrace();
2125480093f4SDimitry Andric                 },
2126480093f4SDimitry Andric                 [&](const llvm::ErrorInfoBase &E) {
2127480093f4SDimitry Andric                   debugger.GetErrorStream() << E.message();
2128480093f4SDimitry Andric                 });
2129480093f4SDimitry Andric 
2130480093f4SDimitry Andric           } else {
2131480093f4SDimitry Andric             ret_val = maybe_ret_val.get();
2132480093f4SDimitry Andric           }
2133*0b57cec5SDimitry Andric         }
2134*0b57cec5SDimitry Andric         return ret_val;
2135*0b57cec5SDimitry Andric       }
2136*0b57cec5SDimitry Andric     }
2137*0b57cec5SDimitry Andric   }
2138*0b57cec5SDimitry Andric   // We currently always true so we stop in case anything goes wrong when
2139*0b57cec5SDimitry Andric   // trying to call the script function
2140*0b57cec5SDimitry Andric   return true;
2141*0b57cec5SDimitry Andric }
2142*0b57cec5SDimitry Andric 
2143*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
2144*0b57cec5SDimitry Andric     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2145*0b57cec5SDimitry Andric   WatchpointOptions::CommandData *wp_option_data =
2146*0b57cec5SDimitry Andric       (WatchpointOptions::CommandData *)baton;
2147*0b57cec5SDimitry Andric   const char *python_function_name = wp_option_data->script_source.c_str();
2148*0b57cec5SDimitry Andric 
2149*0b57cec5SDimitry Andric   if (!context)
2150*0b57cec5SDimitry Andric     return true;
2151*0b57cec5SDimitry Andric 
2152*0b57cec5SDimitry Andric   ExecutionContext exe_ctx(context->exe_ctx_ref);
2153*0b57cec5SDimitry Andric   Target *target = exe_ctx.GetTargetPtr();
2154*0b57cec5SDimitry Andric 
2155*0b57cec5SDimitry Andric   if (!target)
2156*0b57cec5SDimitry Andric     return true;
2157*0b57cec5SDimitry Andric 
2158*0b57cec5SDimitry Andric   Debugger &debugger = target->GetDebugger();
2159*0b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
2160e8d8bef9SDimitry Andric       GetPythonInterpreter(debugger);
2161*0b57cec5SDimitry Andric 
2162e8d8bef9SDimitry Andric   if (!python_interpreter)
2163*0b57cec5SDimitry Andric     return true;
2164*0b57cec5SDimitry Andric 
2165*0b57cec5SDimitry Andric   if (python_function_name && python_function_name[0]) {
2166*0b57cec5SDimitry Andric     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2167*0b57cec5SDimitry Andric     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2168*0b57cec5SDimitry Andric     if (wp_sp) {
2169*0b57cec5SDimitry Andric       if (stop_frame_sp && wp_sp) {
2170*0b57cec5SDimitry Andric         bool ret_val = true;
2171*0b57cec5SDimitry Andric         {
2172*0b57cec5SDimitry Andric           Locker py_lock(python_interpreter, Locker::AcquireLock |
2173*0b57cec5SDimitry Andric                                                  Locker::InitSession |
2174*0b57cec5SDimitry Andric                                                  Locker::NoSTDIN);
2175*0b57cec5SDimitry Andric           ret_val = LLDBSwigPythonWatchpointCallbackFunction(
2176*0b57cec5SDimitry Andric               python_function_name,
2177*0b57cec5SDimitry Andric               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2178*0b57cec5SDimitry Andric               wp_sp);
2179*0b57cec5SDimitry Andric         }
2180*0b57cec5SDimitry Andric         return ret_val;
2181*0b57cec5SDimitry Andric       }
2182*0b57cec5SDimitry Andric     }
2183*0b57cec5SDimitry Andric   }
2184*0b57cec5SDimitry Andric   // We currently always true so we stop in case anything goes wrong when
2185*0b57cec5SDimitry Andric   // trying to call the script function
2186*0b57cec5SDimitry Andric   return true;
2187*0b57cec5SDimitry Andric }
2188*0b57cec5SDimitry Andric 
2189*0b57cec5SDimitry Andric size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2190*0b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
2191*0b57cec5SDimitry Andric   if (!implementor_sp)
2192*0b57cec5SDimitry Andric     return 0;
2193*0b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2194*0b57cec5SDimitry Andric   if (!generic)
2195*0b57cec5SDimitry Andric     return 0;
21964824e7fdSDimitry Andric   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2197*0b57cec5SDimitry Andric   if (!implementor)
2198*0b57cec5SDimitry Andric     return 0;
2199*0b57cec5SDimitry Andric 
2200*0b57cec5SDimitry Andric   size_t ret_val = 0;
2201*0b57cec5SDimitry Andric 
2202*0b57cec5SDimitry Andric   {
2203*0b57cec5SDimitry Andric     Locker py_lock(this,
2204*0b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2205*0b57cec5SDimitry Andric     ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max);
2206*0b57cec5SDimitry Andric   }
2207*0b57cec5SDimitry Andric 
2208*0b57cec5SDimitry Andric   return ret_val;
2209*0b57cec5SDimitry Andric }
2210*0b57cec5SDimitry Andric 
2211*0b57cec5SDimitry Andric lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
2212*0b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
2213*0b57cec5SDimitry Andric   if (!implementor_sp)
2214*0b57cec5SDimitry Andric     return lldb::ValueObjectSP();
2215*0b57cec5SDimitry Andric 
2216*0b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2217*0b57cec5SDimitry Andric   if (!generic)
2218*0b57cec5SDimitry Andric     return lldb::ValueObjectSP();
22194824e7fdSDimitry Andric   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2220*0b57cec5SDimitry Andric   if (!implementor)
2221*0b57cec5SDimitry Andric     return lldb::ValueObjectSP();
2222*0b57cec5SDimitry Andric 
2223*0b57cec5SDimitry Andric   lldb::ValueObjectSP ret_val;
2224*0b57cec5SDimitry Andric   {
2225*0b57cec5SDimitry Andric     Locker py_lock(this,
2226*0b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
22274824e7fdSDimitry Andric     PyObject *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx);
2228*0b57cec5SDimitry Andric     if (child_ptr != nullptr && child_ptr != Py_None) {
2229*0b57cec5SDimitry Andric       lldb::SBValue *sb_value_ptr =
2230*0b57cec5SDimitry Andric           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2231*0b57cec5SDimitry Andric       if (sb_value_ptr == nullptr)
2232*0b57cec5SDimitry Andric         Py_XDECREF(child_ptr);
2233*0b57cec5SDimitry Andric       else
2234*0b57cec5SDimitry Andric         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2235*0b57cec5SDimitry Andric     } else {
2236*0b57cec5SDimitry Andric       Py_XDECREF(child_ptr);
2237*0b57cec5SDimitry Andric     }
2238*0b57cec5SDimitry Andric   }
2239*0b57cec5SDimitry Andric 
2240*0b57cec5SDimitry Andric   return ret_val;
2241*0b57cec5SDimitry Andric }
2242*0b57cec5SDimitry Andric 
2243*0b57cec5SDimitry Andric int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2244*0b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
2245*0b57cec5SDimitry Andric   if (!implementor_sp)
2246*0b57cec5SDimitry Andric     return UINT32_MAX;
2247*0b57cec5SDimitry Andric 
2248*0b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2249*0b57cec5SDimitry Andric   if (!generic)
2250*0b57cec5SDimitry Andric     return UINT32_MAX;
22514824e7fdSDimitry Andric   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2252*0b57cec5SDimitry Andric   if (!implementor)
2253*0b57cec5SDimitry Andric     return UINT32_MAX;
2254*0b57cec5SDimitry Andric 
2255*0b57cec5SDimitry Andric   int ret_val = UINT32_MAX;
2256*0b57cec5SDimitry Andric 
2257*0b57cec5SDimitry Andric   {
2258*0b57cec5SDimitry Andric     Locker py_lock(this,
2259*0b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2260*0b57cec5SDimitry Andric     ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
2261*0b57cec5SDimitry Andric   }
2262*0b57cec5SDimitry Andric 
2263*0b57cec5SDimitry Andric   return ret_val;
2264*0b57cec5SDimitry Andric }
2265*0b57cec5SDimitry Andric 
2266*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2267*0b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp) {
2268*0b57cec5SDimitry Andric   bool ret_val = false;
2269*0b57cec5SDimitry Andric 
2270*0b57cec5SDimitry Andric   if (!implementor_sp)
2271*0b57cec5SDimitry Andric     return ret_val;
2272*0b57cec5SDimitry Andric 
2273*0b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2274*0b57cec5SDimitry Andric   if (!generic)
2275*0b57cec5SDimitry Andric     return ret_val;
22764824e7fdSDimitry Andric   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2277*0b57cec5SDimitry Andric   if (!implementor)
2278*0b57cec5SDimitry Andric     return ret_val;
2279*0b57cec5SDimitry Andric 
2280*0b57cec5SDimitry Andric   {
2281*0b57cec5SDimitry Andric     Locker py_lock(this,
2282*0b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2283*0b57cec5SDimitry Andric     ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor);
2284*0b57cec5SDimitry Andric   }
2285*0b57cec5SDimitry Andric 
2286*0b57cec5SDimitry Andric   return ret_val;
2287*0b57cec5SDimitry Andric }
2288*0b57cec5SDimitry Andric 
2289*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2290*0b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp) {
2291*0b57cec5SDimitry Andric   bool ret_val = false;
2292*0b57cec5SDimitry Andric 
2293*0b57cec5SDimitry Andric   if (!implementor_sp)
2294*0b57cec5SDimitry Andric     return ret_val;
2295*0b57cec5SDimitry Andric 
2296*0b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2297*0b57cec5SDimitry Andric   if (!generic)
2298*0b57cec5SDimitry Andric     return ret_val;
22994824e7fdSDimitry Andric   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2300*0b57cec5SDimitry Andric   if (!implementor)
2301*0b57cec5SDimitry Andric     return ret_val;
2302*0b57cec5SDimitry Andric 
2303*0b57cec5SDimitry Andric   {
2304*0b57cec5SDimitry Andric     Locker py_lock(this,
2305*0b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2306*0b57cec5SDimitry Andric     ret_val =
2307*0b57cec5SDimitry Andric         LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor);
2308*0b57cec5SDimitry Andric   }
2309*0b57cec5SDimitry Andric 
2310*0b57cec5SDimitry Andric   return ret_val;
2311*0b57cec5SDimitry Andric }
2312*0b57cec5SDimitry Andric 
2313*0b57cec5SDimitry Andric lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
2314*0b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp) {
2315*0b57cec5SDimitry Andric   lldb::ValueObjectSP ret_val(nullptr);
2316*0b57cec5SDimitry Andric 
2317*0b57cec5SDimitry Andric   if (!implementor_sp)
2318*0b57cec5SDimitry Andric     return ret_val;
2319*0b57cec5SDimitry Andric 
2320*0b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2321*0b57cec5SDimitry Andric   if (!generic)
2322*0b57cec5SDimitry Andric     return ret_val;
23234824e7fdSDimitry Andric   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2324*0b57cec5SDimitry Andric   if (!implementor)
2325*0b57cec5SDimitry Andric     return ret_val;
2326*0b57cec5SDimitry Andric 
2327*0b57cec5SDimitry Andric   {
2328*0b57cec5SDimitry Andric     Locker py_lock(this,
2329*0b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
23304824e7fdSDimitry Andric     PyObject *child_ptr =
23314824e7fdSDimitry Andric         LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2332*0b57cec5SDimitry Andric     if (child_ptr != nullptr && child_ptr != Py_None) {
2333*0b57cec5SDimitry Andric       lldb::SBValue *sb_value_ptr =
2334*0b57cec5SDimitry Andric           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2335*0b57cec5SDimitry Andric       if (sb_value_ptr == nullptr)
2336*0b57cec5SDimitry Andric         Py_XDECREF(child_ptr);
2337*0b57cec5SDimitry Andric       else
2338*0b57cec5SDimitry Andric         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2339*0b57cec5SDimitry Andric     } else {
2340*0b57cec5SDimitry Andric       Py_XDECREF(child_ptr);
2341*0b57cec5SDimitry Andric     }
2342*0b57cec5SDimitry Andric   }
2343*0b57cec5SDimitry Andric 
2344*0b57cec5SDimitry Andric   return ret_val;
2345*0b57cec5SDimitry Andric }
2346*0b57cec5SDimitry Andric 
2347*0b57cec5SDimitry Andric ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2348*0b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp) {
2349*0b57cec5SDimitry Andric   Locker py_lock(this,
2350*0b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2351*0b57cec5SDimitry Andric 
2352bdd1243dSDimitry Andric   if (!implementor_sp)
2353bdd1243dSDimitry Andric     return {};
2354bdd1243dSDimitry Andric 
2355bdd1243dSDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2356bdd1243dSDimitry Andric   if (!generic)
2357bdd1243dSDimitry Andric     return {};
2358bdd1243dSDimitry Andric 
2359bdd1243dSDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
2360bdd1243dSDimitry Andric                            (PyObject *)generic->GetValue());
2361bdd1243dSDimitry Andric   if (!implementor.IsAllocated())
2362bdd1243dSDimitry Andric     return {};
2363bdd1243dSDimitry Andric 
2364bdd1243dSDimitry Andric   llvm::Expected<PythonObject> expected_py_return =
2365bdd1243dSDimitry Andric       implementor.CallMethod("get_type_name");
2366bdd1243dSDimitry Andric 
2367bdd1243dSDimitry Andric   if (!expected_py_return) {
2368bdd1243dSDimitry Andric     llvm::consumeError(expected_py_return.takeError());
2369bdd1243dSDimitry Andric     return {};
2370bdd1243dSDimitry Andric   }
2371bdd1243dSDimitry Andric 
2372bdd1243dSDimitry Andric   PythonObject py_return = std::move(expected_py_return.get());
2373*0b57cec5SDimitry Andric 
2374*0b57cec5SDimitry Andric   ConstString ret_val;
2375*0b57cec5SDimitry Andric   bool got_string = false;
2376*0b57cec5SDimitry Andric   std::string buffer;
2377*0b57cec5SDimitry Andric 
2378*0b57cec5SDimitry Andric   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2379*0b57cec5SDimitry Andric     PythonString py_string(PyRefType::Borrowed, py_return.get());
2380*0b57cec5SDimitry Andric     llvm::StringRef return_data(py_string.GetString());
2381*0b57cec5SDimitry Andric     if (!return_data.empty()) {
2382*0b57cec5SDimitry Andric       buffer.assign(return_data.data(), return_data.size());
2383*0b57cec5SDimitry Andric       got_string = true;
2384*0b57cec5SDimitry Andric     }
2385*0b57cec5SDimitry Andric   }
2386*0b57cec5SDimitry Andric 
2387*0b57cec5SDimitry Andric   if (got_string)
2388*0b57cec5SDimitry Andric     ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
2389*0b57cec5SDimitry Andric 
2390*0b57cec5SDimitry Andric   return ret_val;
2391*0b57cec5SDimitry Andric }
2392*0b57cec5SDimitry Andric 
2393*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2394*0b57cec5SDimitry Andric     const char *impl_function, Process *process, std::string &output,
2395*0b57cec5SDimitry Andric     Status &error) {
2396*0b57cec5SDimitry Andric   bool ret_val;
2397*0b57cec5SDimitry Andric   if (!process) {
2398*0b57cec5SDimitry Andric     error.SetErrorString("no process");
2399*0b57cec5SDimitry Andric     return false;
2400*0b57cec5SDimitry Andric   }
2401*0b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
2402*0b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
2403*0b57cec5SDimitry Andric     return false;
2404*0b57cec5SDimitry Andric   }
2405*0b57cec5SDimitry Andric 
2406*0b57cec5SDimitry Andric   {
2407*0b57cec5SDimitry Andric     Locker py_lock(this,
2408*0b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2409*0b57cec5SDimitry Andric     ret_val = LLDBSWIGPythonRunScriptKeywordProcess(
24104824e7fdSDimitry Andric         impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
24114824e7fdSDimitry Andric         output);
2412*0b57cec5SDimitry Andric     if (!ret_val)
2413*0b57cec5SDimitry Andric       error.SetErrorString("python script evaluation failed");
2414*0b57cec5SDimitry Andric   }
2415*0b57cec5SDimitry Andric   return ret_val;
2416*0b57cec5SDimitry Andric }
2417*0b57cec5SDimitry Andric 
2418*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2419*0b57cec5SDimitry Andric     const char *impl_function, Thread *thread, std::string &output,
2420*0b57cec5SDimitry Andric     Status &error) {
2421*0b57cec5SDimitry Andric   if (!thread) {
2422*0b57cec5SDimitry Andric     error.SetErrorString("no thread");
2423*0b57cec5SDimitry Andric     return false;
2424*0b57cec5SDimitry Andric   }
2425*0b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
2426*0b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
2427*0b57cec5SDimitry Andric     return false;
2428*0b57cec5SDimitry Andric   }
2429*0b57cec5SDimitry Andric 
2430*0b57cec5SDimitry Andric   Locker py_lock(this,
2431*0b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2432bdd1243dSDimitry Andric   if (std::optional<std::string> result = LLDBSWIGPythonRunScriptKeywordThread(
24330eae32dcSDimitry Andric           impl_function, m_dictionary_name.c_str(),
24340eae32dcSDimitry Andric           thread->shared_from_this())) {
24350eae32dcSDimitry Andric     output = std::move(*result);
24360eae32dcSDimitry Andric     return true;
2437*0b57cec5SDimitry Andric   }
24380eae32dcSDimitry Andric   error.SetErrorString("python script evaluation failed");
24390eae32dcSDimitry Andric   return false;
2440*0b57cec5SDimitry Andric }
2441*0b57cec5SDimitry Andric 
2442*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2443*0b57cec5SDimitry Andric     const char *impl_function, Target *target, std::string &output,
2444*0b57cec5SDimitry Andric     Status &error) {
2445*0b57cec5SDimitry Andric   bool ret_val;
2446*0b57cec5SDimitry Andric   if (!target) {
2447*0b57cec5SDimitry Andric     error.SetErrorString("no thread");
2448*0b57cec5SDimitry Andric     return false;
2449*0b57cec5SDimitry Andric   }
2450*0b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
2451*0b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
2452*0b57cec5SDimitry Andric     return false;
2453*0b57cec5SDimitry Andric   }
2454*0b57cec5SDimitry Andric 
2455*0b57cec5SDimitry Andric   {
2456*0b57cec5SDimitry Andric     TargetSP target_sp(target->shared_from_this());
2457*0b57cec5SDimitry Andric     Locker py_lock(this,
2458*0b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2459*0b57cec5SDimitry Andric     ret_val = LLDBSWIGPythonRunScriptKeywordTarget(
2460*0b57cec5SDimitry Andric         impl_function, m_dictionary_name.c_str(), target_sp, output);
2461*0b57cec5SDimitry Andric     if (!ret_val)
2462*0b57cec5SDimitry Andric       error.SetErrorString("python script evaluation failed");
2463*0b57cec5SDimitry Andric   }
2464*0b57cec5SDimitry Andric   return ret_val;
2465*0b57cec5SDimitry Andric }
2466*0b57cec5SDimitry Andric 
2467*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2468*0b57cec5SDimitry Andric     const char *impl_function, StackFrame *frame, std::string &output,
2469*0b57cec5SDimitry Andric     Status &error) {
2470*0b57cec5SDimitry Andric   if (!frame) {
2471*0b57cec5SDimitry Andric     error.SetErrorString("no frame");
2472*0b57cec5SDimitry Andric     return false;
2473*0b57cec5SDimitry Andric   }
2474*0b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
2475*0b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
2476*0b57cec5SDimitry Andric     return false;
2477*0b57cec5SDimitry Andric   }
2478*0b57cec5SDimitry Andric 
2479*0b57cec5SDimitry Andric   Locker py_lock(this,
2480*0b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2481bdd1243dSDimitry Andric   if (std::optional<std::string> result = LLDBSWIGPythonRunScriptKeywordFrame(
24820eae32dcSDimitry Andric           impl_function, m_dictionary_name.c_str(),
24830eae32dcSDimitry Andric           frame->shared_from_this())) {
24840eae32dcSDimitry Andric     output = std::move(*result);
24850eae32dcSDimitry Andric     return true;
2486*0b57cec5SDimitry Andric   }
24870eae32dcSDimitry Andric   error.SetErrorString("python script evaluation failed");
24880eae32dcSDimitry Andric   return false;
2489*0b57cec5SDimitry Andric }
2490*0b57cec5SDimitry Andric 
2491*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2492*0b57cec5SDimitry Andric     const char *impl_function, ValueObject *value, std::string &output,
2493*0b57cec5SDimitry Andric     Status &error) {
2494*0b57cec5SDimitry Andric   bool ret_val;
2495*0b57cec5SDimitry Andric   if (!value) {
2496*0b57cec5SDimitry Andric     error.SetErrorString("no value");
2497*0b57cec5SDimitry Andric     return false;
2498*0b57cec5SDimitry Andric   }
2499*0b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
2500*0b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
2501*0b57cec5SDimitry Andric     return false;
2502*0b57cec5SDimitry Andric   }
2503*0b57cec5SDimitry Andric 
2504*0b57cec5SDimitry Andric   {
2505*0b57cec5SDimitry Andric     Locker py_lock(this,
2506*0b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2507*0b57cec5SDimitry Andric     ret_val = LLDBSWIGPythonRunScriptKeywordValue(
25084824e7fdSDimitry Andric         impl_function, m_dictionary_name.c_str(), value->GetSP(), output);
2509*0b57cec5SDimitry Andric     if (!ret_val)
2510*0b57cec5SDimitry Andric       error.SetErrorString("python script evaluation failed");
2511*0b57cec5SDimitry Andric   }
2512*0b57cec5SDimitry Andric   return ret_val;
2513*0b57cec5SDimitry Andric }
2514*0b57cec5SDimitry Andric 
2515*0b57cec5SDimitry Andric uint64_t replace_all(std::string &str, const std::string &oldStr,
2516*0b57cec5SDimitry Andric                      const std::string &newStr) {
2517*0b57cec5SDimitry Andric   size_t pos = 0;
2518*0b57cec5SDimitry Andric   uint64_t matches = 0;
2519*0b57cec5SDimitry Andric   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2520*0b57cec5SDimitry Andric     matches++;
2521*0b57cec5SDimitry Andric     str.replace(pos, oldStr.length(), newStr);
2522*0b57cec5SDimitry Andric     pos += newStr.length();
2523*0b57cec5SDimitry Andric   }
2524*0b57cec5SDimitry Andric   return matches;
2525*0b57cec5SDimitry Andric }
2526*0b57cec5SDimitry Andric 
2527*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2528fe6060f1SDimitry Andric     const char *pathname, const LoadScriptOptions &options,
2529fe6060f1SDimitry Andric     lldb_private::Status &error, StructuredData::ObjectSP *module_sp,
2530fe6060f1SDimitry Andric     FileSpec extra_search_dir) {
2531e8d8bef9SDimitry Andric   namespace fs = llvm::sys::fs;
2532e8d8bef9SDimitry Andric   namespace path = llvm::sys::path;
2533e8d8bef9SDimitry Andric 
2534fe6060f1SDimitry Andric   ExecuteScriptOptions exc_options = ExecuteScriptOptions()
2535fe6060f1SDimitry Andric                                          .SetEnableIO(!options.GetSilent())
2536fe6060f1SDimitry Andric                                          .SetSetLLDBGlobals(false);
2537fe6060f1SDimitry Andric 
2538*0b57cec5SDimitry Andric   if (!pathname || !pathname[0]) {
2539fcaf7f86SDimitry Andric     error.SetErrorString("empty path");
2540*0b57cec5SDimitry Andric     return false;
2541*0b57cec5SDimitry Andric   }
2542*0b57cec5SDimitry Andric 
2543fe6060f1SDimitry Andric   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2544fe6060f1SDimitry Andric       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2545fe6060f1SDimitry Andric           exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2546fe6060f1SDimitry Andric 
2547fe6060f1SDimitry Andric   if (!io_redirect_or_error) {
2548fe6060f1SDimitry Andric     error = io_redirect_or_error.takeError();
2549fe6060f1SDimitry Andric     return false;
2550fe6060f1SDimitry Andric   }
2551fe6060f1SDimitry Andric 
2552fe6060f1SDimitry Andric   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
2553*0b57cec5SDimitry Andric 
2554*0b57cec5SDimitry Andric   // Before executing Python code, lock the GIL.
2555*0b57cec5SDimitry Andric   Locker py_lock(this,
2556*0b57cec5SDimitry Andric                  Locker::AcquireLock |
2557fe6060f1SDimitry Andric                      (options.GetInitSession() ? Locker::InitSession : 0) |
2558fe6060f1SDimitry Andric                      Locker::NoSTDIN,
2559*0b57cec5SDimitry Andric                  Locker::FreeAcquiredLock |
2560fe6060f1SDimitry Andric                      (options.GetInitSession() ? Locker::TearDownSession : 0),
2561fe6060f1SDimitry Andric                  io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2562fe6060f1SDimitry Andric                  io_redirect.GetErrorFile());
2563*0b57cec5SDimitry Andric 
2564fe6060f1SDimitry Andric   auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2565e8d8bef9SDimitry Andric     if (directory.empty()) {
2566e8d8bef9SDimitry Andric       return llvm::make_error<llvm::StringError>(
2567e8d8bef9SDimitry Andric           "invalid directory name", llvm::inconvertibleErrorCode());
2568*0b57cec5SDimitry Andric     }
2569*0b57cec5SDimitry Andric 
2570*0b57cec5SDimitry Andric     replace_all(directory, "\\", "\\\\");
2571*0b57cec5SDimitry Andric     replace_all(directory, "'", "\\'");
2572*0b57cec5SDimitry Andric 
2573e8d8bef9SDimitry Andric     // Make sure that Python has "directory" in the search path.
2574*0b57cec5SDimitry Andric     StreamString command_stream;
2575*0b57cec5SDimitry Andric     command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
2576*0b57cec5SDimitry Andric                           "sys.path.insert(1,'%s');\n\n",
2577*0b57cec5SDimitry Andric                           directory.c_str(), directory.c_str());
2578*0b57cec5SDimitry Andric     bool syspath_retval =
2579fe6060f1SDimitry Andric         ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
2580*0b57cec5SDimitry Andric     if (!syspath_retval) {
2581e8d8bef9SDimitry Andric       return llvm::make_error<llvm::StringError>(
2582e8d8bef9SDimitry Andric           "Python sys.path handling failed", llvm::inconvertibleErrorCode());
2583*0b57cec5SDimitry Andric     }
2584*0b57cec5SDimitry Andric 
2585e8d8bef9SDimitry Andric     return llvm::Error::success();
2586e8d8bef9SDimitry Andric   };
2587e8d8bef9SDimitry Andric 
2588e8d8bef9SDimitry Andric   std::string module_name(pathname);
2589fe6060f1SDimitry Andric   bool possible_package = false;
2590e8d8bef9SDimitry Andric 
2591e8d8bef9SDimitry Andric   if (extra_search_dir) {
2592e8d8bef9SDimitry Andric     if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2593e8d8bef9SDimitry Andric       error = std::move(e);
2594e8d8bef9SDimitry Andric       return false;
2595*0b57cec5SDimitry Andric     }
2596*0b57cec5SDimitry Andric   } else {
2597e8d8bef9SDimitry Andric     FileSpec module_file(pathname);
2598e8d8bef9SDimitry Andric     FileSystem::Instance().Resolve(module_file);
2599e8d8bef9SDimitry Andric 
2600e8d8bef9SDimitry Andric     fs::file_status st;
2601e8d8bef9SDimitry Andric     std::error_code ec = status(module_file.GetPath(), st);
2602e8d8bef9SDimitry Andric 
2603e8d8bef9SDimitry Andric     if (ec || st.type() == fs::file_type::status_error ||
2604e8d8bef9SDimitry Andric         st.type() == fs::file_type::type_unknown ||
2605e8d8bef9SDimitry Andric         st.type() == fs::file_type::file_not_found) {
2606e8d8bef9SDimitry Andric       // if not a valid file of any sort, check if it might be a filename still
2607e8d8bef9SDimitry Andric       // dot can't be used but / and \ can, and if either is found, reject
2608e8d8bef9SDimitry Andric       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2609fcaf7f86SDimitry Andric         error.SetErrorStringWithFormatv("invalid pathname '{0}'", pathname);
2610e8d8bef9SDimitry Andric         return false;
2611e8d8bef9SDimitry Andric       }
2612e8d8bef9SDimitry Andric       // Not a filename, probably a package of some sort, let it go through.
2613fe6060f1SDimitry Andric       possible_package = true;
2614e8d8bef9SDimitry Andric     } else if (is_directory(st) || is_regular_file(st)) {
2615e8d8bef9SDimitry Andric       if (module_file.GetDirectory().IsEmpty()) {
2616fcaf7f86SDimitry Andric         error.SetErrorStringWithFormatv("invalid directory name '{0}'", pathname);
2617e8d8bef9SDimitry Andric         return false;
2618e8d8bef9SDimitry Andric       }
2619e8d8bef9SDimitry Andric       if (llvm::Error e =
2620e8d8bef9SDimitry Andric               ExtendSysPath(module_file.GetDirectory().GetCString())) {
2621e8d8bef9SDimitry Andric         error = std::move(e);
2622e8d8bef9SDimitry Andric         return false;
2623e8d8bef9SDimitry Andric       }
2624e8d8bef9SDimitry Andric       module_name = module_file.GetFilename().GetCString();
2625e8d8bef9SDimitry Andric     } else {
2626*0b57cec5SDimitry Andric       error.SetErrorString("no known way to import this module specification");
2627*0b57cec5SDimitry Andric       return false;
2628*0b57cec5SDimitry Andric     }
2629e8d8bef9SDimitry Andric   }
2630e8d8bef9SDimitry Andric 
2631e8d8bef9SDimitry Andric   // Strip .py or .pyc extension
2632e8d8bef9SDimitry Andric   llvm::StringRef extension = llvm::sys::path::extension(module_name);
2633e8d8bef9SDimitry Andric   if (!extension.empty()) {
2634e8d8bef9SDimitry Andric     if (extension == ".py")
2635e8d8bef9SDimitry Andric       module_name.resize(module_name.length() - 3);
2636e8d8bef9SDimitry Andric     else if (extension == ".pyc")
2637e8d8bef9SDimitry Andric       module_name.resize(module_name.length() - 4);
2638e8d8bef9SDimitry Andric   }
2639*0b57cec5SDimitry Andric 
2640fe6060f1SDimitry Andric   if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2641fe6060f1SDimitry Andric     error.SetErrorStringWithFormat(
2642fe6060f1SDimitry Andric         "Python does not allow dots in module names: %s", module_name.c_str());
2643fe6060f1SDimitry Andric     return false;
2644fe6060f1SDimitry Andric   }
2645fe6060f1SDimitry Andric 
2646fe6060f1SDimitry Andric   if (module_name.find('-') != llvm::StringRef::npos) {
2647fe6060f1SDimitry Andric     error.SetErrorStringWithFormat(
2648fe6060f1SDimitry Andric         "Python discourages dashes in module names: %s", module_name.c_str());
2649fe6060f1SDimitry Andric     return false;
2650fe6060f1SDimitry Andric   }
2651fe6060f1SDimitry Andric 
2652fe6060f1SDimitry Andric   // Check if the module is already imported.
2653e8d8bef9SDimitry Andric   StreamString command_stream;
2654*0b57cec5SDimitry Andric   command_stream.Clear();
2655e8d8bef9SDimitry Andric   command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
2656*0b57cec5SDimitry Andric   bool does_contain = false;
2657fe6060f1SDimitry Andric   // This call will succeed if the module was ever imported in any Debugger in
2658fe6060f1SDimitry Andric   // the lifetime of the process in which this LLDB framework is living.
2659fe6060f1SDimitry Andric   const bool does_contain_executed = ExecuteOneLineWithReturn(
2660*0b57cec5SDimitry Andric       command_stream.GetData(),
2661fe6060f1SDimitry Andric       ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options);
2662fe6060f1SDimitry Andric 
2663fe6060f1SDimitry Andric   const bool was_imported_globally = does_contain_executed && does_contain;
2664fe6060f1SDimitry Andric   const bool was_imported_locally =
2665fe6060f1SDimitry Andric       GetSessionDictionary()
2666e8d8bef9SDimitry Andric           .GetItemForKey(PythonString(module_name))
2667*0b57cec5SDimitry Andric           .IsAllocated();
2668*0b57cec5SDimitry Andric 
2669*0b57cec5SDimitry Andric   // now actually do the import
2670*0b57cec5SDimitry Andric   command_stream.Clear();
2671*0b57cec5SDimitry Andric 
2672fe6060f1SDimitry Andric   if (was_imported_globally || was_imported_locally) {
2673*0b57cec5SDimitry Andric     if (!was_imported_locally)
2674e8d8bef9SDimitry Andric       command_stream.Printf("import %s ; reload_module(%s)",
2675e8d8bef9SDimitry Andric                             module_name.c_str(), module_name.c_str());
2676*0b57cec5SDimitry Andric     else
2677e8d8bef9SDimitry Andric       command_stream.Printf("reload_module(%s)", module_name.c_str());
2678*0b57cec5SDimitry Andric   } else
2679e8d8bef9SDimitry Andric     command_stream.Printf("import %s", module_name.c_str());
2680*0b57cec5SDimitry Andric 
2681fe6060f1SDimitry Andric   error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
2682*0b57cec5SDimitry Andric   if (error.Fail())
2683*0b57cec5SDimitry Andric     return false;
2684*0b57cec5SDimitry Andric 
2685*0b57cec5SDimitry Andric   // if we are here, everything worked
2686*0b57cec5SDimitry Andric   // call __lldb_init_module(debugger,dict)
2687e8d8bef9SDimitry Andric   if (!LLDBSwigPythonCallModuleInit(module_name.c_str(),
26880eae32dcSDimitry Andric                                     m_dictionary_name.c_str(),
26890eae32dcSDimitry Andric                                     m_debugger.shared_from_this())) {
2690*0b57cec5SDimitry Andric     error.SetErrorString("calling __lldb_init_module failed");
2691*0b57cec5SDimitry Andric     return false;
2692*0b57cec5SDimitry Andric   }
2693*0b57cec5SDimitry Andric 
2694*0b57cec5SDimitry Andric   if (module_sp) {
2695*0b57cec5SDimitry Andric     // everything went just great, now set the module object
2696*0b57cec5SDimitry Andric     command_stream.Clear();
2697e8d8bef9SDimitry Andric     command_stream.Printf("%s", module_name.c_str());
2698*0b57cec5SDimitry Andric     void *module_pyobj = nullptr;
2699*0b57cec5SDimitry Andric     if (ExecuteOneLineWithReturn(
2700*0b57cec5SDimitry Andric             command_stream.GetData(),
2701fe6060f1SDimitry Andric             ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2702fe6060f1SDimitry Andric             exc_options) &&
2703*0b57cec5SDimitry Andric         module_pyobj)
270404eeddc0SDimitry Andric       *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
270504eeddc0SDimitry Andric           PyRefType::Owned, static_cast<PyObject *>(module_pyobj)));
2706*0b57cec5SDimitry Andric   }
2707*0b57cec5SDimitry Andric 
2708*0b57cec5SDimitry Andric   return true;
2709*0b57cec5SDimitry Andric }
2710*0b57cec5SDimitry Andric 
2711*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
2712*0b57cec5SDimitry Andric   if (!word || !word[0])
2713*0b57cec5SDimitry Andric     return false;
2714*0b57cec5SDimitry Andric 
2715*0b57cec5SDimitry Andric   llvm::StringRef word_sr(word);
2716*0b57cec5SDimitry Andric 
2717*0b57cec5SDimitry Andric   // filter out a few characters that would just confuse us and that are
2718*0b57cec5SDimitry Andric   // clearly not keyword material anyway
2719*0b57cec5SDimitry Andric   if (word_sr.find('"') != llvm::StringRef::npos ||
2720*0b57cec5SDimitry Andric       word_sr.find('\'') != llvm::StringRef::npos)
2721*0b57cec5SDimitry Andric     return false;
2722*0b57cec5SDimitry Andric 
2723*0b57cec5SDimitry Andric   StreamString command_stream;
2724*0b57cec5SDimitry Andric   command_stream.Printf("keyword.iskeyword('%s')", word);
2725*0b57cec5SDimitry Andric   bool result;
2726*0b57cec5SDimitry Andric   ExecuteScriptOptions options;
2727*0b57cec5SDimitry Andric   options.SetEnableIO(false);
2728*0b57cec5SDimitry Andric   options.SetMaskoutErrors(true);
2729*0b57cec5SDimitry Andric   options.SetSetLLDBGlobals(false);
2730*0b57cec5SDimitry Andric   if (ExecuteOneLineWithReturn(command_stream.GetData(),
2731*0b57cec5SDimitry Andric                                ScriptInterpreter::eScriptReturnTypeBool,
2732*0b57cec5SDimitry Andric                                &result, options))
2733*0b57cec5SDimitry Andric     return result;
2734*0b57cec5SDimitry Andric   return false;
2735*0b57cec5SDimitry Andric }
2736*0b57cec5SDimitry Andric 
2737*0b57cec5SDimitry Andric ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2738*0b57cec5SDimitry Andric     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2739*0b57cec5SDimitry Andric     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2740*0b57cec5SDimitry Andric       m_old_asynch(debugger_sp->GetAsyncExecution()) {
2741*0b57cec5SDimitry Andric   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2742*0b57cec5SDimitry Andric     m_debugger_sp->SetAsyncExecution(false);
2743*0b57cec5SDimitry Andric   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2744*0b57cec5SDimitry Andric     m_debugger_sp->SetAsyncExecution(true);
2745*0b57cec5SDimitry Andric }
2746*0b57cec5SDimitry Andric 
2747*0b57cec5SDimitry Andric ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
2748*0b57cec5SDimitry Andric   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2749*0b57cec5SDimitry Andric     m_debugger_sp->SetAsyncExecution(m_old_asynch);
2750*0b57cec5SDimitry Andric }
2751*0b57cec5SDimitry Andric 
2752*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2753*0b57cec5SDimitry Andric     const char *impl_function, llvm::StringRef args,
2754*0b57cec5SDimitry Andric     ScriptedCommandSynchronicity synchronicity,
2755*0b57cec5SDimitry Andric     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2756*0b57cec5SDimitry Andric     const lldb_private::ExecutionContext &exe_ctx) {
2757*0b57cec5SDimitry Andric   if (!impl_function) {
2758*0b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
2759*0b57cec5SDimitry Andric     return false;
2760*0b57cec5SDimitry Andric   }
2761*0b57cec5SDimitry Andric 
2762*0b57cec5SDimitry Andric   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2763*0b57cec5SDimitry Andric   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2764*0b57cec5SDimitry Andric 
2765*0b57cec5SDimitry Andric   if (!debugger_sp.get()) {
2766*0b57cec5SDimitry Andric     error.SetErrorString("invalid Debugger pointer");
2767*0b57cec5SDimitry Andric     return false;
2768*0b57cec5SDimitry Andric   }
2769*0b57cec5SDimitry Andric 
2770*0b57cec5SDimitry Andric   bool ret_val = false;
2771*0b57cec5SDimitry Andric 
2772*0b57cec5SDimitry Andric   std::string err_msg;
2773*0b57cec5SDimitry Andric 
2774*0b57cec5SDimitry Andric   {
2775*0b57cec5SDimitry Andric     Locker py_lock(this,
2776*0b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession |
2777*0b57cec5SDimitry Andric                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2778*0b57cec5SDimitry Andric                    Locker::FreeLock | Locker::TearDownSession);
2779*0b57cec5SDimitry Andric 
2780*0b57cec5SDimitry Andric     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2781*0b57cec5SDimitry Andric 
2782*0b57cec5SDimitry Andric     std::string args_str = args.str();
2783*0b57cec5SDimitry Andric     ret_val = LLDBSwigPythonCallCommand(
2784*0b57cec5SDimitry Andric         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2785*0b57cec5SDimitry Andric         cmd_retobj, exe_ctx_ref_sp);
2786*0b57cec5SDimitry Andric   }
2787*0b57cec5SDimitry Andric 
2788*0b57cec5SDimitry Andric   if (!ret_val)
2789*0b57cec5SDimitry Andric     error.SetErrorString("unable to execute script function");
2790bdd1243dSDimitry Andric   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2791bdd1243dSDimitry Andric     return false;
2792*0b57cec5SDimitry Andric 
2793bdd1243dSDimitry Andric   error.Clear();
2794*0b57cec5SDimitry Andric   return ret_val;
2795*0b57cec5SDimitry Andric }
2796*0b57cec5SDimitry Andric 
2797*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2798*0b57cec5SDimitry Andric     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
2799*0b57cec5SDimitry Andric     ScriptedCommandSynchronicity synchronicity,
2800*0b57cec5SDimitry Andric     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2801*0b57cec5SDimitry Andric     const lldb_private::ExecutionContext &exe_ctx) {
2802*0b57cec5SDimitry Andric   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2803*0b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
2804*0b57cec5SDimitry Andric     return false;
2805*0b57cec5SDimitry Andric   }
2806*0b57cec5SDimitry Andric 
2807*0b57cec5SDimitry Andric   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2808*0b57cec5SDimitry Andric   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2809*0b57cec5SDimitry Andric 
2810*0b57cec5SDimitry Andric   if (!debugger_sp.get()) {
2811*0b57cec5SDimitry Andric     error.SetErrorString("invalid Debugger pointer");
2812*0b57cec5SDimitry Andric     return false;
2813*0b57cec5SDimitry Andric   }
2814*0b57cec5SDimitry Andric 
2815*0b57cec5SDimitry Andric   bool ret_val = false;
2816*0b57cec5SDimitry Andric 
2817*0b57cec5SDimitry Andric   std::string err_msg;
2818*0b57cec5SDimitry Andric 
2819*0b57cec5SDimitry Andric   {
2820*0b57cec5SDimitry Andric     Locker py_lock(this,
2821*0b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession |
2822*0b57cec5SDimitry Andric                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2823*0b57cec5SDimitry Andric                    Locker::FreeLock | Locker::TearDownSession);
2824*0b57cec5SDimitry Andric 
2825*0b57cec5SDimitry Andric     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2826*0b57cec5SDimitry Andric 
2827*0b57cec5SDimitry Andric     std::string args_str = args.str();
28284824e7fdSDimitry Andric     ret_val = LLDBSwigPythonCallCommandObject(
28294824e7fdSDimitry Andric         static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
28304824e7fdSDimitry Andric         args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
2831*0b57cec5SDimitry Andric   }
2832*0b57cec5SDimitry Andric 
2833*0b57cec5SDimitry Andric   if (!ret_val)
2834*0b57cec5SDimitry Andric     error.SetErrorString("unable to execute script function");
2835bdd1243dSDimitry Andric   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2836bdd1243dSDimitry Andric     return false;
2837*0b57cec5SDimitry Andric 
2838bdd1243dSDimitry Andric   error.Clear();
2839*0b57cec5SDimitry Andric   return ret_val;
2840*0b57cec5SDimitry Andric }
2841*0b57cec5SDimitry Andric 
28425ffd83dbSDimitry Andric /// In Python, a special attribute __doc__ contains the docstring for an object
28435ffd83dbSDimitry Andric /// (function, method, class, ...) if any is defined Otherwise, the attribute's
28445ffd83dbSDimitry Andric /// value is None.
2845*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
2846*0b57cec5SDimitry Andric                                                           std::string &dest) {
2847*0b57cec5SDimitry Andric   dest.clear();
28485ffd83dbSDimitry Andric 
2849*0b57cec5SDimitry Andric   if (!item || !*item)
2850*0b57cec5SDimitry Andric     return false;
28515ffd83dbSDimitry Andric 
2852*0b57cec5SDimitry Andric   std::string command(item);
2853*0b57cec5SDimitry Andric   command += ".__doc__";
2854*0b57cec5SDimitry Andric 
28555ffd83dbSDimitry Andric   // Python is going to point this to valid data if ExecuteOneLineWithReturn
28565ffd83dbSDimitry Andric   // returns successfully.
28575ffd83dbSDimitry Andric   char *result_ptr = nullptr;
2858*0b57cec5SDimitry Andric 
2859*0b57cec5SDimitry Andric   if (ExecuteOneLineWithReturn(
28605ffd83dbSDimitry Andric           command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
2861*0b57cec5SDimitry Andric           &result_ptr,
2862fe6060f1SDimitry Andric           ExecuteScriptOptions().SetEnableIO(false))) {
2863*0b57cec5SDimitry Andric     if (result_ptr)
2864*0b57cec5SDimitry Andric       dest.assign(result_ptr);
2865*0b57cec5SDimitry Andric     return true;
2866*0b57cec5SDimitry Andric   }
28675ffd83dbSDimitry Andric 
28685ffd83dbSDimitry Andric   StreamString str_stream;
28695ffd83dbSDimitry Andric   str_stream << "Function " << item
28705ffd83dbSDimitry Andric              << " was not found. Containing module might be missing.";
28715ffd83dbSDimitry Andric   dest = std::string(str_stream.GetString());
28725ffd83dbSDimitry Andric 
28735ffd83dbSDimitry Andric   return false;
2874*0b57cec5SDimitry Andric }
2875*0b57cec5SDimitry Andric 
2876*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
2877*0b57cec5SDimitry Andric     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2878*0b57cec5SDimitry Andric   dest.clear();
2879*0b57cec5SDimitry Andric 
2880*0b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2881*0b57cec5SDimitry Andric 
2882*0b57cec5SDimitry Andric   if (!cmd_obj_sp)
2883*0b57cec5SDimitry Andric     return false;
2884*0b57cec5SDimitry Andric 
2885*0b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
2886*0b57cec5SDimitry Andric                            (PyObject *)cmd_obj_sp->GetValue());
2887*0b57cec5SDimitry Andric 
2888*0b57cec5SDimitry Andric   if (!implementor.IsAllocated())
2889*0b57cec5SDimitry Andric     return false;
2890*0b57cec5SDimitry Andric 
2891bdd1243dSDimitry Andric   llvm::Expected<PythonObject> expected_py_return =
2892bdd1243dSDimitry Andric       implementor.CallMethod("get_short_help");
2893*0b57cec5SDimitry Andric 
2894bdd1243dSDimitry Andric   if (!expected_py_return) {
2895bdd1243dSDimitry Andric     llvm::consumeError(expected_py_return.takeError());
2896*0b57cec5SDimitry Andric     return false;
2897*0b57cec5SDimitry Andric   }
2898*0b57cec5SDimitry Andric 
2899bdd1243dSDimitry Andric   PythonObject py_return = std::move(expected_py_return.get());
2900*0b57cec5SDimitry Andric 
2901*0b57cec5SDimitry Andric   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2902*0b57cec5SDimitry Andric     PythonString py_string(PyRefType::Borrowed, py_return.get());
2903*0b57cec5SDimitry Andric     llvm::StringRef return_data(py_string.GetString());
2904*0b57cec5SDimitry Andric     dest.assign(return_data.data(), return_data.size());
29055ffd83dbSDimitry Andric     return true;
2906*0b57cec5SDimitry Andric   }
29075ffd83dbSDimitry Andric 
29085ffd83dbSDimitry Andric   return false;
2909*0b57cec5SDimitry Andric }
2910*0b57cec5SDimitry Andric 
2911*0b57cec5SDimitry Andric uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
2912*0b57cec5SDimitry Andric     StructuredData::GenericSP cmd_obj_sp) {
2913*0b57cec5SDimitry Andric   uint32_t result = 0;
2914*0b57cec5SDimitry Andric 
2915*0b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2916*0b57cec5SDimitry Andric 
2917*0b57cec5SDimitry Andric   static char callee_name[] = "get_flags";
2918*0b57cec5SDimitry Andric 
2919*0b57cec5SDimitry Andric   if (!cmd_obj_sp)
2920*0b57cec5SDimitry Andric     return result;
2921*0b57cec5SDimitry Andric 
2922*0b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
2923*0b57cec5SDimitry Andric                            (PyObject *)cmd_obj_sp->GetValue());
2924*0b57cec5SDimitry Andric 
2925*0b57cec5SDimitry Andric   if (!implementor.IsAllocated())
2926*0b57cec5SDimitry Andric     return result;
2927*0b57cec5SDimitry Andric 
2928*0b57cec5SDimitry Andric   PythonObject pmeth(PyRefType::Owned,
2929*0b57cec5SDimitry Andric                      PyObject_GetAttrString(implementor.get(), callee_name));
2930*0b57cec5SDimitry Andric 
2931*0b57cec5SDimitry Andric   if (PyErr_Occurred())
2932*0b57cec5SDimitry Andric     PyErr_Clear();
2933*0b57cec5SDimitry Andric 
2934*0b57cec5SDimitry Andric   if (!pmeth.IsAllocated())
2935*0b57cec5SDimitry Andric     return result;
2936*0b57cec5SDimitry Andric 
2937*0b57cec5SDimitry Andric   if (PyCallable_Check(pmeth.get()) == 0) {
2938*0b57cec5SDimitry Andric     if (PyErr_Occurred())
2939*0b57cec5SDimitry Andric       PyErr_Clear();
2940*0b57cec5SDimitry Andric     return result;
2941*0b57cec5SDimitry Andric   }
2942*0b57cec5SDimitry Andric 
2943*0b57cec5SDimitry Andric   if (PyErr_Occurred())
2944*0b57cec5SDimitry Andric     PyErr_Clear();
2945*0b57cec5SDimitry Andric 
29465ffd83dbSDimitry Andric   long long py_return = unwrapOrSetPythonException(
29475ffd83dbSDimitry Andric       As<long long>(implementor.CallMethod(callee_name)));
2948*0b57cec5SDimitry Andric 
2949*0b57cec5SDimitry Andric   // if it fails, print the error but otherwise go on
2950*0b57cec5SDimitry Andric   if (PyErr_Occurred()) {
2951*0b57cec5SDimitry Andric     PyErr_Print();
2952*0b57cec5SDimitry Andric     PyErr_Clear();
29535ffd83dbSDimitry Andric   } else {
29545ffd83dbSDimitry Andric     result = py_return;
2955*0b57cec5SDimitry Andric   }
2956*0b57cec5SDimitry Andric 
2957*0b57cec5SDimitry Andric   return result;
2958*0b57cec5SDimitry Andric }
2959*0b57cec5SDimitry Andric 
2960*0b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
2961*0b57cec5SDimitry Andric     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2962*0b57cec5SDimitry Andric   dest.clear();
2963*0b57cec5SDimitry Andric 
2964*0b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2965*0b57cec5SDimitry Andric 
2966*0b57cec5SDimitry Andric   if (!cmd_obj_sp)
2967*0b57cec5SDimitry Andric     return false;
2968*0b57cec5SDimitry Andric 
2969*0b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
2970*0b57cec5SDimitry Andric                            (PyObject *)cmd_obj_sp->GetValue());
2971*0b57cec5SDimitry Andric 
2972*0b57cec5SDimitry Andric   if (!implementor.IsAllocated())
2973*0b57cec5SDimitry Andric     return false;
2974*0b57cec5SDimitry Andric 
2975bdd1243dSDimitry Andric   llvm::Expected<PythonObject> expected_py_return =
2976bdd1243dSDimitry Andric       implementor.CallMethod("get_long_help");
2977*0b57cec5SDimitry Andric 
2978bdd1243dSDimitry Andric   if (!expected_py_return) {
2979bdd1243dSDimitry Andric     llvm::consumeError(expected_py_return.takeError());
2980*0b57cec5SDimitry Andric     return false;
2981*0b57cec5SDimitry Andric   }
2982*0b57cec5SDimitry Andric 
2983bdd1243dSDimitry Andric   PythonObject py_return = std::move(expected_py_return.get());
2984*0b57cec5SDimitry Andric 
2985bdd1243dSDimitry Andric   bool got_string = false;
2986*0b57cec5SDimitry Andric   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2987*0b57cec5SDimitry Andric     PythonString str(PyRefType::Borrowed, py_return.get());
2988*0b57cec5SDimitry Andric     llvm::StringRef str_data(str.GetString());
2989*0b57cec5SDimitry Andric     dest.assign(str_data.data(), str_data.size());
2990*0b57cec5SDimitry Andric     got_string = true;
2991*0b57cec5SDimitry Andric   }
2992*0b57cec5SDimitry Andric 
2993*0b57cec5SDimitry Andric   return got_string;
2994*0b57cec5SDimitry Andric }
2995*0b57cec5SDimitry Andric 
2996*0b57cec5SDimitry Andric std::unique_ptr<ScriptInterpreterLocker>
2997*0b57cec5SDimitry Andric ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
2998*0b57cec5SDimitry Andric   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
2999*0b57cec5SDimitry Andric       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3000*0b57cec5SDimitry Andric       Locker::FreeLock | Locker::TearDownSession));
3001*0b57cec5SDimitry Andric   return py_lock;
3002*0b57cec5SDimitry Andric }
3003*0b57cec5SDimitry Andric 
300404eeddc0SDimitry Andric void ScriptInterpreterPythonImpl::Initialize() {
3005e8d8bef9SDimitry Andric   LLDB_SCOPED_TIMER();
3006*0b57cec5SDimitry Andric 
3007*0b57cec5SDimitry Andric   // RAII-based initialization which correctly handles multiple-initialization,
3008*0b57cec5SDimitry Andric   // version- specific differences among Python 2 and Python 3, and saving and
3009*0b57cec5SDimitry Andric   // restoring various other pieces of state that can get mucked with during
3010*0b57cec5SDimitry Andric   // initialization.
3011*0b57cec5SDimitry Andric   InitializePythonRAII initialize_guard;
3012*0b57cec5SDimitry Andric 
3013*0b57cec5SDimitry Andric   LLDBSwigPyInit();
3014*0b57cec5SDimitry Andric 
3015*0b57cec5SDimitry Andric   // Update the path python uses to search for modules to include the current
3016*0b57cec5SDimitry Andric   // directory.
3017*0b57cec5SDimitry Andric 
3018*0b57cec5SDimitry Andric   PyRun_SimpleString("import sys");
3019*0b57cec5SDimitry Andric   AddToSysPath(AddLocation::End, ".");
3020*0b57cec5SDimitry Andric 
3021*0b57cec5SDimitry Andric   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
3022*0b57cec5SDimitry Andric   // that use a backslash as the path separator, this will result in executing
3023*0b57cec5SDimitry Andric   // python code containing paths with unescaped backslashes.  But Python also
3024*0b57cec5SDimitry Andric   // accepts forward slashes, so to make life easier we just use that.
3025*0b57cec5SDimitry Andric   if (FileSpec file_spec = GetPythonDir())
3026*0b57cec5SDimitry Andric     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3027*0b57cec5SDimitry Andric   if (FileSpec file_spec = HostInfo::GetShlibDir())
3028*0b57cec5SDimitry Andric     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3029*0b57cec5SDimitry Andric 
3030*0b57cec5SDimitry Andric   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3031*0b57cec5SDimitry Andric                      "lldb.embedded_interpreter; from "
3032*0b57cec5SDimitry Andric                      "lldb.embedded_interpreter import run_python_interpreter; "
3033*0b57cec5SDimitry Andric                      "from lldb.embedded_interpreter import run_one_line");
303404eeddc0SDimitry Andric 
303504eeddc0SDimitry Andric #if LLDB_USE_PYTHON_SET_INTERRUPT
303604eeddc0SDimitry Andric   // Python will not just overwrite its internal SIGINT handler but also the
303704eeddc0SDimitry Andric   // one from the process. Backup the current SIGINT handler to prevent that
303804eeddc0SDimitry Andric   // Python deletes it.
303904eeddc0SDimitry Andric   RestoreSignalHandlerScope save_sigint(SIGINT);
304004eeddc0SDimitry Andric 
304104eeddc0SDimitry Andric   // Setup a default SIGINT signal handler that works the same way as the
304204eeddc0SDimitry Andric   // normal Python REPL signal handler which raises a KeyboardInterrupt.
304304eeddc0SDimitry Andric   // Also make sure to not pollute the user's REPL with the signal module nor
304404eeddc0SDimitry Andric   // our utility function.
304504eeddc0SDimitry Andric   PyRun_SimpleString("def lldb_setup_sigint_handler():\n"
304604eeddc0SDimitry Andric                      "  import signal;\n"
304704eeddc0SDimitry Andric                      "  def signal_handler(sig, frame):\n"
304804eeddc0SDimitry Andric                      "    raise KeyboardInterrupt()\n"
304904eeddc0SDimitry Andric                      "  signal.signal(signal.SIGINT, signal_handler);\n"
305004eeddc0SDimitry Andric                      "lldb_setup_sigint_handler();\n"
305104eeddc0SDimitry Andric                      "del lldb_setup_sigint_handler\n");
305204eeddc0SDimitry Andric #endif
3053*0b57cec5SDimitry Andric }
3054*0b57cec5SDimitry Andric 
3055*0b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3056*0b57cec5SDimitry Andric                                                std::string path) {
3057*0b57cec5SDimitry Andric   std::string path_copy;
3058*0b57cec5SDimitry Andric 
3059*0b57cec5SDimitry Andric   std::string statement;
3060*0b57cec5SDimitry Andric   if (location == AddLocation::Beginning) {
3061*0b57cec5SDimitry Andric     statement.assign("sys.path.insert(0,\"");
3062*0b57cec5SDimitry Andric     statement.append(path);
3063*0b57cec5SDimitry Andric     statement.append("\")");
3064*0b57cec5SDimitry Andric   } else {
3065*0b57cec5SDimitry Andric     statement.assign("sys.path.append(\"");
3066*0b57cec5SDimitry Andric     statement.append(path);
3067*0b57cec5SDimitry Andric     statement.append("\")");
3068*0b57cec5SDimitry Andric   }
3069*0b57cec5SDimitry Andric   PyRun_SimpleString(statement.c_str());
3070*0b57cec5SDimitry Andric }
3071*0b57cec5SDimitry Andric 
3072*0b57cec5SDimitry Andric // We are intentionally NOT calling Py_Finalize here (this would be the logical
3073*0b57cec5SDimitry Andric // place to call it).  Calling Py_Finalize here causes test suite runs to seg
3074*0b57cec5SDimitry Andric // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
3075*0b57cec5SDimitry Andric // be called 'at_exit'.  When the test suite Python harness finishes up, it
3076*0b57cec5SDimitry Andric // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3077*0b57cec5SDimitry Andric // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3078*0b57cec5SDimitry Andric // which calls ScriptInterpreter::Terminate, which calls
3079*0b57cec5SDimitry Andric // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
3080*0b57cec5SDimitry Andric // end up with Py_Finalize being called from within Py_Finalize, which results
3081*0b57cec5SDimitry Andric // in a seg fault. Since this function only gets called when lldb is shutting
3082*0b57cec5SDimitry Andric // down and going away anyway, the fact that we don't actually call Py_Finalize
3083*0b57cec5SDimitry Andric // should not cause any problems (everything should shut down/go away anyway
3084*0b57cec5SDimitry Andric // when the process exits).
3085*0b57cec5SDimitry Andric //
3086*0b57cec5SDimitry Andric // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3087*0b57cec5SDimitry Andric 
3088480093f4SDimitry Andric #endif
3089