180814287SRaphael Isemann //===-- ScriptInterpreterPython.cpp ---------------------------------------===//
22c1f46dcSZachary Turner //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
62c1f46dcSZachary Turner //
72c1f46dcSZachary Turner //===----------------------------------------------------------------------===//
82c1f46dcSZachary Turner 
959998b7bSJonas Devlieghere #include "lldb/Host/Config.h"
10d055e3a0SPedro Tammela #include "lldb/lldb-enumerations.h"
11d68983e3SPavel Labath 
124e26cf2cSJonas Devlieghere #if LLDB_ENABLE_PYTHON
13d68983e3SPavel Labath 
1441de9a97SKate Stone // LLDB Python header must be included first
152c1f46dcSZachary Turner #include "lldb-python.h"
1641de9a97SKate Stone 
172c1f46dcSZachary Turner #include "PythonDataObjects.h"
189357b5d0Sserge-sans-paille #include "PythonReadline.h"
191f6a57c1SMed Ismail Bennani #include "SWIGPythonBridge.h"
2063dd5d25SJonas Devlieghere #include "ScriptInterpreterPythonImpl.h"
211f6a57c1SMed Ismail Bennani #include "ScriptedProcessPythonInterface.h"
221f6a57c1SMed Ismail Bennani 
231f6a57c1SMed Ismail Bennani #include "lldb/API/SBError.h"
2441ae8e74SKuba Mracek #include "lldb/API/SBFrame.h"
2563dd5d25SJonas Devlieghere #include "lldb/API/SBValue.h"
262c1f46dcSZachary Turner #include "lldb/Breakpoint/StoppointCallbackContext.h"
272c1f46dcSZachary Turner #include "lldb/Breakpoint/WatchpointOptions.h"
282c1f46dcSZachary Turner #include "lldb/Core/Communication.h"
292c1f46dcSZachary Turner #include "lldb/Core/Debugger.h"
302c1f46dcSZachary Turner #include "lldb/Core/PluginManager.h"
312c1f46dcSZachary Turner #include "lldb/Core/ValueObject.h"
322c1f46dcSZachary Turner #include "lldb/DataFormatters/TypeSummary.h"
334eff2d31SZachary Turner #include "lldb/Host/FileSystem.h"
342c1f46dcSZachary Turner #include "lldb/Host/HostInfo.h"
352c1f46dcSZachary Turner #include "lldb/Host/Pipe.h"
362c1f46dcSZachary Turner #include "lldb/Interpreter/CommandInterpreter.h"
372c1f46dcSZachary Turner #include "lldb/Interpreter/CommandReturnObject.h"
382c1f46dcSZachary Turner #include "lldb/Target/Thread.h"
392c1f46dcSZachary Turner #include "lldb/Target/ThreadPlan.h"
405861234eSJonas Devlieghere #include "lldb/Utility/ReproducerInstrumentation.h"
4138d0632eSPavel Labath #include "lldb/Utility/Timer.h"
4222c8efcdSZachary Turner #include "llvm/ADT/STLExtras.h"
43b9c1b51eSKate Stone #include "llvm/ADT/StringRef.h"
44d79273c9SJonas Devlieghere #include "llvm/Support/Error.h"
457d86ee5aSZachary Turner #include "llvm/Support/FileSystem.h"
462fce1137SLawrence D'Anna #include "llvm/Support/FormatAdapters.h"
472c1f46dcSZachary Turner 
4876e47d48SRaphael Isemann #include <cstdio>
4976e47d48SRaphael Isemann #include <cstdlib>
509a6c7572SJonas Devlieghere #include <memory>
519a6c7572SJonas Devlieghere #include <mutex>
529a6c7572SJonas Devlieghere #include <string>
539a6c7572SJonas Devlieghere 
542c1f46dcSZachary Turner using namespace lldb;
552c1f46dcSZachary Turner using namespace lldb_private;
56722b6189SLawrence D'Anna using namespace lldb_private::python;
5704edd189SLawrence D'Anna using llvm::Expected;
582c1f46dcSZachary Turner 
59bba9ba8dSJonas Devlieghere LLDB_PLUGIN_DEFINE(ScriptInterpreterPython)
60fbb4d1e4SJonas Devlieghere 
61b01b1087SJonas Devlieghere // Defined in the SWIG source file
62b01b1087SJonas Devlieghere #if PY_MAJOR_VERSION >= 3
63b01b1087SJonas Devlieghere extern "C" PyObject *PyInit__lldb(void);
64b01b1087SJonas Devlieghere 
65b01b1087SJonas Devlieghere #define LLDBSwigPyInit PyInit__lldb
66b01b1087SJonas Devlieghere 
67b01b1087SJonas Devlieghere #else
68b01b1087SJonas Devlieghere extern "C" void init_lldb(void);
69b01b1087SJonas Devlieghere 
70b01b1087SJonas Devlieghere #define LLDBSwigPyInit init_lldb
71b01b1087SJonas Devlieghere #endif
72b01b1087SJonas Devlieghere 
73b01b1087SJonas Devlieghere 
74d055e3a0SPedro Tammela static ScriptInterpreterPythonImpl *GetPythonInterpreter(Debugger &debugger) {
75d055e3a0SPedro Tammela   ScriptInterpreter *script_interpreter =
76d055e3a0SPedro Tammela       debugger.GetScriptInterpreter(true, lldb::eScriptLanguagePython);
77d055e3a0SPedro Tammela   return static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
78d055e3a0SPedro Tammela }
79d055e3a0SPedro Tammela 
802c1f46dcSZachary Turner static bool g_initialized = false;
812c1f46dcSZachary Turner 
82b9c1b51eSKate Stone namespace {
8322c8efcdSZachary Turner 
8405097246SAdrian Prantl // Initializing Python is not a straightforward process.  We cannot control
8505097246SAdrian Prantl // what external code may have done before getting to this point in LLDB,
8605097246SAdrian Prantl // including potentially having already initialized Python, so we need to do a
8705097246SAdrian Prantl // lot of work to ensure that the existing state of the system is maintained
8805097246SAdrian Prantl // across our initialization.  We do this by using an RAII pattern where we
8905097246SAdrian Prantl // save off initial state at the beginning, and restore it at the end
90b9c1b51eSKate Stone struct InitializePythonRAII {
91079fe48aSZachary Turner public:
929494c510SJonas Devlieghere   InitializePythonRAII() {
93079fe48aSZachary Turner     InitializePythonHome();
94079fe48aSZachary Turner 
959357b5d0Sserge-sans-paille #ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
969357b5d0Sserge-sans-paille     // Python's readline is incompatible with libedit being linked into lldb.
979357b5d0Sserge-sans-paille     // Provide a patched version local to the embedded interpreter.
989357b5d0Sserge-sans-paille     bool ReadlinePatched = false;
999357b5d0Sserge-sans-paille     for (auto *p = PyImport_Inittab; p->name != NULL; p++) {
1009357b5d0Sserge-sans-paille       if (strcmp(p->name, "readline") == 0) {
1019357b5d0Sserge-sans-paille         p->initfunc = initlldb_readline;
1029357b5d0Sserge-sans-paille         break;
1039357b5d0Sserge-sans-paille       }
1049357b5d0Sserge-sans-paille     }
1059357b5d0Sserge-sans-paille     if (!ReadlinePatched) {
1069357b5d0Sserge-sans-paille       PyImport_AppendInittab("readline", initlldb_readline);
1079357b5d0Sserge-sans-paille       ReadlinePatched = true;
1089357b5d0Sserge-sans-paille     }
1099357b5d0Sserge-sans-paille #endif
1109357b5d0Sserge-sans-paille 
11174587a0eSVadim Chugunov     // Register _lldb as a built-in module.
11205495c5dSJonas Devlieghere     PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
11374587a0eSVadim Chugunov 
114079fe48aSZachary Turner // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
115079fe48aSZachary Turner // calling `Py_Initialize` and `PyEval_InitThreads`.  < 3.2 requires that you
116079fe48aSZachary Turner // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
117079fe48aSZachary Turner #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
118079fe48aSZachary Turner     Py_InitializeEx(0);
119079fe48aSZachary Turner     InitializeThreadsPrivate();
120079fe48aSZachary Turner #else
121079fe48aSZachary Turner     InitializeThreadsPrivate();
122079fe48aSZachary Turner     Py_InitializeEx(0);
123079fe48aSZachary Turner #endif
124079fe48aSZachary Turner   }
125079fe48aSZachary Turner 
126b9c1b51eSKate Stone   ~InitializePythonRAII() {
127b9c1b51eSKate Stone     if (m_was_already_initialized) {
1283b7e1981SPavel Labath       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
1293b7e1981SPavel Labath       LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
1301b6700efSTatyana Krasnukha                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
131079fe48aSZachary Turner       PyGILState_Release(m_gil_state);
132b9c1b51eSKate Stone     } else {
133079fe48aSZachary Turner       // We initialized the threads in this function, just unlock the GIL.
134079fe48aSZachary Turner       PyEval_SaveThread();
135079fe48aSZachary Turner     }
136079fe48aSZachary Turner   }
137079fe48aSZachary Turner 
138079fe48aSZachary Turner private:
139b9c1b51eSKate Stone   void InitializePythonHome() {
1403ec3f62fSHaibo Huang #if LLDB_EMBED_PYTHON_HOME
1413ec3f62fSHaibo Huang #if PY_MAJOR_VERSION >= 3
1423ec3f62fSHaibo Huang     typedef wchar_t* str_type;
1433ec3f62fSHaibo Huang #else
1443ec3f62fSHaibo Huang     typedef char* str_type;
1453ec3f62fSHaibo Huang #endif
1463ec3f62fSHaibo Huang     static str_type g_python_home = []() -> str_type {
1473ec3f62fSHaibo Huang       const char *lldb_python_home = LLDB_PYTHON_HOME;
1483ec3f62fSHaibo Huang       const char *absolute_python_home = nullptr;
1493ec3f62fSHaibo Huang       llvm::SmallString<64> path;
1503ec3f62fSHaibo Huang       if (llvm::sys::path::is_absolute(lldb_python_home)) {
1513ec3f62fSHaibo Huang         absolute_python_home = lldb_python_home;
1523ec3f62fSHaibo Huang       } else {
1533ec3f62fSHaibo Huang         FileSpec spec = HostInfo::GetShlibDir();
1543ec3f62fSHaibo Huang         if (!spec)
1553ec3f62fSHaibo Huang           return nullptr;
1563ec3f62fSHaibo Huang         spec.GetPath(path);
1573ec3f62fSHaibo Huang         llvm::sys::path::append(path, lldb_python_home);
1583ec3f62fSHaibo Huang         absolute_python_home = path.c_str();
1593ec3f62fSHaibo Huang       }
16022c8efcdSZachary Turner #if PY_MAJOR_VERSION >= 3
16122c8efcdSZachary Turner       size_t size = 0;
1623ec3f62fSHaibo Huang       return Py_DecodeLocale(absolute_python_home, &size);
16322c8efcdSZachary Turner #else
1643ec3f62fSHaibo Huang       return strdup(absolute_python_home);
16522c8efcdSZachary Turner #endif
1663ec3f62fSHaibo Huang     }();
1673ec3f62fSHaibo Huang     if (g_python_home != nullptr) {
168079fe48aSZachary Turner       Py_SetPythonHome(g_python_home);
1693ec3f62fSHaibo Huang     }
170386f00dbSDavide Italiano #else
171386f00dbSDavide Italiano #if defined(__APPLE__) && PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION == 7
17263dd5d25SJonas Devlieghere     // For Darwin, the only Python version supported is the one shipped in the
17363dd5d25SJonas Devlieghere     // OS OS and linked with lldb. Other installation of Python may have higher
1744f9cb260SDavide Italiano     // priorities in the path, overriding PYTHONHOME and causing
1754f9cb260SDavide Italiano     // problems/incompatibilities. In order to avoid confusion, always hardcode
1764f9cb260SDavide Italiano     // the PythonHome to be right, as it's not going to change.
17763dd5d25SJonas Devlieghere     static char path[] =
17863dd5d25SJonas Devlieghere         "/System/Library/Frameworks/Python.framework/Versions/2.7";
1794f9cb260SDavide Italiano     Py_SetPythonHome(path);
180386f00dbSDavide Italiano #endif
181386f00dbSDavide Italiano #endif
18222c8efcdSZachary Turner   }
18322c8efcdSZachary Turner 
184b9c1b51eSKate Stone   void InitializeThreadsPrivate() {
1851b6700efSTatyana Krasnukha // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself,
1861b6700efSTatyana Krasnukha // so there is no way to determine whether the embedded interpreter
1871b6700efSTatyana Krasnukha // was already initialized by some external code. `PyEval_ThreadsInitialized`
1881b6700efSTatyana Krasnukha // would always return `true` and `PyGILState_Ensure/Release` flow would be
1891b6700efSTatyana Krasnukha // executed instead of unlocking GIL with `PyEval_SaveThread`. When
1901b6700efSTatyana Krasnukha // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock.
1911b6700efSTatyana Krasnukha #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3)
1921b6700efSTatyana Krasnukha     // The only case we should go further and acquire the GIL: it is unlocked.
1931b6700efSTatyana Krasnukha     if (PyGILState_Check())
1941b6700efSTatyana Krasnukha       return;
1951b6700efSTatyana Krasnukha #endif
1961b6700efSTatyana Krasnukha 
197b9c1b51eSKate Stone     if (PyEval_ThreadsInitialized()) {
1983b7e1981SPavel Labath       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
199079fe48aSZachary Turner 
200079fe48aSZachary Turner       m_was_already_initialized = true;
201079fe48aSZachary Turner       m_gil_state = PyGILState_Ensure();
2023b7e1981SPavel Labath       LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n",
203079fe48aSZachary Turner                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
204079fe48aSZachary Turner       return;
205079fe48aSZachary Turner     }
206079fe48aSZachary Turner 
207079fe48aSZachary Turner     // InitThreads acquires the GIL if it hasn't been called before.
208079fe48aSZachary Turner     PyEval_InitThreads();
209079fe48aSZachary Turner   }
210079fe48aSZachary Turner 
2119494c510SJonas Devlieghere   PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
2129494c510SJonas Devlieghere   bool m_was_already_initialized = false;
213079fe48aSZachary Turner };
21463dd5d25SJonas Devlieghere } // namespace
2152c1f46dcSZachary Turner 
2162df331b0SPavel Labath void ScriptInterpreterPython::ComputePythonDirForApple(
2172df331b0SPavel Labath     llvm::SmallVectorImpl<char> &path) {
2182df331b0SPavel Labath   auto style = llvm::sys::path::Style::posix;
2192df331b0SPavel Labath 
2202df331b0SPavel Labath   llvm::StringRef path_ref(path.begin(), path.size());
2212df331b0SPavel Labath   auto rbegin = llvm::sys::path::rbegin(path_ref, style);
2222df331b0SPavel Labath   auto rend = llvm::sys::path::rend(path_ref);
2232df331b0SPavel Labath   auto framework = std::find(rbegin, rend, "LLDB.framework");
2242df331b0SPavel Labath   if (framework == rend) {
22561f471a7SHaibo Huang     ComputePythonDir(path);
2262df331b0SPavel Labath     return;
2272df331b0SPavel Labath   }
2282df331b0SPavel Labath   path.resize(framework - rend);
2292df331b0SPavel Labath   llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
2302df331b0SPavel Labath }
2312df331b0SPavel Labath 
23261f471a7SHaibo Huang void ScriptInterpreterPython::ComputePythonDir(
2332df331b0SPavel Labath     llvm::SmallVectorImpl<char> &path) {
2342df331b0SPavel Labath   // Build the path by backing out of the lib dir, then building with whatever
2352df331b0SPavel Labath   // the real python interpreter uses.  (e.g. lib for most, lib64 on RHEL
23661f471a7SHaibo Huang   // x86_64, or bin on Windows).
23761f471a7SHaibo Huang   llvm::sys::path::remove_filename(path);
23861f471a7SHaibo Huang   llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
2390016b450SHaibo Huang 
2400016b450SHaibo Huang #if defined(_WIN32)
2410016b450SHaibo Huang   // This will be injected directly through FileSpec.GetDirectory().SetString(),
2420016b450SHaibo Huang   // so we need to normalize manually.
2430016b450SHaibo Huang   std::replace(path.begin(), path.end(), '\\', '/');
2440016b450SHaibo Huang #endif
2452df331b0SPavel Labath }
2462df331b0SPavel Labath 
2472df331b0SPavel Labath FileSpec ScriptInterpreterPython::GetPythonDir() {
2482df331b0SPavel Labath   static FileSpec g_spec = []() {
2492df331b0SPavel Labath     FileSpec spec = HostInfo::GetShlibDir();
2502df331b0SPavel Labath     if (!spec)
2512df331b0SPavel Labath       return FileSpec();
2522df331b0SPavel Labath     llvm::SmallString<64> path;
2532df331b0SPavel Labath     spec.GetPath(path);
2542df331b0SPavel Labath 
2552df331b0SPavel Labath #if defined(__APPLE__)
2562df331b0SPavel Labath     ComputePythonDirForApple(path);
2572df331b0SPavel Labath #else
25861f471a7SHaibo Huang     ComputePythonDir(path);
2592df331b0SPavel Labath #endif
2602df331b0SPavel Labath     spec.GetDirectory().SetString(path);
2612df331b0SPavel Labath     return spec;
2622df331b0SPavel Labath   }();
2632df331b0SPavel Labath   return g_spec;
2642df331b0SPavel Labath }
2652df331b0SPavel Labath 
2664c2cf3a3SLawrence D'Anna static const char GetInterpreterInfoScript[] = R"(
2674c2cf3a3SLawrence D'Anna import os
2684c2cf3a3SLawrence D'Anna import sys
2694c2cf3a3SLawrence D'Anna 
2704c2cf3a3SLawrence D'Anna def main(lldb_python_dir, python_exe_relative_path):
2714c2cf3a3SLawrence D'Anna   info = {
2724c2cf3a3SLawrence D'Anna     "lldb-pythonpath": lldb_python_dir,
2734c2cf3a3SLawrence D'Anna     "language": "python",
2744c2cf3a3SLawrence D'Anna     "prefix": sys.prefix,
2754c2cf3a3SLawrence D'Anna     "executable": os.path.join(sys.prefix, python_exe_relative_path)
2764c2cf3a3SLawrence D'Anna   }
2774c2cf3a3SLawrence D'Anna   return info
2784c2cf3a3SLawrence D'Anna )";
2794c2cf3a3SLawrence D'Anna 
2804c2cf3a3SLawrence D'Anna static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH;
2814c2cf3a3SLawrence D'Anna 
282bbef51ebSLawrence D'Anna StructuredData::DictionarySP ScriptInterpreterPython::GetInterpreterInfo() {
283bbef51ebSLawrence D'Anna   GIL gil;
284bbef51ebSLawrence D'Anna   FileSpec python_dir_spec = GetPythonDir();
285bbef51ebSLawrence D'Anna   if (!python_dir_spec)
286bbef51ebSLawrence D'Anna     return nullptr;
2874c2cf3a3SLawrence D'Anna   PythonScript get_info(GetInterpreterInfoScript);
2884c2cf3a3SLawrence D'Anna   auto info_json = unwrapIgnoringErrors(
2894c2cf3a3SLawrence D'Anna       As<PythonDictionary>(get_info(PythonString(python_dir_spec.GetPath()),
2904c2cf3a3SLawrence D'Anna                                     PythonString(python_exe_relative_path))));
291bbef51ebSLawrence D'Anna   if (!info_json)
292bbef51ebSLawrence D'Anna     return nullptr;
293bbef51ebSLawrence D'Anna   return info_json.CreateStructuredDictionary();
294bbef51ebSLawrence D'Anna }
295bbef51ebSLawrence D'Anna 
296004a264fSPavel Labath void ScriptInterpreterPython::SharedLibraryDirectoryHelper(
297004a264fSPavel Labath     FileSpec &this_file) {
298004a264fSPavel Labath   // When we're loaded from python, this_file will point to the file inside the
299004a264fSPavel Labath   // python package directory. Replace it with the one in the lib directory.
300004a264fSPavel Labath #ifdef _WIN32
301004a264fSPavel Labath   // On windows, we need to manually back out of the python tree, and go into
302004a264fSPavel Labath   // the bin directory. This is pretty much the inverse of what ComputePythonDir
303004a264fSPavel Labath   // does.
304004a264fSPavel Labath   if (this_file.GetFileNameExtension() == ConstString(".pyd")) {
305004a264fSPavel Labath     this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd
306004a264fSPavel Labath     this_file.RemoveLastPathComponent(); // lldb
3072e826088SPavel Labath     llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
3082e826088SPavel Labath     for (auto it = llvm::sys::path::begin(libdir),
3092e826088SPavel Labath               end = llvm::sys::path::end(libdir);
310004a264fSPavel Labath          it != end; ++it)
311004a264fSPavel Labath       this_file.RemoveLastPathComponent();
312004a264fSPavel Labath     this_file.AppendPathComponent("bin");
313004a264fSPavel Labath     this_file.AppendPathComponent("liblldb.dll");
314004a264fSPavel Labath   }
315004a264fSPavel Labath #else
316004a264fSPavel Labath   // The python file is a symlink, so we can find the real library by resolving
317004a264fSPavel Labath   // it. We can do this unconditionally.
318004a264fSPavel Labath   FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
319004a264fSPavel Labath #endif
320004a264fSPavel Labath }
321004a264fSPavel Labath 
3225f4980f0SPavel Labath llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() {
32363dd5d25SJonas Devlieghere   return "Embedded Python interpreter";
32463dd5d25SJonas Devlieghere }
32563dd5d25SJonas Devlieghere 
32663dd5d25SJonas Devlieghere void ScriptInterpreterPython::Initialize() {
32763dd5d25SJonas Devlieghere   static llvm::once_flag g_once_flag;
32863dd5d25SJonas Devlieghere 
32963dd5d25SJonas Devlieghere   llvm::call_once(g_once_flag, []() {
33063dd5d25SJonas Devlieghere     PluginManager::RegisterPlugin(GetPluginNameStatic(),
33163dd5d25SJonas Devlieghere                                   GetPluginDescriptionStatic(),
33263dd5d25SJonas Devlieghere                                   lldb::eScriptLanguagePython,
33363dd5d25SJonas Devlieghere                                   ScriptInterpreterPythonImpl::CreateInstance);
33463dd5d25SJonas Devlieghere   });
33563dd5d25SJonas Devlieghere }
33663dd5d25SJonas Devlieghere 
33763dd5d25SJonas Devlieghere void ScriptInterpreterPython::Terminate() {}
33863dd5d25SJonas Devlieghere 
33963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::Locker(
34063dd5d25SJonas Devlieghere     ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
341b07823f3SLawrence D'Anna     uint16_t on_leave, FileSP in, FileSP out, FileSP err)
34263dd5d25SJonas Devlieghere     : ScriptInterpreterLocker(),
34363dd5d25SJonas Devlieghere       m_teardown_session((on_leave & TearDownSession) == TearDownSession),
34463dd5d25SJonas Devlieghere       m_python_interpreter(py_interpreter) {
3455861234eSJonas Devlieghere   repro::Recorder::PrivateThread();
34663dd5d25SJonas Devlieghere   DoAcquireLock();
34763dd5d25SJonas Devlieghere   if ((on_entry & InitSession) == InitSession) {
34863dd5d25SJonas Devlieghere     if (!DoInitSession(on_entry, in, out, err)) {
34963dd5d25SJonas Devlieghere       // Don't teardown the session if we didn't init it.
35063dd5d25SJonas Devlieghere       m_teardown_session = false;
35163dd5d25SJonas Devlieghere     }
35263dd5d25SJonas Devlieghere   }
35363dd5d25SJonas Devlieghere }
35463dd5d25SJonas Devlieghere 
35563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
35663dd5d25SJonas Devlieghere   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
35763dd5d25SJonas Devlieghere   m_GILState = PyGILState_Ensure();
35863dd5d25SJonas Devlieghere   LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked",
35963dd5d25SJonas Devlieghere             m_GILState == PyGILState_UNLOCKED ? "un" : "");
36063dd5d25SJonas Devlieghere 
36163dd5d25SJonas Devlieghere   // we need to save the thread state when we first start the command because
36263dd5d25SJonas Devlieghere   // we might decide to interrupt it while some action is taking place outside
36363dd5d25SJonas Devlieghere   // of Python (e.g. printing to screen, waiting for the network, ...) in that
36463dd5d25SJonas Devlieghere   // case, _PyThreadState_Current will be NULL - and we would be unable to set
36563dd5d25SJonas Devlieghere   // the asynchronous exception - not a desirable situation
36663dd5d25SJonas Devlieghere   m_python_interpreter->SetThreadState(PyThreadState_Get());
36763dd5d25SJonas Devlieghere   m_python_interpreter->IncrementLockCount();
36863dd5d25SJonas Devlieghere   return true;
36963dd5d25SJonas Devlieghere }
37063dd5d25SJonas Devlieghere 
37163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
372b07823f3SLawrence D'Anna                                                         FileSP in, FileSP out,
373b07823f3SLawrence D'Anna                                                         FileSP err) {
37463dd5d25SJonas Devlieghere   if (!m_python_interpreter)
37563dd5d25SJonas Devlieghere     return false;
37663dd5d25SJonas Devlieghere   return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
37763dd5d25SJonas Devlieghere }
37863dd5d25SJonas Devlieghere 
37963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
38063dd5d25SJonas Devlieghere   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
38163dd5d25SJonas Devlieghere   LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
38263dd5d25SJonas Devlieghere             m_GILState == PyGILState_UNLOCKED ? "un" : "");
38363dd5d25SJonas Devlieghere   PyGILState_Release(m_GILState);
38463dd5d25SJonas Devlieghere   m_python_interpreter->DecrementLockCount();
38563dd5d25SJonas Devlieghere   return true;
38663dd5d25SJonas Devlieghere }
38763dd5d25SJonas Devlieghere 
38863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
38963dd5d25SJonas Devlieghere   if (!m_python_interpreter)
39063dd5d25SJonas Devlieghere     return false;
39163dd5d25SJonas Devlieghere   m_python_interpreter->LeaveSession();
39263dd5d25SJonas Devlieghere   return true;
39363dd5d25SJonas Devlieghere }
39463dd5d25SJonas Devlieghere 
39563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::~Locker() {
39663dd5d25SJonas Devlieghere   if (m_teardown_session)
39763dd5d25SJonas Devlieghere     DoTearDownSession();
39863dd5d25SJonas Devlieghere   DoFreeLock();
39963dd5d25SJonas Devlieghere }
40063dd5d25SJonas Devlieghere 
4018d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger)
4028d1fb843SJonas Devlieghere     : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
40363dd5d25SJonas Devlieghere       m_saved_stderr(), m_main_module(),
40463dd5d25SJonas Devlieghere       m_session_dict(PyInitialValue::Invalid),
40563dd5d25SJonas Devlieghere       m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(),
40663dd5d25SJonas Devlieghere       m_run_one_line_str_global(),
4078d1fb843SJonas Devlieghere       m_dictionary_name(m_debugger.GetInstanceName().AsCString()),
408ea1752a7SJonas Devlieghere       m_active_io_handler(eIOHandlerNone), m_session_is_active(false),
40964ec505dSJonas Devlieghere       m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
410ea1752a7SJonas Devlieghere       m_command_thread_state(nullptr) {
41163dd5d25SJonas Devlieghere   InitializePrivate();
41263dd5d25SJonas Devlieghere 
4131f6a57c1SMed Ismail Bennani   m_scripted_process_interface_up =
4141f6a57c1SMed Ismail Bennani       std::make_unique<ScriptedProcessPythonInterface>(*this);
4151f6a57c1SMed Ismail Bennani 
41663dd5d25SJonas Devlieghere   m_dictionary_name.append("_dict");
41763dd5d25SJonas Devlieghere   StreamString run_string;
41863dd5d25SJonas Devlieghere   run_string.Printf("%s = dict()", m_dictionary_name.c_str());
41963dd5d25SJonas Devlieghere 
42063dd5d25SJonas Devlieghere   Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock);
42163dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
42263dd5d25SJonas Devlieghere 
42363dd5d25SJonas Devlieghere   run_string.Clear();
42463dd5d25SJonas Devlieghere   run_string.Printf(
42563dd5d25SJonas Devlieghere       "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
42663dd5d25SJonas Devlieghere       m_dictionary_name.c_str());
42763dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
42863dd5d25SJonas Devlieghere 
42963dd5d25SJonas Devlieghere   // Reloading modules requires a different syntax in Python 2 and Python 3.
43063dd5d25SJonas Devlieghere   // This provides a consistent syntax no matter what version of Python.
43163dd5d25SJonas Devlieghere   run_string.Clear();
43263dd5d25SJonas Devlieghere   run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')",
43363dd5d25SJonas Devlieghere                     m_dictionary_name.c_str());
43463dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
43563dd5d25SJonas Devlieghere 
43663dd5d25SJonas Devlieghere   // WARNING: temporary code that loads Cocoa formatters - this should be done
43763dd5d25SJonas Devlieghere   // on a per-platform basis rather than loading the whole set and letting the
43863dd5d25SJonas Devlieghere   // individual formatter classes exploit APIs to check whether they can/cannot
43963dd5d25SJonas Devlieghere   // do their task
44063dd5d25SJonas Devlieghere   run_string.Clear();
44163dd5d25SJonas Devlieghere   run_string.Printf(
44263dd5d25SJonas Devlieghere       "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')",
44363dd5d25SJonas Devlieghere       m_dictionary_name.c_str());
44463dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
44563dd5d25SJonas Devlieghere   run_string.Clear();
44663dd5d25SJonas Devlieghere 
44763dd5d25SJonas Devlieghere   run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
44863dd5d25SJonas Devlieghere                     "lldb.embedded_interpreter import run_python_interpreter; "
44963dd5d25SJonas Devlieghere                     "from lldb.embedded_interpreter import run_one_line')",
45063dd5d25SJonas Devlieghere                     m_dictionary_name.c_str());
45163dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
45263dd5d25SJonas Devlieghere   run_string.Clear();
45363dd5d25SJonas Devlieghere 
45463dd5d25SJonas Devlieghere   run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
45563dd5d25SJonas Devlieghere                     "; pydoc.pager = pydoc.plainpager')",
4568d1fb843SJonas Devlieghere                     m_dictionary_name.c_str(), m_debugger.GetID());
45763dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
45863dd5d25SJonas Devlieghere }
45963dd5d25SJonas Devlieghere 
46063dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
46163dd5d25SJonas Devlieghere   // the session dictionary may hold objects with complex state which means
46263dd5d25SJonas Devlieghere   // that they may need to be torn down with some level of smarts and that, in
46363dd5d25SJonas Devlieghere   // turn, requires a valid thread state force Python to procure itself such a
46463dd5d25SJonas Devlieghere   // thread state, nuke the session dictionary and then release it for others
46563dd5d25SJonas Devlieghere   // to use and proceed with the rest of the shutdown
46663dd5d25SJonas Devlieghere   auto gil_state = PyGILState_Ensure();
46763dd5d25SJonas Devlieghere   m_session_dict.Reset();
46863dd5d25SJonas Devlieghere   PyGILState_Release(gil_state);
46963dd5d25SJonas Devlieghere }
47063dd5d25SJonas Devlieghere 
47163dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler,
47263dd5d25SJonas Devlieghere                                                      bool interactive) {
4732c1f46dcSZachary Turner   const char *instructions = nullptr;
4742c1f46dcSZachary Turner 
475b9c1b51eSKate Stone   switch (m_active_io_handler) {
4762c1f46dcSZachary Turner   case eIOHandlerNone:
4772c1f46dcSZachary Turner     break;
4782c1f46dcSZachary Turner   case eIOHandlerBreakpoint:
4792c1f46dcSZachary Turner     instructions = R"(Enter your Python command(s). Type 'DONE' to end.
4802c1f46dcSZachary Turner def function (frame, bp_loc, internal_dict):
4812c1f46dcSZachary Turner     """frame: the lldb.SBFrame for the location at which you stopped
4822c1f46dcSZachary Turner        bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
4832c1f46dcSZachary Turner        internal_dict: an LLDB support object not to be used"""
4842c1f46dcSZachary Turner )";
4852c1f46dcSZachary Turner     break;
4862c1f46dcSZachary Turner   case eIOHandlerWatchpoint:
4872c1f46dcSZachary Turner     instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
4882c1f46dcSZachary Turner     break;
4892c1f46dcSZachary Turner   }
4902c1f46dcSZachary Turner 
491b9c1b51eSKate Stone   if (instructions) {
4927ca15ba7SLawrence D'Anna     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
4930affb582SDave Lee     if (output_sp && interactive) {
4942c1f46dcSZachary Turner       output_sp->PutCString(instructions);
4952c1f46dcSZachary Turner       output_sp->Flush();
4962c1f46dcSZachary Turner     }
4972c1f46dcSZachary Turner   }
4982c1f46dcSZachary Turner }
4992c1f46dcSZachary Turner 
50063dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler,
501b9c1b51eSKate Stone                                                          std::string &data) {
5022c1f46dcSZachary Turner   io_handler.SetIsDone(true);
5038d1fb843SJonas Devlieghere   bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
5042c1f46dcSZachary Turner 
505b9c1b51eSKate Stone   switch (m_active_io_handler) {
5062c1f46dcSZachary Turner   case eIOHandlerNone:
5072c1f46dcSZachary Turner     break;
508b9c1b51eSKate Stone   case eIOHandlerBreakpoint: {
509cfb96d84SJim Ingham     std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
510cfb96d84SJim Ingham         (std::vector<std::reference_wrapper<BreakpointOptions>> *)
511cfb96d84SJim Ingham             io_handler.GetUserData();
512cfb96d84SJim Ingham     for (BreakpointOptions &bp_options : *bp_options_vec) {
5132c1f46dcSZachary Turner 
514a8f3ae7cSJonas Devlieghere       auto data_up = std::make_unique<CommandDataPython>();
515d5b44036SJonas Devlieghere       if (!data_up)
5164e4fbe82SZachary Turner         break;
517d5b44036SJonas Devlieghere       data_up->user_source.SplitIntoLines(data);
5182c1f46dcSZachary Turner 
519738af7a6SJim Ingham       StructuredData::ObjectSP empty_args_sp;
520d5b44036SJonas Devlieghere       if (GenerateBreakpointCommandCallbackData(data_up->user_source,
521738af7a6SJim Ingham                                                 data_up->script_source,
522738af7a6SJim Ingham                                                 false)
523b9c1b51eSKate Stone               .Success()) {
5244e4fbe82SZachary Turner         auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
525d5b44036SJonas Devlieghere             std::move(data_up));
526cfb96d84SJim Ingham         bp_options.SetCallback(
52763dd5d25SJonas Devlieghere             ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
528b9c1b51eSKate Stone       } else if (!batch_mode) {
5297ca15ba7SLawrence D'Anna         StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
530b9c1b51eSKate Stone         if (error_sp) {
5312c1f46dcSZachary Turner           error_sp->Printf("Warning: No command attached to breakpoint.\n");
5322c1f46dcSZachary Turner           error_sp->Flush();
5332c1f46dcSZachary Turner         }
5342c1f46dcSZachary Turner       }
5352c1f46dcSZachary Turner     }
5362c1f46dcSZachary Turner     m_active_io_handler = eIOHandlerNone;
537b9c1b51eSKate Stone   } break;
538b9c1b51eSKate Stone   case eIOHandlerWatchpoint: {
539b9c1b51eSKate Stone     WatchpointOptions *wp_options =
540b9c1b51eSKate Stone         (WatchpointOptions *)io_handler.GetUserData();
541a8f3ae7cSJonas Devlieghere     auto data_up = std::make_unique<WatchpointOptions::CommandData>();
542d5b44036SJonas Devlieghere     data_up->user_source.SplitIntoLines(data);
5432c1f46dcSZachary Turner 
544d5b44036SJonas Devlieghere     if (GenerateWatchpointCommandCallbackData(data_up->user_source,
545d5b44036SJonas Devlieghere                                               data_up->script_source)) {
5464e4fbe82SZachary Turner       auto baton_sp =
547d5b44036SJonas Devlieghere           std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
548b9c1b51eSKate Stone       wp_options->SetCallback(
54963dd5d25SJonas Devlieghere           ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
550b9c1b51eSKate Stone     } else if (!batch_mode) {
5517ca15ba7SLawrence D'Anna       StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
552b9c1b51eSKate Stone       if (error_sp) {
5532c1f46dcSZachary Turner         error_sp->Printf("Warning: No command attached to breakpoint.\n");
5542c1f46dcSZachary Turner         error_sp->Flush();
5552c1f46dcSZachary Turner       }
5562c1f46dcSZachary Turner     }
5572c1f46dcSZachary Turner     m_active_io_handler = eIOHandlerNone;
558b9c1b51eSKate Stone   } break;
5592c1f46dcSZachary Turner   }
5602c1f46dcSZachary Turner }
5612c1f46dcSZachary Turner 
56263dd5d25SJonas Devlieghere lldb::ScriptInterpreterSP
5638d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) {
5648d1fb843SJonas Devlieghere   return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
56563dd5d25SJonas Devlieghere }
5662c1f46dcSZachary Turner 
56763dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::LeaveSession() {
5682c1f46dcSZachary Turner   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
5692c1f46dcSZachary Turner   if (log)
57063dd5d25SJonas Devlieghere     log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
5712c1f46dcSZachary Turner 
57220b52c33SJonas Devlieghere   // Unset the LLDB global variables.
57320b52c33SJonas Devlieghere   PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
57420b52c33SJonas Devlieghere                      "= None; lldb.thread = None; lldb.frame = None");
57520b52c33SJonas Devlieghere 
57605097246SAdrian Prantl   // checking that we have a valid thread state - since we use our own
57705097246SAdrian Prantl   // threading and locking in some (rare) cases during cleanup Python may end
57805097246SAdrian Prantl   // up believing we have no thread state and PyImport_AddModule will crash if
57905097246SAdrian Prantl   // that is the case - since that seems to only happen when destroying the
58005097246SAdrian Prantl   // SBDebugger, we can make do without clearing up stdout and stderr
5812c1f46dcSZachary Turner 
5822c1f46dcSZachary Turner   // rdar://problem/11292882
583b9c1b51eSKate Stone   // When the current thread state is NULL, PyThreadState_Get() issues a fatal
584b9c1b51eSKate Stone   // error.
585b9c1b51eSKate Stone   if (PyThreadState_GetDict()) {
5862c1f46dcSZachary Turner     PythonDictionary &sys_module_dict = GetSysModuleDictionary();
587b9c1b51eSKate Stone     if (sys_module_dict.IsValid()) {
588b9c1b51eSKate Stone       if (m_saved_stdin.IsValid()) {
589f8b22f8fSZachary Turner         sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
5902c1f46dcSZachary Turner         m_saved_stdin.Reset();
5912c1f46dcSZachary Turner       }
592b9c1b51eSKate Stone       if (m_saved_stdout.IsValid()) {
593f8b22f8fSZachary Turner         sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
5942c1f46dcSZachary Turner         m_saved_stdout.Reset();
5952c1f46dcSZachary Turner       }
596b9c1b51eSKate Stone       if (m_saved_stderr.IsValid()) {
597f8b22f8fSZachary Turner         sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
5982c1f46dcSZachary Turner         m_saved_stderr.Reset();
5992c1f46dcSZachary Turner       }
6002c1f46dcSZachary Turner     }
6012c1f46dcSZachary Turner   }
6022c1f46dcSZachary Turner 
6032c1f46dcSZachary Turner   m_session_is_active = false;
6042c1f46dcSZachary Turner }
6052c1f46dcSZachary Turner 
606b07823f3SLawrence D'Anna bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp,
607b07823f3SLawrence D'Anna                                                const char *py_name,
608b07823f3SLawrence D'Anna                                                PythonObject &save_file,
609b9c1b51eSKate Stone                                                const char *mode) {
610b07823f3SLawrence D'Anna   if (!file_sp || !*file_sp) {
611b07823f3SLawrence D'Anna     save_file.Reset();
612b07823f3SLawrence D'Anna     return false;
613b07823f3SLawrence D'Anna   }
614b07823f3SLawrence D'Anna   File &file = *file_sp;
615b07823f3SLawrence D'Anna 
616a31baf08SGreg Clayton   // Flush the file before giving it to python to avoid interleaved output.
617a31baf08SGreg Clayton   file.Flush();
618a31baf08SGreg Clayton 
619a31baf08SGreg Clayton   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
620a31baf08SGreg Clayton 
6210f783599SLawrence D'Anna   auto new_file = PythonFile::FromFile(file, mode);
6220f783599SLawrence D'Anna   if (!new_file) {
6230f783599SLawrence D'Anna     llvm::consumeError(new_file.takeError());
6240f783599SLawrence D'Anna     return false;
6250f783599SLawrence D'Anna   }
6260f783599SLawrence D'Anna 
627b07823f3SLawrence D'Anna   save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
628a31baf08SGreg Clayton 
6290f783599SLawrence D'Anna   sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
630a31baf08SGreg Clayton   return true;
631a31baf08SGreg Clayton }
632a31baf08SGreg Clayton 
63363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
634b07823f3SLawrence D'Anna                                                FileSP in_sp, FileSP out_sp,
635b07823f3SLawrence D'Anna                                                FileSP err_sp) {
636b9c1b51eSKate Stone   // If we have already entered the session, without having officially 'left'
63705097246SAdrian Prantl   // it, then there is no need to 'enter' it again.
6382c1f46dcSZachary Turner   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
639b9c1b51eSKate Stone   if (m_session_is_active) {
64063e5fb76SJonas Devlieghere     LLDB_LOGF(
64163e5fb76SJonas Devlieghere         log,
64263dd5d25SJonas Devlieghere         "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
643b9c1b51eSKate Stone         ") session is already active, returning without doing anything",
644b9c1b51eSKate Stone         on_entry_flags);
6452c1f46dcSZachary Turner     return false;
6462c1f46dcSZachary Turner   }
6472c1f46dcSZachary Turner 
64863e5fb76SJonas Devlieghere   LLDB_LOGF(
64963e5fb76SJonas Devlieghere       log,
65063e5fb76SJonas Devlieghere       "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
651b9c1b51eSKate Stone       on_entry_flags);
6522c1f46dcSZachary Turner 
6532c1f46dcSZachary Turner   m_session_is_active = true;
6542c1f46dcSZachary Turner 
6552c1f46dcSZachary Turner   StreamString run_string;
6562c1f46dcSZachary Turner 
657b9c1b51eSKate Stone   if (on_entry_flags & Locker::InitGlobals) {
658b9c1b51eSKate Stone     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
6598d1fb843SJonas Devlieghere                       m_dictionary_name.c_str(), m_debugger.GetID());
660b9c1b51eSKate Stone     run_string.Printf(
661b9c1b51eSKate Stone         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
6628d1fb843SJonas Devlieghere         m_debugger.GetID());
6632c1f46dcSZachary Turner     run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
6642c1f46dcSZachary Turner     run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
6652c1f46dcSZachary Turner     run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
6662c1f46dcSZachary Turner     run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
6672c1f46dcSZachary Turner     run_string.PutCString("')");
668b9c1b51eSKate Stone   } else {
66905097246SAdrian Prantl     // If we aren't initing the globals, we should still always set the
67005097246SAdrian Prantl     // debugger (since that is always unique.)
671b9c1b51eSKate Stone     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
6728d1fb843SJonas Devlieghere                       m_dictionary_name.c_str(), m_debugger.GetID());
673b9c1b51eSKate Stone     run_string.Printf(
674b9c1b51eSKate Stone         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
6758d1fb843SJonas Devlieghere         m_debugger.GetID());
6762c1f46dcSZachary Turner     run_string.PutCString("')");
6772c1f46dcSZachary Turner   }
6782c1f46dcSZachary Turner 
6792c1f46dcSZachary Turner   PyRun_SimpleString(run_string.GetData());
6802c1f46dcSZachary Turner   run_string.Clear();
6812c1f46dcSZachary Turner 
6822c1f46dcSZachary Turner   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
683b9c1b51eSKate Stone   if (sys_module_dict.IsValid()) {
684b07823f3SLawrence D'Anna     lldb::FileSP top_in_sp;
685b07823f3SLawrence D'Anna     lldb::StreamFileSP top_out_sp, top_err_sp;
686b07823f3SLawrence D'Anna     if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
687b07823f3SLawrence D'Anna       m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
688b07823f3SLawrence D'Anna                                                  top_err_sp);
6892c1f46dcSZachary Turner 
690b9c1b51eSKate Stone     if (on_entry_flags & Locker::NoSTDIN) {
6912c1f46dcSZachary Turner       m_saved_stdin.Reset();
692b9c1b51eSKate Stone     } else {
693b07823f3SLawrence D'Anna       if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
694b07823f3SLawrence D'Anna         if (top_in_sp)
695b07823f3SLawrence D'Anna           SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
6962c1f46dcSZachary Turner       }
697a31baf08SGreg Clayton     }
698a31baf08SGreg Clayton 
699b07823f3SLawrence D'Anna     if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
700b07823f3SLawrence D'Anna       if (top_out_sp)
701b07823f3SLawrence D'Anna         SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w");
702a31baf08SGreg Clayton     }
703a31baf08SGreg Clayton 
704b07823f3SLawrence D'Anna     if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
705b07823f3SLawrence D'Anna       if (top_err_sp)
706b07823f3SLawrence D'Anna         SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w");
707a31baf08SGreg Clayton     }
7082c1f46dcSZachary Turner   }
7092c1f46dcSZachary Turner 
7102c1f46dcSZachary Turner   if (PyErr_Occurred())
7112c1f46dcSZachary Turner     PyErr_Clear();
7122c1f46dcSZachary Turner 
7132c1f46dcSZachary Turner   return true;
7142c1f46dcSZachary Turner }
7152c1f46dcSZachary Turner 
71604edd189SLawrence D'Anna PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
717f8b22f8fSZachary Turner   if (!m_main_module.IsValid())
71804edd189SLawrence D'Anna     m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__"));
7192c1f46dcSZachary Turner   return m_main_module;
7202c1f46dcSZachary Turner }
7212c1f46dcSZachary Turner 
72263dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
723f8b22f8fSZachary Turner   if (m_session_dict.IsValid())
724f8b22f8fSZachary Turner     return m_session_dict;
725f8b22f8fSZachary Turner 
7262c1f46dcSZachary Turner   PythonObject &main_module = GetMainModule();
727f8b22f8fSZachary Turner   if (!main_module.IsValid())
728f8b22f8fSZachary Turner     return m_session_dict;
729f8b22f8fSZachary Turner 
730b9c1b51eSKate Stone   PythonDictionary main_dict(PyRefType::Borrowed,
731b9c1b51eSKate Stone                              PyModule_GetDict(main_module.get()));
732f8b22f8fSZachary Turner   if (!main_dict.IsValid())
733f8b22f8fSZachary Turner     return m_session_dict;
734f8b22f8fSZachary Turner 
735722b6189SLawrence D'Anna   m_session_dict = unwrapIgnoringErrors(
736722b6189SLawrence D'Anna       As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
7372c1f46dcSZachary Turner   return m_session_dict;
7382c1f46dcSZachary Turner }
7392c1f46dcSZachary Turner 
74063dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
741f8b22f8fSZachary Turner   if (m_sys_module_dict.IsValid())
742f8b22f8fSZachary Turner     return m_sys_module_dict;
743722b6189SLawrence D'Anna   PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys"));
744722b6189SLawrence D'Anna   m_sys_module_dict = sys_module.GetDictionary();
7452c1f46dcSZachary Turner   return m_sys_module_dict;
7462c1f46dcSZachary Turner }
7472c1f46dcSZachary Turner 
748a69bbe02SLawrence D'Anna llvm::Expected<unsigned>
749a69bbe02SLawrence D'Anna ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
750a69bbe02SLawrence D'Anna     const llvm::StringRef &callable_name) {
751738af7a6SJim Ingham   if (callable_name.empty()) {
752738af7a6SJim Ingham     return llvm::createStringError(
753738af7a6SJim Ingham         llvm::inconvertibleErrorCode(),
754738af7a6SJim Ingham         "called with empty callable name.");
755738af7a6SJim Ingham   }
756738af7a6SJim Ingham   Locker py_lock(this, Locker::AcquireLock |
757738af7a6SJim Ingham                  Locker::InitSession |
758738af7a6SJim Ingham                  Locker::NoSTDIN);
759738af7a6SJim Ingham   auto dict = PythonModule::MainModule()
760738af7a6SJim Ingham       .ResolveName<PythonDictionary>(m_dictionary_name);
761a69bbe02SLawrence D'Anna   auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
762a69bbe02SLawrence D'Anna       callable_name, dict);
763738af7a6SJim Ingham   if (!pfunc.IsAllocated()) {
764738af7a6SJim Ingham     return llvm::createStringError(
765738af7a6SJim Ingham         llvm::inconvertibleErrorCode(),
766738af7a6SJim Ingham         "can't find callable: %s", callable_name.str().c_str());
767738af7a6SJim Ingham   }
768adbf64ccSLawrence D'Anna   llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
769adbf64ccSLawrence D'Anna   if (!arg_info)
770adbf64ccSLawrence D'Anna     return arg_info.takeError();
771adbf64ccSLawrence D'Anna   return arg_info.get().max_positional_args;
772738af7a6SJim Ingham }
773738af7a6SJim Ingham 
774b9c1b51eSKate Stone static std::string GenerateUniqueName(const char *base_name_wanted,
7752c1f46dcSZachary Turner                                       uint32_t &functions_counter,
776b9c1b51eSKate Stone                                       const void *name_token = nullptr) {
7772c1f46dcSZachary Turner   StreamString sstr;
7782c1f46dcSZachary Turner 
7792c1f46dcSZachary Turner   if (!base_name_wanted)
7802c1f46dcSZachary Turner     return std::string();
7812c1f46dcSZachary Turner 
7822c1f46dcSZachary Turner   if (!name_token)
7832c1f46dcSZachary Turner     sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
7842c1f46dcSZachary Turner   else
7852c1f46dcSZachary Turner     sstr.Printf("%s_%p", base_name_wanted, name_token);
7862c1f46dcSZachary Turner 
787adcd0268SBenjamin Kramer   return std::string(sstr.GetString());
7882c1f46dcSZachary Turner }
7892c1f46dcSZachary Turner 
79063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
791f8b22f8fSZachary Turner   if (m_run_one_line_function.IsValid())
792f8b22f8fSZachary Turner     return true;
793f8b22f8fSZachary Turner 
794b9c1b51eSKate Stone   PythonObject module(PyRefType::Borrowed,
795b9c1b51eSKate Stone                       PyImport_AddModule("lldb.embedded_interpreter"));
796f8b22f8fSZachary Turner   if (!module.IsValid())
797f8b22f8fSZachary Turner     return false;
798f8b22f8fSZachary Turner 
799b9c1b51eSKate Stone   PythonDictionary module_dict(PyRefType::Borrowed,
800b9c1b51eSKate Stone                                PyModule_GetDict(module.get()));
801f8b22f8fSZachary Turner   if (!module_dict.IsValid())
802f8b22f8fSZachary Turner     return false;
803f8b22f8fSZachary Turner 
804b9c1b51eSKate Stone   m_run_one_line_function =
805b9c1b51eSKate Stone       module_dict.GetItemForKey(PythonString("run_one_line"));
806b9c1b51eSKate Stone   m_run_one_line_str_global =
807b9c1b51eSKate Stone       module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
808f8b22f8fSZachary Turner   return m_run_one_line_function.IsValid();
8092c1f46dcSZachary Turner }
8102c1f46dcSZachary Turner 
81163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLine(
8124d51a902SRaphael Isemann     llvm::StringRef command, CommandReturnObject *result,
813b9c1b51eSKate Stone     const ExecuteScriptOptions &options) {
814d6c062bcSRaphael Isemann   std::string command_str = command.str();
815d6c062bcSRaphael Isemann 
8162c1f46dcSZachary Turner   if (!m_valid_session)
8172c1f46dcSZachary Turner     return false;
8182c1f46dcSZachary Turner 
8194d51a902SRaphael Isemann   if (!command.empty()) {
820b9c1b51eSKate Stone     // We want to call run_one_line, passing in the dictionary and the command
82105097246SAdrian Prantl     // string.  We cannot do this through PyRun_SimpleString here because the
82205097246SAdrian Prantl     // command string may contain escaped characters, and putting it inside
823b9c1b51eSKate Stone     // another string to pass to PyRun_SimpleString messes up the escaping.  So
82405097246SAdrian Prantl     // we use the following more complicated method to pass the command string
82505097246SAdrian Prantl     // directly down to Python.
826d79273c9SJonas Devlieghere     llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
82784228365SJonas Devlieghere         io_redirect_or_error = ScriptInterpreterIORedirect::Create(
82884228365SJonas Devlieghere             options.GetEnableIO(), m_debugger, result);
829d79273c9SJonas Devlieghere     if (!io_redirect_or_error) {
830d79273c9SJonas Devlieghere       if (result)
831d79273c9SJonas Devlieghere         result->AppendErrorWithFormatv(
832d79273c9SJonas Devlieghere             "failed to redirect I/O: {0}\n",
833d79273c9SJonas Devlieghere             llvm::fmt_consume(io_redirect_or_error.takeError()));
834d79273c9SJonas Devlieghere       else
835d79273c9SJonas Devlieghere         llvm::consumeError(io_redirect_or_error.takeError());
8362fce1137SLawrence D'Anna       return false;
8372fce1137SLawrence D'Anna     }
838d79273c9SJonas Devlieghere 
839d79273c9SJonas Devlieghere     ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
8402c1f46dcSZachary Turner 
84132064024SZachary Turner     bool success = false;
84232064024SZachary Turner     {
84305097246SAdrian Prantl       // WARNING!  It's imperative that this RAII scope be as tight as
84405097246SAdrian Prantl       // possible. In particular, the scope must end *before* we try to join
84505097246SAdrian Prantl       // the read thread.  The reason for this is that a pre-requisite for
84605097246SAdrian Prantl       // joining the read thread is that we close the write handle (to break
84705097246SAdrian Prantl       // the pipe and cause it to wake up and exit).  But acquiring the GIL as
84805097246SAdrian Prantl       // below will redirect Python's stdio to use this same handle.  If we
84905097246SAdrian Prantl       // close the handle while Python is still using it, bad things will
85005097246SAdrian Prantl       // happen.
851b9c1b51eSKate Stone       Locker locker(
852b9c1b51eSKate Stone           this,
85363dd5d25SJonas Devlieghere           Locker::AcquireLock | Locker::InitSession |
85463dd5d25SJonas Devlieghere               (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
8552c1f46dcSZachary Turner               ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
856d79273c9SJonas Devlieghere           Locker::FreeAcquiredLock | Locker::TearDownSession,
857d79273c9SJonas Devlieghere           io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
858d79273c9SJonas Devlieghere           io_redirect.GetErrorFile());
8592c1f46dcSZachary Turner 
8602c1f46dcSZachary Turner       // Find the correct script interpreter dictionary in the main module.
8612c1f46dcSZachary Turner       PythonDictionary &session_dict = GetSessionDictionary();
862b9c1b51eSKate Stone       if (session_dict.IsValid()) {
863b9c1b51eSKate Stone         if (GetEmbeddedInterpreterModuleObjects()) {
864b9c1b51eSKate Stone           if (PyCallable_Check(m_run_one_line_function.get())) {
865b9c1b51eSKate Stone             PythonObject pargs(
866b9c1b51eSKate Stone                 PyRefType::Owned,
867d6c062bcSRaphael Isemann                 Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
868b9c1b51eSKate Stone             if (pargs.IsValid()) {
869b9c1b51eSKate Stone               PythonObject return_value(
870b9c1b51eSKate Stone                   PyRefType::Owned,
871b9c1b51eSKate Stone                   PyObject_CallObject(m_run_one_line_function.get(),
872b9c1b51eSKate Stone                                       pargs.get()));
873f8b22f8fSZachary Turner               if (return_value.IsValid())
8742c1f46dcSZachary Turner                 success = true;
875b9c1b51eSKate Stone               else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
8762c1f46dcSZachary Turner                 PyErr_Print();
8772c1f46dcSZachary Turner                 PyErr_Clear();
8782c1f46dcSZachary Turner               }
8792c1f46dcSZachary Turner             }
8802c1f46dcSZachary Turner           }
8812c1f46dcSZachary Turner         }
8822c1f46dcSZachary Turner       }
8832c1f46dcSZachary Turner 
884d79273c9SJonas Devlieghere       io_redirect.Flush();
8852c1f46dcSZachary Turner     }
8862c1f46dcSZachary Turner 
8872c1f46dcSZachary Turner     if (success)
8882c1f46dcSZachary Turner       return true;
8892c1f46dcSZachary Turner 
8902c1f46dcSZachary Turner     // The one-liner failed.  Append the error message.
8914d51a902SRaphael Isemann     if (result) {
892b9c1b51eSKate Stone       result->AppendErrorWithFormat(
8934d51a902SRaphael Isemann           "python failed attempting to evaluate '%s'\n", command_str.c_str());
8944d51a902SRaphael Isemann     }
8952c1f46dcSZachary Turner     return false;
8962c1f46dcSZachary Turner   }
8972c1f46dcSZachary Turner 
8982c1f46dcSZachary Turner   if (result)
8992c1f46dcSZachary Turner     result->AppendError("empty command passed to python\n");
9002c1f46dcSZachary Turner   return false;
9012c1f46dcSZachary Turner }
9022c1f46dcSZachary Turner 
90363dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
9045c1c8443SJonas Devlieghere   LLDB_SCOPED_TIMER();
9052c1f46dcSZachary Turner 
9068d1fb843SJonas Devlieghere   Debugger &debugger = m_debugger;
9072c1f46dcSZachary Turner 
908b9c1b51eSKate Stone   // At the moment, the only time the debugger does not have an input file
90905097246SAdrian Prantl   // handle is when this is called directly from Python, in which case it is
91005097246SAdrian Prantl   // both dangerous and unnecessary (not to mention confusing) to try to embed
91105097246SAdrian Prantl   // a running interpreter loop inside the already running Python interpreter
91205097246SAdrian Prantl   // loop, so we won't do it.
9132c1f46dcSZachary Turner 
9147ca15ba7SLawrence D'Anna   if (!debugger.GetInputFile().IsValid())
9152c1f46dcSZachary Turner     return;
9162c1f46dcSZachary Turner 
9172c1f46dcSZachary Turner   IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
918b9c1b51eSKate Stone   if (io_handler_sp) {
9197ce2de2cSJonas Devlieghere     debugger.RunIOHandlerAsync(io_handler_sp);
9202c1f46dcSZachary Turner   }
9212c1f46dcSZachary Turner }
9222c1f46dcSZachary Turner 
92363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Interrupt() {
9242c1f46dcSZachary Turner   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
9252c1f46dcSZachary Turner 
926b9c1b51eSKate Stone   if (IsExecutingPython()) {
927b1cf558dSEnrico Granata     PyThreadState *state = PyThreadState_GET();
9282c1f46dcSZachary Turner     if (!state)
9292c1f46dcSZachary Turner       state = GetThreadState();
930b9c1b51eSKate Stone     if (state) {
9312c1f46dcSZachary Turner       long tid = state->thread_id;
93222c8efcdSZachary Turner       PyThreadState_Swap(state);
9332c1f46dcSZachary Turner       int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
93463e5fb76SJonas Devlieghere       LLDB_LOGF(log,
93563e5fb76SJonas Devlieghere                 "ScriptInterpreterPythonImpl::Interrupt() sending "
936b9c1b51eSKate Stone                 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
937b9c1b51eSKate Stone                 tid, num_threads);
9382c1f46dcSZachary Turner       return true;
9392c1f46dcSZachary Turner     }
9402c1f46dcSZachary Turner   }
94163e5fb76SJonas Devlieghere   LLDB_LOGF(log,
94263dd5d25SJonas Devlieghere             "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
943b9c1b51eSKate Stone             "can't interrupt");
9442c1f46dcSZachary Turner   return false;
9452c1f46dcSZachary Turner }
94604edd189SLawrence D'Anna 
94763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
9484d51a902SRaphael Isemann     llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
949b9c1b51eSKate Stone     void *ret_value, const ExecuteScriptOptions &options) {
9502c1f46dcSZachary Turner 
951f9517353SJonas Devlieghere   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
952f9517353SJonas Devlieghere       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
953f9517353SJonas Devlieghere           options.GetEnableIO(), m_debugger, /*result=*/nullptr);
954f9517353SJonas Devlieghere 
955f9517353SJonas Devlieghere   if (!io_redirect_or_error) {
956f9517353SJonas Devlieghere     llvm::consumeError(io_redirect_or_error.takeError());
957f9517353SJonas Devlieghere     return false;
958f9517353SJonas Devlieghere   }
959f9517353SJonas Devlieghere 
960f9517353SJonas Devlieghere   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
961f9517353SJonas Devlieghere 
96263dd5d25SJonas Devlieghere   Locker locker(this,
96363dd5d25SJonas Devlieghere                 Locker::AcquireLock | Locker::InitSession |
96463dd5d25SJonas Devlieghere                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
965b9c1b51eSKate Stone                     Locker::NoSTDIN,
966f9517353SJonas Devlieghere                 Locker::FreeAcquiredLock | Locker::TearDownSession,
967f9517353SJonas Devlieghere                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
968f9517353SJonas Devlieghere                 io_redirect.GetErrorFile());
9692c1f46dcSZachary Turner 
97004edd189SLawrence D'Anna   PythonModule &main_module = GetMainModule();
97104edd189SLawrence D'Anna   PythonDictionary globals = main_module.GetDictionary();
9722c1f46dcSZachary Turner 
9732c1f46dcSZachary Turner   PythonDictionary locals = GetSessionDictionary();
97404edd189SLawrence D'Anna   if (!locals.IsValid())
975722b6189SLawrence D'Anna     locals = unwrapIgnoringErrors(
976722b6189SLawrence D'Anna         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
977f8b22f8fSZachary Turner   if (!locals.IsValid())
9782c1f46dcSZachary Turner     locals = globals;
9792c1f46dcSZachary Turner 
98004edd189SLawrence D'Anna   Expected<PythonObject> maybe_py_return =
98104edd189SLawrence D'Anna       runStringOneLine(in_string, globals, locals);
9822c1f46dcSZachary Turner 
98304edd189SLawrence D'Anna   if (!maybe_py_return) {
98404edd189SLawrence D'Anna     llvm::handleAllErrors(
98504edd189SLawrence D'Anna         maybe_py_return.takeError(),
98604edd189SLawrence D'Anna         [&](PythonException &E) {
98704edd189SLawrence D'Anna           E.Restore();
98804edd189SLawrence D'Anna           if (options.GetMaskoutErrors()) {
98904edd189SLawrence D'Anna             if (E.Matches(PyExc_SyntaxError)) {
99004edd189SLawrence D'Anna               PyErr_Print();
9912c1f46dcSZachary Turner             }
99204edd189SLawrence D'Anna             PyErr_Clear();
99304edd189SLawrence D'Anna           }
99404edd189SLawrence D'Anna         },
99504edd189SLawrence D'Anna         [](const llvm::ErrorInfoBase &E) {});
99604edd189SLawrence D'Anna     return false;
9972c1f46dcSZachary Turner   }
9982c1f46dcSZachary Turner 
99904edd189SLawrence D'Anna   PythonObject py_return = std::move(maybe_py_return.get());
100004edd189SLawrence D'Anna   assert(py_return.IsValid());
100104edd189SLawrence D'Anna 
1002b9c1b51eSKate Stone   switch (return_type) {
10032c1f46dcSZachary Turner   case eScriptReturnTypeCharPtr: // "char *"
10042c1f46dcSZachary Turner   {
10052c1f46dcSZachary Turner     const char format[3] = "s#";
100604edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
10072c1f46dcSZachary Turner   }
1008b9c1b51eSKate Stone   case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
1009b9c1b51eSKate Stone                                        // Py_None
10102c1f46dcSZachary Turner   {
10112c1f46dcSZachary Turner     const char format[3] = "z";
101204edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
10132c1f46dcSZachary Turner   }
1014b9c1b51eSKate Stone   case eScriptReturnTypeBool: {
10152c1f46dcSZachary Turner     const char format[2] = "b";
101604edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
10172c1f46dcSZachary Turner   }
1018b9c1b51eSKate Stone   case eScriptReturnTypeShortInt: {
10192c1f46dcSZachary Turner     const char format[2] = "h";
102004edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (short *)ret_value);
10212c1f46dcSZachary Turner   }
1022b9c1b51eSKate Stone   case eScriptReturnTypeShortIntUnsigned: {
10232c1f46dcSZachary Turner     const char format[2] = "H";
102404edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
10252c1f46dcSZachary Turner   }
1026b9c1b51eSKate Stone   case eScriptReturnTypeInt: {
10272c1f46dcSZachary Turner     const char format[2] = "i";
102804edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (int *)ret_value);
10292c1f46dcSZachary Turner   }
1030b9c1b51eSKate Stone   case eScriptReturnTypeIntUnsigned: {
10312c1f46dcSZachary Turner     const char format[2] = "I";
103204edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
10332c1f46dcSZachary Turner   }
1034b9c1b51eSKate Stone   case eScriptReturnTypeLongInt: {
10352c1f46dcSZachary Turner     const char format[2] = "l";
103604edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (long *)ret_value);
10372c1f46dcSZachary Turner   }
1038b9c1b51eSKate Stone   case eScriptReturnTypeLongIntUnsigned: {
10392c1f46dcSZachary Turner     const char format[2] = "k";
104004edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
10412c1f46dcSZachary Turner   }
1042b9c1b51eSKate Stone   case eScriptReturnTypeLongLong: {
10432c1f46dcSZachary Turner     const char format[2] = "L";
104404edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
10452c1f46dcSZachary Turner   }
1046b9c1b51eSKate Stone   case eScriptReturnTypeLongLongUnsigned: {
10472c1f46dcSZachary Turner     const char format[2] = "K";
104804edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format,
104904edd189SLawrence D'Anna                        (unsigned long long *)ret_value);
10502c1f46dcSZachary Turner   }
1051b9c1b51eSKate Stone   case eScriptReturnTypeFloat: {
10522c1f46dcSZachary Turner     const char format[2] = "f";
105304edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (float *)ret_value);
10542c1f46dcSZachary Turner   }
1055b9c1b51eSKate Stone   case eScriptReturnTypeDouble: {
10562c1f46dcSZachary Turner     const char format[2] = "d";
105704edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (double *)ret_value);
10582c1f46dcSZachary Turner   }
1059b9c1b51eSKate Stone   case eScriptReturnTypeChar: {
10602c1f46dcSZachary Turner     const char format[2] = "c";
106104edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (char *)ret_value);
10622c1f46dcSZachary Turner   }
1063b9c1b51eSKate Stone   case eScriptReturnTypeOpaqueObject: {
106404edd189SLawrence D'Anna     *((PyObject **)ret_value) = py_return.release();
106504edd189SLawrence D'Anna     return true;
10662c1f46dcSZachary Turner   }
10672c1f46dcSZachary Turner   }
10681dfb1a85SPavel Labath   llvm_unreachable("Fully covered switch!");
10692c1f46dcSZachary Turner }
10702c1f46dcSZachary Turner 
107163dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1072b9c1b51eSKate Stone     const char *in_string, const ExecuteScriptOptions &options) {
107304edd189SLawrence D'Anna 
107404edd189SLawrence D'Anna   if (in_string == nullptr)
107504edd189SLawrence D'Anna     return Status();
10762c1f46dcSZachary Turner 
1077f9517353SJonas Devlieghere   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1078f9517353SJonas Devlieghere       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1079f9517353SJonas Devlieghere           options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1080f9517353SJonas Devlieghere 
1081f9517353SJonas Devlieghere   if (!io_redirect_or_error)
1082f9517353SJonas Devlieghere     return Status(io_redirect_or_error.takeError());
1083f9517353SJonas Devlieghere 
1084f9517353SJonas Devlieghere   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1085f9517353SJonas Devlieghere 
108663dd5d25SJonas Devlieghere   Locker locker(this,
108763dd5d25SJonas Devlieghere                 Locker::AcquireLock | Locker::InitSession |
108863dd5d25SJonas Devlieghere                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1089b9c1b51eSKate Stone                     Locker::NoSTDIN,
1090f9517353SJonas Devlieghere                 Locker::FreeAcquiredLock | Locker::TearDownSession,
1091f9517353SJonas Devlieghere                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1092f9517353SJonas Devlieghere                 io_redirect.GetErrorFile());
10932c1f46dcSZachary Turner 
109404edd189SLawrence D'Anna   PythonModule &main_module = GetMainModule();
109504edd189SLawrence D'Anna   PythonDictionary globals = main_module.GetDictionary();
10962c1f46dcSZachary Turner 
10972c1f46dcSZachary Turner   PythonDictionary locals = GetSessionDictionary();
1098f8b22f8fSZachary Turner   if (!locals.IsValid())
1099722b6189SLawrence D'Anna     locals = unwrapIgnoringErrors(
1100722b6189SLawrence D'Anna         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1101f8b22f8fSZachary Turner   if (!locals.IsValid())
11022c1f46dcSZachary Turner     locals = globals;
11032c1f46dcSZachary Turner 
110404edd189SLawrence D'Anna   Expected<PythonObject> return_value =
110504edd189SLawrence D'Anna       runStringMultiLine(in_string, globals, locals);
11062c1f46dcSZachary Turner 
110704edd189SLawrence D'Anna   if (!return_value) {
110804edd189SLawrence D'Anna     llvm::Error error =
110904edd189SLawrence D'Anna         llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
111004edd189SLawrence D'Anna           llvm::Error error = llvm::createStringError(
111104edd189SLawrence D'Anna               llvm::inconvertibleErrorCode(), E.ReadBacktrace());
111204edd189SLawrence D'Anna           if (!options.GetMaskoutErrors())
111304edd189SLawrence D'Anna             E.Restore();
11142c1f46dcSZachary Turner           return error;
111504edd189SLawrence D'Anna         });
111604edd189SLawrence D'Anna     return Status(std::move(error));
111704edd189SLawrence D'Anna   }
111804edd189SLawrence D'Anna 
111904edd189SLawrence D'Anna   return Status();
11202c1f46dcSZachary Turner }
11212c1f46dcSZachary Turner 
112263dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1123cfb96d84SJim Ingham     std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1124b9c1b51eSKate Stone     CommandReturnObject &result) {
11252c1f46dcSZachary Turner   m_active_io_handler = eIOHandlerBreakpoint;
11268d1fb843SJonas Devlieghere   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1127a6faf851SJonas Devlieghere       "    ", *this, &bp_options_vec);
11282c1f46dcSZachary Turner }
11292c1f46dcSZachary Turner 
113063dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1131b9c1b51eSKate Stone     WatchpointOptions *wp_options, CommandReturnObject &result) {
11322c1f46dcSZachary Turner   m_active_io_handler = eIOHandlerWatchpoint;
11338d1fb843SJonas Devlieghere   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1134a6faf851SJonas Devlieghere       "    ", *this, wp_options);
11352c1f46dcSZachary Turner }
11362c1f46dcSZachary Turner 
1137738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1138cfb96d84SJim Ingham     BreakpointOptions &bp_options, const char *function_name,
1139738af7a6SJim Ingham     StructuredData::ObjectSP extra_args_sp) {
1140738af7a6SJim Ingham   Status error;
11412c1f46dcSZachary Turner   // For now just cons up a oneliner that calls the provided function.
11422c1f46dcSZachary Turner   std::string oneliner("return ");
11432c1f46dcSZachary Turner   oneliner += function_name;
1144738af7a6SJim Ingham 
1145a69bbe02SLawrence D'Anna   llvm::Expected<unsigned> maybe_args =
1146a69bbe02SLawrence D'Anna       GetMaxPositionalArgumentsForCallable(function_name);
1147738af7a6SJim Ingham   if (!maybe_args) {
1148a69bbe02SLawrence D'Anna     error.SetErrorStringWithFormat(
1149a69bbe02SLawrence D'Anna         "could not get num args: %s",
1150738af7a6SJim Ingham         llvm::toString(maybe_args.takeError()).c_str());
1151738af7a6SJim Ingham     return error;
1152738af7a6SJim Ingham   }
1153a69bbe02SLawrence D'Anna   size_t max_args = *maybe_args;
1154738af7a6SJim Ingham 
1155738af7a6SJim Ingham   bool uses_extra_args = false;
1156a69bbe02SLawrence D'Anna   if (max_args >= 4) {
1157738af7a6SJim Ingham     uses_extra_args = true;
1158738af7a6SJim Ingham     oneliner += "(frame, bp_loc, extra_args, internal_dict)";
1159a69bbe02SLawrence D'Anna   } else if (max_args >= 3) {
1160738af7a6SJim Ingham     if (extra_args_sp) {
1161738af7a6SJim Ingham       error.SetErrorString("cannot pass extra_args to a three argument callback"
1162738af7a6SJim Ingham                           );
1163738af7a6SJim Ingham       return error;
1164738af7a6SJim Ingham     }
1165738af7a6SJim Ingham     uses_extra_args = false;
11662c1f46dcSZachary Turner     oneliner += "(frame, bp_loc, internal_dict)";
1167738af7a6SJim Ingham   } else {
1168738af7a6SJim Ingham     error.SetErrorStringWithFormat("expected 3 or 4 argument "
1169a69bbe02SLawrence D'Anna                                    "function, %s can only take %zu",
1170a69bbe02SLawrence D'Anna                                    function_name, max_args);
1171738af7a6SJim Ingham     return error;
1172738af7a6SJim Ingham   }
1173738af7a6SJim Ingham 
1174738af7a6SJim Ingham   SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp,
1175738af7a6SJim Ingham                                uses_extra_args);
1176738af7a6SJim Ingham   return error;
11772c1f46dcSZachary Turner }
11782c1f46dcSZachary Turner 
117963dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1180cfb96d84SJim Ingham     BreakpointOptions &bp_options,
1181f7e07256SJim Ingham     std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
118297206d57SZachary Turner   Status error;
1183f7e07256SJim Ingham   error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1184738af7a6SJim Ingham                                                 cmd_data_up->script_source,
1185738af7a6SJim Ingham                                                 false);
1186f7e07256SJim Ingham   if (error.Fail()) {
1187f7e07256SJim Ingham     return error;
1188f7e07256SJim Ingham   }
1189f7e07256SJim Ingham   auto baton_sp =
1190f7e07256SJim Ingham       std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1191cfb96d84SJim Ingham   bp_options.SetCallback(
119263dd5d25SJonas Devlieghere       ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1193f7e07256SJim Ingham   return error;
1194f7e07256SJim Ingham }
1195f7e07256SJim Ingham 
119663dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1197cfb96d84SJim Ingham     BreakpointOptions &bp_options, const char *command_body_text) {
1198738af7a6SJim Ingham   return SetBreakpointCommandCallback(bp_options, command_body_text, {},false);
1199738af7a6SJim Ingham }
12002c1f46dcSZachary Turner 
1201738af7a6SJim Ingham // Set a Python one-liner as the callback for the breakpoint.
1202738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1203cfb96d84SJim Ingham     BreakpointOptions &bp_options, const char *command_body_text,
1204cfb96d84SJim Ingham     StructuredData::ObjectSP extra_args_sp, bool uses_extra_args) {
1205738af7a6SJim Ingham   auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1206b9c1b51eSKate Stone   // Split the command_body_text into lines, and pass that to
120705097246SAdrian Prantl   // GenerateBreakpointCommandCallbackData.  That will wrap the body in an
120805097246SAdrian Prantl   // auto-generated function, and return the function name in script_source.
120905097246SAdrian Prantl   // That is what the callback will actually invoke.
12102c1f46dcSZachary Turner 
1211d5b44036SJonas Devlieghere   data_up->user_source.SplitIntoLines(command_body_text);
1212d5b44036SJonas Devlieghere   Status error = GenerateBreakpointCommandCallbackData(data_up->user_source,
1213738af7a6SJim Ingham                                                        data_up->script_source,
1214738af7a6SJim Ingham                                                        uses_extra_args);
1215b9c1b51eSKate Stone   if (error.Success()) {
12164e4fbe82SZachary Turner     auto baton_sp =
1217d5b44036SJonas Devlieghere         std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1218cfb96d84SJim Ingham     bp_options.SetCallback(
121963dd5d25SJonas Devlieghere         ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
12202c1f46dcSZachary Turner     return error;
122193571c3cSJonas Devlieghere   }
12222c1f46dcSZachary Turner   return error;
12232c1f46dcSZachary Turner }
12242c1f46dcSZachary Turner 
12252c1f46dcSZachary Turner // Set a Python one-liner as the callback for the watchpoint.
122663dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1227b9c1b51eSKate Stone     WatchpointOptions *wp_options, const char *oneliner) {
1228a8f3ae7cSJonas Devlieghere   auto data_up = std::make_unique<WatchpointOptions::CommandData>();
12292c1f46dcSZachary Turner 
12302c1f46dcSZachary Turner   // It's necessary to set both user_source and script_source to the oneliner.
1231b9c1b51eSKate Stone   // The former is used to generate callback description (as in watchpoint
123205097246SAdrian Prantl   // command list) while the latter is used for Python to interpret during the
123305097246SAdrian Prantl   // actual callback.
12342c1f46dcSZachary Turner 
1235d5b44036SJonas Devlieghere   data_up->user_source.AppendString(oneliner);
1236d5b44036SJonas Devlieghere   data_up->script_source.assign(oneliner);
12372c1f46dcSZachary Turner 
1238d5b44036SJonas Devlieghere   if (GenerateWatchpointCommandCallbackData(data_up->user_source,
1239d5b44036SJonas Devlieghere                                             data_up->script_source)) {
12404e4fbe82SZachary Turner     auto baton_sp =
1241d5b44036SJonas Devlieghere         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
124263dd5d25SJonas Devlieghere     wp_options->SetCallback(
124363dd5d25SJonas Devlieghere         ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
12442c1f46dcSZachary Turner   }
12452c1f46dcSZachary Turner 
12462c1f46dcSZachary Turner   return;
12472c1f46dcSZachary Turner }
12482c1f46dcSZachary Turner 
124963dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1250b9c1b51eSKate Stone     StringList &function_def) {
12512c1f46dcSZachary Turner   // Convert StringList to one long, newline delimited, const char *.
12522c1f46dcSZachary Turner   std::string function_def_string(function_def.CopyList());
12532c1f46dcSZachary Turner 
125497206d57SZachary Turner   Status error = ExecuteMultipleLines(
1255b9c1b51eSKate Stone       function_def_string.c_str(),
1256fd2433e1SJonas Devlieghere       ExecuteScriptOptions().SetEnableIO(false));
12572c1f46dcSZachary Turner   return error;
12582c1f46dcSZachary Turner }
12592c1f46dcSZachary Turner 
126063dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature,
1261b9c1b51eSKate Stone                                                      const StringList &input) {
126297206d57SZachary Turner   Status error;
12632c1f46dcSZachary Turner   int num_lines = input.GetSize();
1264b9c1b51eSKate Stone   if (num_lines == 0) {
12652c1f46dcSZachary Turner     error.SetErrorString("No input data.");
12662c1f46dcSZachary Turner     return error;
12672c1f46dcSZachary Turner   }
12682c1f46dcSZachary Turner 
1269b9c1b51eSKate Stone   if (!signature || *signature == 0) {
12702c1f46dcSZachary Turner     error.SetErrorString("No output function name.");
12712c1f46dcSZachary Turner     return error;
12722c1f46dcSZachary Turner   }
12732c1f46dcSZachary Turner 
12742c1f46dcSZachary Turner   StreamString sstr;
12752c1f46dcSZachary Turner   StringList auto_generated_function;
12762c1f46dcSZachary Turner   auto_generated_function.AppendString(signature);
1277b9c1b51eSKate Stone   auto_generated_function.AppendString(
1278b9c1b51eSKate Stone       "     global_dict = globals()"); // Grab the global dictionary
1279b9c1b51eSKate Stone   auto_generated_function.AppendString(
1280b9c1b51eSKate Stone       "     new_keys = internal_dict.keys()"); // Make a list of keys in the
1281b9c1b51eSKate Stone                                                // session dict
1282b9c1b51eSKate Stone   auto_generated_function.AppendString(
1283b9c1b51eSKate Stone       "     old_keys = global_dict.keys()"); // Save list of keys in global dict
1284b9c1b51eSKate Stone   auto_generated_function.AppendString(
1285b9c1b51eSKate Stone       "     global_dict.update (internal_dict)"); // Add the session dictionary
1286b9c1b51eSKate Stone                                                   // to the
12872c1f46dcSZachary Turner   // global dictionary.
12882c1f46dcSZachary Turner 
12892c1f46dcSZachary Turner   // Wrap everything up inside the function, increasing the indentation.
12902c1f46dcSZachary Turner 
12912c1f46dcSZachary Turner   auto_generated_function.AppendString("     if True:");
1292b9c1b51eSKate Stone   for (int i = 0; i < num_lines; ++i) {
12932c1f46dcSZachary Turner     sstr.Clear();
12942c1f46dcSZachary Turner     sstr.Printf("       %s", input.GetStringAtIndex(i));
12952c1f46dcSZachary Turner     auto_generated_function.AppendString(sstr.GetData());
12962c1f46dcSZachary Turner   }
1297b9c1b51eSKate Stone   auto_generated_function.AppendString(
1298b9c1b51eSKate Stone       "     for key in new_keys:"); // Iterate over all the keys from session
1299b9c1b51eSKate Stone                                     // dict
1300b9c1b51eSKate Stone   auto_generated_function.AppendString(
1301b9c1b51eSKate Stone       "         internal_dict[key] = global_dict[key]"); // Update session dict
1302b9c1b51eSKate Stone                                                          // values
1303b9c1b51eSKate Stone   auto_generated_function.AppendString(
1304b9c1b51eSKate Stone       "         if key not in old_keys:"); // If key was not originally in
1305b9c1b51eSKate Stone                                            // global dict
1306b9c1b51eSKate Stone   auto_generated_function.AppendString(
1307b9c1b51eSKate Stone       "             del global_dict[key]"); //  ...then remove key/value from
1308b9c1b51eSKate Stone                                             //  global dict
13092c1f46dcSZachary Turner 
13102c1f46dcSZachary Turner   // Verify that the results are valid Python.
13112c1f46dcSZachary Turner 
13122c1f46dcSZachary Turner   error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
13132c1f46dcSZachary Turner 
13142c1f46dcSZachary Turner   return error;
13152c1f46dcSZachary Turner }
13162c1f46dcSZachary Turner 
131763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1318b9c1b51eSKate Stone     StringList &user_input, std::string &output, const void *name_token) {
13192c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
13202c1f46dcSZachary Turner   user_input.RemoveBlankLines();
13212c1f46dcSZachary Turner   StreamString sstr;
13222c1f46dcSZachary Turner 
13232c1f46dcSZachary Turner   // Check to see if we have any data; if not, just return.
13242c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
13252c1f46dcSZachary Turner     return false;
13262c1f46dcSZachary Turner 
1327b9c1b51eSKate Stone   // Take what the user wrote, wrap it all up inside one big auto-generated
132805097246SAdrian Prantl   // Python function, passing in the ValueObject as parameter to the function.
13292c1f46dcSZachary Turner 
1330b9c1b51eSKate Stone   std::string auto_generated_function_name(
1331b9c1b51eSKate Stone       GenerateUniqueName("lldb_autogen_python_type_print_func",
1332b9c1b51eSKate Stone                          num_created_functions, name_token));
1333b9c1b51eSKate Stone   sstr.Printf("def %s (valobj, internal_dict):",
1334b9c1b51eSKate Stone               auto_generated_function_name.c_str());
13352c1f46dcSZachary Turner 
13362c1f46dcSZachary Turner   if (!GenerateFunction(sstr.GetData(), user_input).Success())
13372c1f46dcSZachary Turner     return false;
13382c1f46dcSZachary Turner 
13392c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
13402c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
13412c1f46dcSZachary Turner   return true;
13422c1f46dcSZachary Turner }
13432c1f46dcSZachary Turner 
134463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1345b9c1b51eSKate Stone     StringList &user_input, std::string &output) {
13462c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
13472c1f46dcSZachary Turner   user_input.RemoveBlankLines();
13482c1f46dcSZachary Turner   StreamString sstr;
13492c1f46dcSZachary Turner 
13502c1f46dcSZachary Turner   // Check to see if we have any data; if not, just return.
13512c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
13522c1f46dcSZachary Turner     return false;
13532c1f46dcSZachary Turner 
1354b9c1b51eSKate Stone   std::string auto_generated_function_name(GenerateUniqueName(
1355b9c1b51eSKate Stone       "lldb_autogen_python_cmd_alias_func", num_created_functions));
13562c1f46dcSZachary Turner 
1357b9c1b51eSKate Stone   sstr.Printf("def %s (debugger, args, result, internal_dict):",
1358b9c1b51eSKate Stone               auto_generated_function_name.c_str());
13592c1f46dcSZachary Turner 
13602c1f46dcSZachary Turner   if (!GenerateFunction(sstr.GetData(), user_input).Success())
13612c1f46dcSZachary Turner     return false;
13622c1f46dcSZachary Turner 
13632c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
13642c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
13652c1f46dcSZachary Turner   return true;
13662c1f46dcSZachary Turner }
13672c1f46dcSZachary Turner 
136863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
136963dd5d25SJonas Devlieghere     StringList &user_input, std::string &output, const void *name_token) {
13702c1f46dcSZachary Turner   static uint32_t num_created_classes = 0;
13712c1f46dcSZachary Turner   user_input.RemoveBlankLines();
13722c1f46dcSZachary Turner   int num_lines = user_input.GetSize();
13732c1f46dcSZachary Turner   StreamString sstr;
13742c1f46dcSZachary Turner 
13752c1f46dcSZachary Turner   // Check to see if we have any data; if not, just return.
13762c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
13772c1f46dcSZachary Turner     return false;
13782c1f46dcSZachary Turner 
13792c1f46dcSZachary Turner   // Wrap all user input into a Python class
13802c1f46dcSZachary Turner 
1381b9c1b51eSKate Stone   std::string auto_generated_class_name(GenerateUniqueName(
1382b9c1b51eSKate Stone       "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
13832c1f46dcSZachary Turner 
13842c1f46dcSZachary Turner   StringList auto_generated_class;
13852c1f46dcSZachary Turner 
13862c1f46dcSZachary Turner   // Create the function name & definition string.
13872c1f46dcSZachary Turner 
13882c1f46dcSZachary Turner   sstr.Printf("class %s:", auto_generated_class_name.c_str());
1389c156427dSZachary Turner   auto_generated_class.AppendString(sstr.GetString());
13902c1f46dcSZachary Turner 
139105097246SAdrian Prantl   // Wrap everything up inside the class, increasing the indentation. we don't
139205097246SAdrian Prantl   // need to play any fancy indentation tricks here because there is no
13932c1f46dcSZachary Turner   // surrounding code whose indentation we need to honor
1394b9c1b51eSKate Stone   for (int i = 0; i < num_lines; ++i) {
13952c1f46dcSZachary Turner     sstr.Clear();
13962c1f46dcSZachary Turner     sstr.Printf("     %s", user_input.GetStringAtIndex(i));
1397c156427dSZachary Turner     auto_generated_class.AppendString(sstr.GetString());
13982c1f46dcSZachary Turner   }
13992c1f46dcSZachary Turner 
140005097246SAdrian Prantl   // Verify that the results are valid Python. (even though the method is
140105097246SAdrian Prantl   // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
14022c1f46dcSZachary Turner   // (TODO: rename that method to ExportDefinitionToInterpreter)
14032c1f46dcSZachary Turner   if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
14042c1f46dcSZachary Turner     return false;
14052c1f46dcSZachary Turner 
14062c1f46dcSZachary Turner   // Store the name of the auto-generated class
14072c1f46dcSZachary Turner 
14082c1f46dcSZachary Turner   output.assign(auto_generated_class_name);
14092c1f46dcSZachary Turner   return true;
14102c1f46dcSZachary Turner }
14112c1f46dcSZachary Turner 
141263dd5d25SJonas Devlieghere StructuredData::GenericSP
141363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
141441ae8e74SKuba Mracek   if (class_name == nullptr || class_name[0] == '\0')
141541ae8e74SKuba Mracek     return StructuredData::GenericSP();
141641ae8e74SKuba Mracek 
141741ae8e74SKuba Mracek   void *ret_val;
141841ae8e74SKuba Mracek 
141941ae8e74SKuba Mracek   {
142041ae8e74SKuba Mracek     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
142141ae8e74SKuba Mracek                    Locker::FreeLock);
142205495c5dSJonas Devlieghere     ret_val = LLDBSWIGPython_CreateFrameRecognizer(class_name,
142305495c5dSJonas Devlieghere                                                    m_dictionary_name.c_str());
142441ae8e74SKuba Mracek   }
142541ae8e74SKuba Mracek 
142641ae8e74SKuba Mracek   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
142741ae8e74SKuba Mracek }
142841ae8e74SKuba Mracek 
142963dd5d25SJonas Devlieghere lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
143041ae8e74SKuba Mracek     const StructuredData::ObjectSP &os_plugin_object_sp,
143141ae8e74SKuba Mracek     lldb::StackFrameSP frame_sp) {
143241ae8e74SKuba Mracek   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
143341ae8e74SKuba Mracek 
143463dd5d25SJonas Devlieghere   if (!os_plugin_object_sp)
143563dd5d25SJonas Devlieghere     return ValueObjectListSP();
143641ae8e74SKuba Mracek 
143741ae8e74SKuba Mracek   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
143863dd5d25SJonas Devlieghere   if (!generic)
143963dd5d25SJonas Devlieghere     return nullptr;
144041ae8e74SKuba Mracek 
144141ae8e74SKuba Mracek   PythonObject implementor(PyRefType::Borrowed,
144241ae8e74SKuba Mracek                            (PyObject *)generic->GetValue());
144341ae8e74SKuba Mracek 
144463dd5d25SJonas Devlieghere   if (!implementor.IsAllocated())
144563dd5d25SJonas Devlieghere     return ValueObjectListSP();
144641ae8e74SKuba Mracek 
14479a14adeaSPavel Labath   PythonObject py_return(
14489a14adeaSPavel Labath       PyRefType::Owned,
14499a14adeaSPavel Labath       LLDBSwigPython_GetRecognizedArguments(implementor.get(), frame_sp));
145041ae8e74SKuba Mracek 
145141ae8e74SKuba Mracek   // if it fails, print the error but otherwise go on
145241ae8e74SKuba Mracek   if (PyErr_Occurred()) {
145341ae8e74SKuba Mracek     PyErr_Print();
145441ae8e74SKuba Mracek     PyErr_Clear();
145541ae8e74SKuba Mracek   }
145641ae8e74SKuba Mracek   if (py_return.get()) {
145741ae8e74SKuba Mracek     PythonList result_list(PyRefType::Borrowed, py_return.get());
145841ae8e74SKuba Mracek     ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
14598f81aed1SDavid Bolvansky     for (size_t i = 0; i < result_list.GetSize(); i++) {
146041ae8e74SKuba Mracek       PyObject *item = result_list.GetItemAtIndex(i).get();
146141ae8e74SKuba Mracek       lldb::SBValue *sb_value_ptr =
146205495c5dSJonas Devlieghere           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
146305495c5dSJonas Devlieghere       auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
146463dd5d25SJonas Devlieghere       if (valobj_sp)
146563dd5d25SJonas Devlieghere         result->Append(valobj_sp);
146641ae8e74SKuba Mracek     }
146741ae8e74SKuba Mracek     return result;
146841ae8e74SKuba Mracek   }
146941ae8e74SKuba Mracek   return ValueObjectListSP();
147041ae8e74SKuba Mracek }
147141ae8e74SKuba Mracek 
147263dd5d25SJonas Devlieghere StructuredData::GenericSP
147363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject(
1474b9c1b51eSKate Stone     const char *class_name, lldb::ProcessSP process_sp) {
14752c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
14762c1f46dcSZachary Turner     return StructuredData::GenericSP();
14772c1f46dcSZachary Turner 
14782c1f46dcSZachary Turner   if (!process_sp)
14792c1f46dcSZachary Turner     return StructuredData::GenericSP();
14802c1f46dcSZachary Turner 
14812c1f46dcSZachary Turner   void *ret_val;
14822c1f46dcSZachary Turner 
14832c1f46dcSZachary Turner   {
1484b9c1b51eSKate Stone     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
14852c1f46dcSZachary Turner                    Locker::FreeLock);
148605495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonCreateOSPlugin(
148705495c5dSJonas Devlieghere         class_name, m_dictionary_name.c_str(), process_sp);
14882c1f46dcSZachary Turner   }
14892c1f46dcSZachary Turner 
14902c1f46dcSZachary Turner   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
14912c1f46dcSZachary Turner }
14922c1f46dcSZachary Turner 
149363dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo(
1494b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp) {
1495b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
14962c1f46dcSZachary Turner 
14972c1f46dcSZachary Turner   static char callee_name[] = "get_register_info";
14982c1f46dcSZachary Turner 
14992c1f46dcSZachary Turner   if (!os_plugin_object_sp)
15002c1f46dcSZachary Turner     return StructuredData::DictionarySP();
15012c1f46dcSZachary Turner 
15022c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
15032c1f46dcSZachary Turner   if (!generic)
15042c1f46dcSZachary Turner     return nullptr;
15052c1f46dcSZachary Turner 
1506b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1507b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
15082c1f46dcSZachary Turner 
1509f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
15102c1f46dcSZachary Turner     return StructuredData::DictionarySP();
15112c1f46dcSZachary Turner 
1512b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1513b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
15142c1f46dcSZachary Turner 
15152c1f46dcSZachary Turner   if (PyErr_Occurred())
15162c1f46dcSZachary Turner     PyErr_Clear();
15172c1f46dcSZachary Turner 
1518f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
15192c1f46dcSZachary Turner     return StructuredData::DictionarySP();
15202c1f46dcSZachary Turner 
1521b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
15222c1f46dcSZachary Turner     if (PyErr_Occurred())
15232c1f46dcSZachary Turner       PyErr_Clear();
15242c1f46dcSZachary Turner 
15252c1f46dcSZachary Turner     return StructuredData::DictionarySP();
15262c1f46dcSZachary Turner   }
15272c1f46dcSZachary Turner 
15282c1f46dcSZachary Turner   if (PyErr_Occurred())
15292c1f46dcSZachary Turner     PyErr_Clear();
15302c1f46dcSZachary Turner 
15312c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1532b9c1b51eSKate Stone   PythonObject py_return(
1533b9c1b51eSKate Stone       PyRefType::Owned,
1534b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
15352c1f46dcSZachary Turner 
15362c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1537b9c1b51eSKate Stone   if (PyErr_Occurred()) {
15382c1f46dcSZachary Turner     PyErr_Print();
15392c1f46dcSZachary Turner     PyErr_Clear();
15402c1f46dcSZachary Turner   }
1541b9c1b51eSKate Stone   if (py_return.get()) {
1542f8b22f8fSZachary Turner     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
15432c1f46dcSZachary Turner     return result_dict.CreateStructuredDictionary();
15442c1f46dcSZachary Turner   }
154558b794aeSGreg Clayton   return StructuredData::DictionarySP();
154658b794aeSGreg Clayton }
15472c1f46dcSZachary Turner 
154863dd5d25SJonas Devlieghere StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo(
1549b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp) {
1550b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
15512c1f46dcSZachary Turner 
15522c1f46dcSZachary Turner   static char callee_name[] = "get_thread_info";
15532c1f46dcSZachary Turner 
15542c1f46dcSZachary Turner   if (!os_plugin_object_sp)
15552c1f46dcSZachary Turner     return StructuredData::ArraySP();
15562c1f46dcSZachary Turner 
15572c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
15582c1f46dcSZachary Turner   if (!generic)
15592c1f46dcSZachary Turner     return nullptr;
15602c1f46dcSZachary Turner 
1561b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1562b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
1563f8b22f8fSZachary Turner 
1564f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
15652c1f46dcSZachary Turner     return StructuredData::ArraySP();
15662c1f46dcSZachary Turner 
1567b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1568b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
15692c1f46dcSZachary Turner 
15702c1f46dcSZachary Turner   if (PyErr_Occurred())
15712c1f46dcSZachary Turner     PyErr_Clear();
15722c1f46dcSZachary Turner 
1573f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
15742c1f46dcSZachary Turner     return StructuredData::ArraySP();
15752c1f46dcSZachary Turner 
1576b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
15772c1f46dcSZachary Turner     if (PyErr_Occurred())
15782c1f46dcSZachary Turner       PyErr_Clear();
15792c1f46dcSZachary Turner 
15802c1f46dcSZachary Turner     return StructuredData::ArraySP();
15812c1f46dcSZachary Turner   }
15822c1f46dcSZachary Turner 
15832c1f46dcSZachary Turner   if (PyErr_Occurred())
15842c1f46dcSZachary Turner     PyErr_Clear();
15852c1f46dcSZachary Turner 
15862c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1587b9c1b51eSKate Stone   PythonObject py_return(
1588b9c1b51eSKate Stone       PyRefType::Owned,
1589b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
15902c1f46dcSZachary Turner 
15912c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1592b9c1b51eSKate Stone   if (PyErr_Occurred()) {
15932c1f46dcSZachary Turner     PyErr_Print();
15942c1f46dcSZachary Turner     PyErr_Clear();
15952c1f46dcSZachary Turner   }
15962c1f46dcSZachary Turner 
1597b9c1b51eSKate Stone   if (py_return.get()) {
1598f8b22f8fSZachary Turner     PythonList result_list(PyRefType::Borrowed, py_return.get());
1599f8b22f8fSZachary Turner     return result_list.CreateStructuredArray();
16002c1f46dcSZachary Turner   }
160158b794aeSGreg Clayton   return StructuredData::ArraySP();
160258b794aeSGreg Clayton }
16032c1f46dcSZachary Turner 
160463dd5d25SJonas Devlieghere StructuredData::StringSP
160563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData(
1606b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
1607b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
16082c1f46dcSZachary Turner 
16092c1f46dcSZachary Turner   static char callee_name[] = "get_register_data";
1610b9c1b51eSKate Stone   static char *param_format =
1611b9c1b51eSKate Stone       const_cast<char *>(GetPythonValueFormatString(tid));
16122c1f46dcSZachary Turner 
16132c1f46dcSZachary Turner   if (!os_plugin_object_sp)
16142c1f46dcSZachary Turner     return StructuredData::StringSP();
16152c1f46dcSZachary Turner 
16162c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
16172c1f46dcSZachary Turner   if (!generic)
16182c1f46dcSZachary Turner     return nullptr;
1619b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1620b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
16212c1f46dcSZachary Turner 
1622f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
16232c1f46dcSZachary Turner     return StructuredData::StringSP();
16242c1f46dcSZachary Turner 
1625b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1626b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
16272c1f46dcSZachary Turner 
16282c1f46dcSZachary Turner   if (PyErr_Occurred())
16292c1f46dcSZachary Turner     PyErr_Clear();
16302c1f46dcSZachary Turner 
1631f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
16322c1f46dcSZachary Turner     return StructuredData::StringSP();
16332c1f46dcSZachary Turner 
1634b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
16352c1f46dcSZachary Turner     if (PyErr_Occurred())
16362c1f46dcSZachary Turner       PyErr_Clear();
16372c1f46dcSZachary Turner     return StructuredData::StringSP();
16382c1f46dcSZachary Turner   }
16392c1f46dcSZachary Turner 
16402c1f46dcSZachary Turner   if (PyErr_Occurred())
16412c1f46dcSZachary Turner     PyErr_Clear();
16422c1f46dcSZachary Turner 
16432c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1644b9c1b51eSKate Stone   PythonObject py_return(
1645b9c1b51eSKate Stone       PyRefType::Owned,
1646b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, param_format, tid));
16472c1f46dcSZachary Turner 
16482c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1649b9c1b51eSKate Stone   if (PyErr_Occurred()) {
16502c1f46dcSZachary Turner     PyErr_Print();
16512c1f46dcSZachary Turner     PyErr_Clear();
16522c1f46dcSZachary Turner   }
1653f8b22f8fSZachary Turner 
1654b9c1b51eSKate Stone   if (py_return.get()) {
16557a76845cSZachary Turner     PythonBytes result(PyRefType::Borrowed, py_return.get());
16567a76845cSZachary Turner     return result.CreateStructuredString();
16572c1f46dcSZachary Turner   }
165858b794aeSGreg Clayton   return StructuredData::StringSP();
165958b794aeSGreg Clayton }
16602c1f46dcSZachary Turner 
166163dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread(
1662b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
1663b9c1b51eSKate Stone     lldb::addr_t context) {
1664b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
16652c1f46dcSZachary Turner 
16662c1f46dcSZachary Turner   static char callee_name[] = "create_thread";
16672c1f46dcSZachary Turner   std::string param_format;
16682c1f46dcSZachary Turner   param_format += GetPythonValueFormatString(tid);
16692c1f46dcSZachary Turner   param_format += GetPythonValueFormatString(context);
16702c1f46dcSZachary Turner 
16712c1f46dcSZachary Turner   if (!os_plugin_object_sp)
16722c1f46dcSZachary Turner     return StructuredData::DictionarySP();
16732c1f46dcSZachary Turner 
16742c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
16752c1f46dcSZachary Turner   if (!generic)
16762c1f46dcSZachary Turner     return nullptr;
16772c1f46dcSZachary Turner 
1678b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1679b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
1680f8b22f8fSZachary Turner 
1681f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
16822c1f46dcSZachary Turner     return StructuredData::DictionarySP();
16832c1f46dcSZachary Turner 
1684b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1685b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
16862c1f46dcSZachary Turner 
16872c1f46dcSZachary Turner   if (PyErr_Occurred())
16882c1f46dcSZachary Turner     PyErr_Clear();
16892c1f46dcSZachary Turner 
1690f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
16912c1f46dcSZachary Turner     return StructuredData::DictionarySP();
16922c1f46dcSZachary Turner 
1693b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
16942c1f46dcSZachary Turner     if (PyErr_Occurred())
16952c1f46dcSZachary Turner       PyErr_Clear();
16962c1f46dcSZachary Turner     return StructuredData::DictionarySP();
16972c1f46dcSZachary Turner   }
16982c1f46dcSZachary Turner 
16992c1f46dcSZachary Turner   if (PyErr_Occurred())
17002c1f46dcSZachary Turner     PyErr_Clear();
17012c1f46dcSZachary Turner 
17022c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1703b9c1b51eSKate Stone   PythonObject py_return(PyRefType::Owned,
1704b9c1b51eSKate Stone                          PyObject_CallMethod(implementor.get(), callee_name,
1705b9c1b51eSKate Stone                                              &param_format[0], tid, context));
17062c1f46dcSZachary Turner 
17072c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1708b9c1b51eSKate Stone   if (PyErr_Occurred()) {
17092c1f46dcSZachary Turner     PyErr_Print();
17102c1f46dcSZachary Turner     PyErr_Clear();
17112c1f46dcSZachary Turner   }
17122c1f46dcSZachary Turner 
1713b9c1b51eSKate Stone   if (py_return.get()) {
1714f8b22f8fSZachary Turner     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
17152c1f46dcSZachary Turner     return result_dict.CreateStructuredDictionary();
17162c1f46dcSZachary Turner   }
171758b794aeSGreg Clayton   return StructuredData::DictionarySP();
171858b794aeSGreg Clayton }
17192c1f46dcSZachary Turner 
172063dd5d25SJonas Devlieghere StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan(
172182de8df2SPavel Labath     const char *class_name, const StructuredDataImpl &args_data,
1722a69bbe02SLawrence D'Anna     std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) {
17232c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
17242c1f46dcSZachary Turner     return StructuredData::ObjectSP();
17252c1f46dcSZachary Turner 
17262c1f46dcSZachary Turner   if (!thread_plan_sp.get())
172793c98346SJim Ingham     return {};
17282c1f46dcSZachary Turner 
17292c1f46dcSZachary Turner   Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
173063dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
1731d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
17322c1f46dcSZachary Turner 
1733d055e3a0SPedro Tammela   if (!python_interpreter)
173493c98346SJim Ingham     return {};
17352c1f46dcSZachary Turner 
17362c1f46dcSZachary Turner   void *ret_val;
17372c1f46dcSZachary Turner 
17382c1f46dcSZachary Turner   {
1739b9c1b51eSKate Stone     Locker py_lock(this,
1740b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
174105495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateScriptedThreadPlan(
1742b9c1b51eSKate Stone         class_name, python_interpreter->m_dictionary_name.c_str(),
174327a14f19SJim Ingham         args_data, error_str, thread_plan_sp);
174493c98346SJim Ingham     if (!ret_val)
174593c98346SJim Ingham       return {};
17462c1f46dcSZachary Turner   }
17472c1f46dcSZachary Turner 
17482c1f46dcSZachary Turner   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
17492c1f46dcSZachary Turner }
17502c1f46dcSZachary Turner 
175163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop(
1752b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
17532c1f46dcSZachary Turner   bool explains_stop = true;
17542c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
17552c1f46dcSZachary Turner   if (implementor_sp)
17562c1f46dcSZachary Turner     generic = implementor_sp->GetAsGeneric();
1757b9c1b51eSKate Stone   if (generic) {
1758b9c1b51eSKate Stone     Locker py_lock(this,
1759b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
176005495c5dSJonas Devlieghere     explains_stop = LLDBSWIGPythonCallThreadPlan(
1761b9c1b51eSKate Stone         generic->GetValue(), "explains_stop", event, script_error);
17622c1f46dcSZachary Turner     if (script_error)
17632c1f46dcSZachary Turner       return true;
17642c1f46dcSZachary Turner   }
17652c1f46dcSZachary Turner   return explains_stop;
17662c1f46dcSZachary Turner }
17672c1f46dcSZachary Turner 
176863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop(
1769b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
17702c1f46dcSZachary Turner   bool should_stop = true;
17712c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
17722c1f46dcSZachary Turner   if (implementor_sp)
17732c1f46dcSZachary Turner     generic = implementor_sp->GetAsGeneric();
1774b9c1b51eSKate Stone   if (generic) {
1775b9c1b51eSKate Stone     Locker py_lock(this,
1776b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
177705495c5dSJonas Devlieghere     should_stop = LLDBSWIGPythonCallThreadPlan(
177805495c5dSJonas Devlieghere         generic->GetValue(), "should_stop", event, script_error);
17792c1f46dcSZachary Turner     if (script_error)
17802c1f46dcSZachary Turner       return true;
17812c1f46dcSZachary Turner   }
17822c1f46dcSZachary Turner   return should_stop;
17832c1f46dcSZachary Turner }
17842c1f46dcSZachary Turner 
178563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale(
1786b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1787c915a7d2SJim Ingham   bool is_stale = true;
1788c915a7d2SJim Ingham   StructuredData::Generic *generic = nullptr;
1789c915a7d2SJim Ingham   if (implementor_sp)
1790c915a7d2SJim Ingham     generic = implementor_sp->GetAsGeneric();
1791b9c1b51eSKate Stone   if (generic) {
1792b9c1b51eSKate Stone     Locker py_lock(this,
1793b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
179405495c5dSJonas Devlieghere     is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale",
179505495c5dSJonas Devlieghere                                             nullptr, script_error);
1796c915a7d2SJim Ingham     if (script_error)
1797c915a7d2SJim Ingham       return true;
1798c915a7d2SJim Ingham   }
1799c915a7d2SJim Ingham   return is_stale;
1800c915a7d2SJim Ingham }
1801c915a7d2SJim Ingham 
180263dd5d25SJonas Devlieghere lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState(
1803b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, bool &script_error) {
18042c1f46dcSZachary Turner   bool should_step = false;
18052c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
18062c1f46dcSZachary Turner   if (implementor_sp)
18072c1f46dcSZachary Turner     generic = implementor_sp->GetAsGeneric();
1808b9c1b51eSKate Stone   if (generic) {
1809b9c1b51eSKate Stone     Locker py_lock(this,
1810b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
181105495c5dSJonas Devlieghere     should_step = LLDBSWIGPythonCallThreadPlan(
1812248a1305SKonrad Kleine         generic->GetValue(), "should_step", nullptr, script_error);
18132c1f46dcSZachary Turner     if (script_error)
18142c1f46dcSZachary Turner       should_step = true;
18152c1f46dcSZachary Turner   }
18162c1f46dcSZachary Turner   if (should_step)
18172c1f46dcSZachary Turner     return lldb::eStateStepping;
18182c1f46dcSZachary Turner   return lldb::eStateRunning;
18192c1f46dcSZachary Turner }
18202c1f46dcSZachary Turner 
18213815e702SJim Ingham StructuredData::GenericSP
182263dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
182382de8df2SPavel Labath     const char *class_name, const StructuredDataImpl &args_data,
18243815e702SJim Ingham     lldb::BreakpointSP &bkpt_sp) {
18253815e702SJim Ingham 
18263815e702SJim Ingham   if (class_name == nullptr || class_name[0] == '\0')
18273815e702SJim Ingham     return StructuredData::GenericSP();
18283815e702SJim Ingham 
18293815e702SJim Ingham   if (!bkpt_sp.get())
18303815e702SJim Ingham     return StructuredData::GenericSP();
18313815e702SJim Ingham 
18323815e702SJim Ingham   Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
183363dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
1834d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
18353815e702SJim Ingham 
1836d055e3a0SPedro Tammela   if (!python_interpreter)
18373815e702SJim Ingham     return StructuredData::GenericSP();
18383815e702SJim Ingham 
18393815e702SJim Ingham   void *ret_val;
18403815e702SJim Ingham 
18413815e702SJim Ingham   {
18423815e702SJim Ingham     Locker py_lock(this,
18433815e702SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
18443815e702SJim Ingham 
184505495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver(
184605495c5dSJonas Devlieghere         class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
184705495c5dSJonas Devlieghere         bkpt_sp);
18483815e702SJim Ingham   }
18493815e702SJim Ingham 
18503815e702SJim Ingham   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
18513815e702SJim Ingham }
18523815e702SJim Ingham 
185363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
185463dd5d25SJonas Devlieghere     StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
18553815e702SJim Ingham   bool should_continue = false;
18563815e702SJim Ingham 
18573815e702SJim Ingham   if (implementor_sp) {
18583815e702SJim Ingham     Locker py_lock(this,
18593815e702SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
186005495c5dSJonas Devlieghere     should_continue = LLDBSwigPythonCallBreakpointResolver(
186105495c5dSJonas Devlieghere         implementor_sp->GetValue(), "__callback__", sym_ctx);
18623815e702SJim Ingham     if (PyErr_Occurred()) {
18633815e702SJim Ingham       PyErr_Print();
18643815e702SJim Ingham       PyErr_Clear();
18653815e702SJim Ingham     }
18663815e702SJim Ingham   }
18673815e702SJim Ingham   return should_continue;
18683815e702SJim Ingham }
18693815e702SJim Ingham 
18703815e702SJim Ingham lldb::SearchDepth
187163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
18723815e702SJim Ingham     StructuredData::GenericSP implementor_sp) {
18733815e702SJim Ingham   int depth_as_int = lldb::eSearchDepthModule;
18743815e702SJim Ingham   if (implementor_sp) {
18753815e702SJim Ingham     Locker py_lock(this,
18763815e702SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
187705495c5dSJonas Devlieghere     depth_as_int = LLDBSwigPythonCallBreakpointResolver(
187805495c5dSJonas Devlieghere         implementor_sp->GetValue(), "__get_depth__", nullptr);
18793815e702SJim Ingham     if (PyErr_Occurred()) {
18803815e702SJim Ingham       PyErr_Print();
18813815e702SJim Ingham       PyErr_Clear();
18823815e702SJim Ingham     }
18833815e702SJim Ingham   }
18843815e702SJim Ingham   if (depth_as_int == lldb::eSearchDepthInvalid)
18853815e702SJim Ingham     return lldb::eSearchDepthModule;
18863815e702SJim Ingham 
18873815e702SJim Ingham   if (depth_as_int <= lldb::kLastSearchDepthKind)
18883815e702SJim Ingham     return (lldb::SearchDepth)depth_as_int;
18893815e702SJim Ingham   return lldb::eSearchDepthModule;
18903815e702SJim Ingham }
18913815e702SJim Ingham 
18921b1d9815SJim Ingham StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
189382de8df2SPavel Labath     TargetSP target_sp, const char *class_name,
189482de8df2SPavel Labath     const StructuredDataImpl &args_data, Status &error) {
18951b1d9815SJim Ingham 
18961b1d9815SJim Ingham   if (!target_sp) {
18971b1d9815SJim Ingham     error.SetErrorString("No target for scripted stop-hook.");
18981b1d9815SJim Ingham     return StructuredData::GenericSP();
18991b1d9815SJim Ingham   }
19001b1d9815SJim Ingham 
19011b1d9815SJim Ingham   if (class_name == nullptr || class_name[0] == '\0') {
19021b1d9815SJim Ingham     error.SetErrorString("No class name for scripted stop-hook.");
19031b1d9815SJim Ingham     return StructuredData::GenericSP();
19041b1d9815SJim Ingham   }
19051b1d9815SJim Ingham 
19061b1d9815SJim Ingham   ScriptInterpreterPythonImpl *python_interpreter =
1907d055e3a0SPedro Tammela       GetPythonInterpreter(m_debugger);
19081b1d9815SJim Ingham 
1909d055e3a0SPedro Tammela   if (!python_interpreter) {
19101b1d9815SJim Ingham     error.SetErrorString("No script interpreter for scripted stop-hook.");
19111b1d9815SJim Ingham     return StructuredData::GenericSP();
19121b1d9815SJim Ingham   }
19131b1d9815SJim Ingham 
19141b1d9815SJim Ingham   void *ret_val;
19151b1d9815SJim Ingham 
19161b1d9815SJim Ingham   {
19171b1d9815SJim Ingham     Locker py_lock(this,
19181b1d9815SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19191b1d9815SJim Ingham 
19201b1d9815SJim Ingham     ret_val = LLDBSwigPythonCreateScriptedStopHook(
19211b1d9815SJim Ingham         target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
19221b1d9815SJim Ingham         args_data, error);
19231b1d9815SJim Ingham   }
19241b1d9815SJim Ingham 
19251b1d9815SJim Ingham   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
19261b1d9815SJim Ingham }
19271b1d9815SJim Ingham 
19281b1d9815SJim Ingham bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
19291b1d9815SJim Ingham     StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
19301b1d9815SJim Ingham     lldb::StreamSP stream_sp) {
19311b1d9815SJim Ingham   assert(implementor_sp &&
19321b1d9815SJim Ingham          "can't call a stop hook with an invalid implementor");
19331b1d9815SJim Ingham   assert(stream_sp && "can't call a stop hook with an invalid stream");
19341b1d9815SJim Ingham 
19351b1d9815SJim Ingham   Locker py_lock(this,
19361b1d9815SJim Ingham                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19371b1d9815SJim Ingham 
19381b1d9815SJim Ingham   lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
19391b1d9815SJim Ingham 
19401b1d9815SJim Ingham   bool ret_val = LLDBSwigPythonStopHookCallHandleStop(
19411b1d9815SJim Ingham       implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
19421b1d9815SJim Ingham   return ret_val;
19431b1d9815SJim Ingham }
19441b1d9815SJim Ingham 
19452c1f46dcSZachary Turner StructuredData::ObjectSP
194663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
194797206d57SZachary Turner                                               lldb_private::Status &error) {
1948dbd7fabaSJonas Devlieghere   if (!FileSystem::Instance().Exists(file_spec)) {
19492c1f46dcSZachary Turner     error.SetErrorString("no such file");
19502c1f46dcSZachary Turner     return StructuredData::ObjectSP();
19512c1f46dcSZachary Turner   }
19522c1f46dcSZachary Turner 
19532c1f46dcSZachary Turner   StructuredData::ObjectSP module_sp;
19542c1f46dcSZachary Turner 
1955f9517353SJonas Devlieghere   LoadScriptOptions load_script_options =
1956f9517353SJonas Devlieghere       LoadScriptOptions().SetInitSession(true).SetSilent(false);
1957f9517353SJonas Devlieghere   if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1958f9517353SJonas Devlieghere                           error, &module_sp))
19592c1f46dcSZachary Turner     return module_sp;
19602c1f46dcSZachary Turner 
19612c1f46dcSZachary Turner   return StructuredData::ObjectSP();
19622c1f46dcSZachary Turner }
19632c1f46dcSZachary Turner 
196463dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
1965b9c1b51eSKate Stone     StructuredData::ObjectSP plugin_module_sp, Target *target,
196697206d57SZachary Turner     const char *setting_name, lldb_private::Status &error) {
196705495c5dSJonas Devlieghere   if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
19682c1f46dcSZachary Turner     return StructuredData::DictionarySP();
19692c1f46dcSZachary Turner   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
19702c1f46dcSZachary Turner   if (!generic)
19712c1f46dcSZachary Turner     return StructuredData::DictionarySP();
19722c1f46dcSZachary Turner 
1973b9c1b51eSKate Stone   Locker py_lock(this,
1974b9c1b51eSKate Stone                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19752c1f46dcSZachary Turner   TargetSP target_sp(target->shared_from_this());
19762c1f46dcSZachary Turner 
197704edd189SLawrence D'Anna   auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting(
197804edd189SLawrence D'Anna       generic->GetValue(), setting_name, target_sp);
197904edd189SLawrence D'Anna 
198004edd189SLawrence D'Anna   if (!setting)
198104edd189SLawrence D'Anna     return StructuredData::DictionarySP();
198204edd189SLawrence D'Anna 
198304edd189SLawrence D'Anna   PythonDictionary py_dict =
198404edd189SLawrence D'Anna       unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
198504edd189SLawrence D'Anna 
198604edd189SLawrence D'Anna   if (!py_dict)
198704edd189SLawrence D'Anna     return StructuredData::DictionarySP();
198804edd189SLawrence D'Anna 
19892c1f46dcSZachary Turner   return py_dict.CreateStructuredDictionary();
19902c1f46dcSZachary Turner }
19912c1f46dcSZachary Turner 
19922c1f46dcSZachary Turner StructuredData::ObjectSP
199363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
1994b9c1b51eSKate Stone     const char *class_name, lldb::ValueObjectSP valobj) {
19952c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
19962c1f46dcSZachary Turner     return StructuredData::ObjectSP();
19972c1f46dcSZachary Turner 
19982c1f46dcSZachary Turner   if (!valobj.get())
19992c1f46dcSZachary Turner     return StructuredData::ObjectSP();
20002c1f46dcSZachary Turner 
20012c1f46dcSZachary Turner   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
20022c1f46dcSZachary Turner   Target *target = exe_ctx.GetTargetPtr();
20032c1f46dcSZachary Turner 
20042c1f46dcSZachary Turner   if (!target)
20052c1f46dcSZachary Turner     return StructuredData::ObjectSP();
20062c1f46dcSZachary Turner 
20072c1f46dcSZachary Turner   Debugger &debugger = target->GetDebugger();
200863dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
2009d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
20102c1f46dcSZachary Turner 
2011d055e3a0SPedro Tammela   if (!python_interpreter)
20122c1f46dcSZachary Turner     return StructuredData::ObjectSP();
20132c1f46dcSZachary Turner 
20142c1f46dcSZachary Turner   void *ret_val = nullptr;
20152c1f46dcSZachary Turner 
20162c1f46dcSZachary Turner   {
2017b9c1b51eSKate Stone     Locker py_lock(this,
2018b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
201905495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateSyntheticProvider(
2020b9c1b51eSKate Stone         class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
20212c1f46dcSZachary Turner   }
20222c1f46dcSZachary Turner 
20232c1f46dcSZachary Turner   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
20242c1f46dcSZachary Turner }
20252c1f46dcSZachary Turner 
20262c1f46dcSZachary Turner StructuredData::GenericSP
202763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
20288d1fb843SJonas Devlieghere   DebuggerSP debugger_sp(m_debugger.shared_from_this());
20292c1f46dcSZachary Turner 
20302c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
20312c1f46dcSZachary Turner     return StructuredData::GenericSP();
20322c1f46dcSZachary Turner 
20332c1f46dcSZachary Turner   if (!debugger_sp.get())
20342c1f46dcSZachary Turner     return StructuredData::GenericSP();
20352c1f46dcSZachary Turner 
20362c1f46dcSZachary Turner   void *ret_val;
20372c1f46dcSZachary Turner 
20382c1f46dcSZachary Turner   {
2039b9c1b51eSKate Stone     Locker py_lock(this,
2040b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
204105495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateCommandObject(
204205495c5dSJonas Devlieghere         class_name, m_dictionary_name.c_str(), debugger_sp);
20432c1f46dcSZachary Turner   }
20442c1f46dcSZachary Turner 
20452c1f46dcSZachary Turner   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
20462c1f46dcSZachary Turner }
20472c1f46dcSZachary Turner 
204863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
2049b9c1b51eSKate Stone     const char *oneliner, std::string &output, const void *name_token) {
20502c1f46dcSZachary Turner   StringList input;
20512c1f46dcSZachary Turner   input.SplitIntoLines(oneliner, strlen(oneliner));
20522c1f46dcSZachary Turner   return GenerateTypeScriptFunction(input, output, name_token);
20532c1f46dcSZachary Turner }
20542c1f46dcSZachary Turner 
205563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
205663dd5d25SJonas Devlieghere     const char *oneliner, std::string &output, const void *name_token) {
20572c1f46dcSZachary Turner   StringList input;
20582c1f46dcSZachary Turner   input.SplitIntoLines(oneliner, strlen(oneliner));
20592c1f46dcSZachary Turner   return GenerateTypeSynthClass(input, output, name_token);
20602c1f46dcSZachary Turner }
20612c1f46dcSZachary Turner 
206263dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
2063738af7a6SJim Ingham     StringList &user_input, std::string &output,
2064738af7a6SJim Ingham     bool has_extra_args) {
20652c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
20662c1f46dcSZachary Turner   user_input.RemoveBlankLines();
20672c1f46dcSZachary Turner   StreamString sstr;
206897206d57SZachary Turner   Status error;
2069b9c1b51eSKate Stone   if (user_input.GetSize() == 0) {
20702c1f46dcSZachary Turner     error.SetErrorString("No input data.");
20712c1f46dcSZachary Turner     return error;
20722c1f46dcSZachary Turner   }
20732c1f46dcSZachary Turner 
2074b9c1b51eSKate Stone   std::string auto_generated_function_name(GenerateUniqueName(
2075b9c1b51eSKate Stone       "lldb_autogen_python_bp_callback_func_", num_created_functions));
2076738af7a6SJim Ingham   if (has_extra_args)
2077738af7a6SJim Ingham     sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
2078738af7a6SJim Ingham                 auto_generated_function_name.c_str());
2079738af7a6SJim Ingham   else
2080b9c1b51eSKate Stone     sstr.Printf("def %s (frame, bp_loc, internal_dict):",
2081b9c1b51eSKate Stone                 auto_generated_function_name.c_str());
20822c1f46dcSZachary Turner 
20832c1f46dcSZachary Turner   error = GenerateFunction(sstr.GetData(), user_input);
20842c1f46dcSZachary Turner   if (!error.Success())
20852c1f46dcSZachary Turner     return error;
20862c1f46dcSZachary Turner 
20872c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
20882c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
20892c1f46dcSZachary Turner   return error;
20902c1f46dcSZachary Turner }
20912c1f46dcSZachary Turner 
209263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
2093b9c1b51eSKate Stone     StringList &user_input, std::string &output) {
20942c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
20952c1f46dcSZachary Turner   user_input.RemoveBlankLines();
20962c1f46dcSZachary Turner   StreamString sstr;
20972c1f46dcSZachary Turner 
20982c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
20992c1f46dcSZachary Turner     return false;
21002c1f46dcSZachary Turner 
2101b9c1b51eSKate Stone   std::string auto_generated_function_name(GenerateUniqueName(
2102b9c1b51eSKate Stone       "lldb_autogen_python_wp_callback_func_", num_created_functions));
2103b9c1b51eSKate Stone   sstr.Printf("def %s (frame, wp, internal_dict):",
2104b9c1b51eSKate Stone               auto_generated_function_name.c_str());
21052c1f46dcSZachary Turner 
21062c1f46dcSZachary Turner   if (!GenerateFunction(sstr.GetData(), user_input).Success())
21072c1f46dcSZachary Turner     return false;
21082c1f46dcSZachary Turner 
21092c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
21102c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
21112c1f46dcSZachary Turner   return true;
21122c1f46dcSZachary Turner }
21132c1f46dcSZachary Turner 
211463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetScriptedSummary(
2115b9c1b51eSKate Stone     const char *python_function_name, lldb::ValueObjectSP valobj,
2116b9c1b51eSKate Stone     StructuredData::ObjectSP &callee_wrapper_sp,
2117b9c1b51eSKate Stone     const TypeSummaryOptions &options, std::string &retval) {
21182c1f46dcSZachary Turner 
21195c1c8443SJonas Devlieghere   LLDB_SCOPED_TIMER();
21202c1f46dcSZachary Turner 
2121b9c1b51eSKate Stone   if (!valobj.get()) {
21222c1f46dcSZachary Turner     retval.assign("<no object>");
21232c1f46dcSZachary Turner     return false;
21242c1f46dcSZachary Turner   }
21252c1f46dcSZachary Turner 
21262c1f46dcSZachary Turner   void *old_callee = nullptr;
21272c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
2128b9c1b51eSKate Stone   if (callee_wrapper_sp) {
21292c1f46dcSZachary Turner     generic = callee_wrapper_sp->GetAsGeneric();
21302c1f46dcSZachary Turner     if (generic)
21312c1f46dcSZachary Turner       old_callee = generic->GetValue();
21322c1f46dcSZachary Turner   }
21332c1f46dcSZachary Turner   void *new_callee = old_callee;
21342c1f46dcSZachary Turner 
21352c1f46dcSZachary Turner   bool ret_val;
2136b9c1b51eSKate Stone   if (python_function_name && *python_function_name) {
21372c1f46dcSZachary Turner     {
2138b9c1b51eSKate Stone       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
2139b9c1b51eSKate Stone                                Locker::NoSTDIN);
21402c1f46dcSZachary Turner       {
21412c1f46dcSZachary Turner         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
21422c1f46dcSZachary Turner 
214305495c5dSJonas Devlieghere         static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
214405495c5dSJonas Devlieghere         Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
214505495c5dSJonas Devlieghere         ret_val = LLDBSwigPythonCallTypeScript(
2146b9c1b51eSKate Stone             python_function_name, GetSessionDictionary().get(), valobj,
2147b9c1b51eSKate Stone             &new_callee, options_sp, retval);
21482c1f46dcSZachary Turner       }
21492c1f46dcSZachary Turner     }
2150b9c1b51eSKate Stone   } else {
21512c1f46dcSZachary Turner     retval.assign("<no function name>");
21522c1f46dcSZachary Turner     return false;
21532c1f46dcSZachary Turner   }
21542c1f46dcSZachary Turner 
21552c1f46dcSZachary Turner   if (new_callee && old_callee != new_callee)
2156796ac80bSJonas Devlieghere     callee_wrapper_sp = std::make_shared<StructuredPythonObject>(new_callee);
21572c1f46dcSZachary Turner 
21582c1f46dcSZachary Turner   return ret_val;
21592c1f46dcSZachary Turner }
21602c1f46dcSZachary Turner 
216163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
2162b9c1b51eSKate Stone     void *baton, StoppointCallbackContext *context, user_id_t break_id,
2163b9c1b51eSKate Stone     user_id_t break_loc_id) {
2164f7e07256SJim Ingham   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
21652c1f46dcSZachary Turner   const char *python_function_name = bp_option_data->script_source.c_str();
21662c1f46dcSZachary Turner 
21672c1f46dcSZachary Turner   if (!context)
21682c1f46dcSZachary Turner     return true;
21692c1f46dcSZachary Turner 
21702c1f46dcSZachary Turner   ExecutionContext exe_ctx(context->exe_ctx_ref);
21712c1f46dcSZachary Turner   Target *target = exe_ctx.GetTargetPtr();
21722c1f46dcSZachary Turner 
21732c1f46dcSZachary Turner   if (!target)
21742c1f46dcSZachary Turner     return true;
21752c1f46dcSZachary Turner 
21762c1f46dcSZachary Turner   Debugger &debugger = target->GetDebugger();
217763dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
2178d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
21792c1f46dcSZachary Turner 
2180d055e3a0SPedro Tammela   if (!python_interpreter)
21812c1f46dcSZachary Turner     return true;
21822c1f46dcSZachary Turner 
2183b9c1b51eSKate Stone   if (python_function_name && python_function_name[0]) {
21842c1f46dcSZachary Turner     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
21852c1f46dcSZachary Turner     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2186b9c1b51eSKate Stone     if (breakpoint_sp) {
2187b9c1b51eSKate Stone       const BreakpointLocationSP bp_loc_sp(
2188b9c1b51eSKate Stone           breakpoint_sp->FindLocationByID(break_loc_id));
21892c1f46dcSZachary Turner 
2190b9c1b51eSKate Stone       if (stop_frame_sp && bp_loc_sp) {
21912c1f46dcSZachary Turner         bool ret_val = true;
21922c1f46dcSZachary Turner         {
2193b9c1b51eSKate Stone           Locker py_lock(python_interpreter, Locker::AcquireLock |
2194b9c1b51eSKate Stone                                                  Locker::InitSession |
2195b9c1b51eSKate Stone                                                  Locker::NoSTDIN);
2196a69bbe02SLawrence D'Anna           Expected<bool> maybe_ret_val =
2197a69bbe02SLawrence D'Anna               LLDBSwigPythonBreakpointCallbackFunction(
2198b9c1b51eSKate Stone                   python_function_name,
2199b9c1b51eSKate Stone                   python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
220082de8df2SPavel Labath                   bp_loc_sp, bp_option_data->m_extra_args);
2201a69bbe02SLawrence D'Anna 
2202a69bbe02SLawrence D'Anna           if (!maybe_ret_val) {
2203a69bbe02SLawrence D'Anna 
2204a69bbe02SLawrence D'Anna             llvm::handleAllErrors(
2205a69bbe02SLawrence D'Anna                 maybe_ret_val.takeError(),
2206a69bbe02SLawrence D'Anna                 [&](PythonException &E) {
2207a69bbe02SLawrence D'Anna                   debugger.GetErrorStream() << E.ReadBacktrace();
2208a69bbe02SLawrence D'Anna                 },
2209a69bbe02SLawrence D'Anna                 [&](const llvm::ErrorInfoBase &E) {
2210a69bbe02SLawrence D'Anna                   debugger.GetErrorStream() << E.message();
2211a69bbe02SLawrence D'Anna                 });
2212a69bbe02SLawrence D'Anna 
2213a69bbe02SLawrence D'Anna           } else {
2214a69bbe02SLawrence D'Anna             ret_val = maybe_ret_val.get();
2215a69bbe02SLawrence D'Anna           }
22162c1f46dcSZachary Turner         }
22172c1f46dcSZachary Turner         return ret_val;
22182c1f46dcSZachary Turner       }
22192c1f46dcSZachary Turner     }
22202c1f46dcSZachary Turner   }
22212c1f46dcSZachary Turner   // We currently always true so we stop in case anything goes wrong when
22222c1f46dcSZachary Turner   // trying to call the script function
22232c1f46dcSZachary Turner   return true;
22242c1f46dcSZachary Turner }
22252c1f46dcSZachary Turner 
222663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
2227b9c1b51eSKate Stone     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2228b9c1b51eSKate Stone   WatchpointOptions::CommandData *wp_option_data =
2229b9c1b51eSKate Stone       (WatchpointOptions::CommandData *)baton;
22302c1f46dcSZachary Turner   const char *python_function_name = wp_option_data->script_source.c_str();
22312c1f46dcSZachary Turner 
22322c1f46dcSZachary Turner   if (!context)
22332c1f46dcSZachary Turner     return true;
22342c1f46dcSZachary Turner 
22352c1f46dcSZachary Turner   ExecutionContext exe_ctx(context->exe_ctx_ref);
22362c1f46dcSZachary Turner   Target *target = exe_ctx.GetTargetPtr();
22372c1f46dcSZachary Turner 
22382c1f46dcSZachary Turner   if (!target)
22392c1f46dcSZachary Turner     return true;
22402c1f46dcSZachary Turner 
22412c1f46dcSZachary Turner   Debugger &debugger = target->GetDebugger();
224263dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
2243d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
22442c1f46dcSZachary Turner 
2245d055e3a0SPedro Tammela   if (!python_interpreter)
22462c1f46dcSZachary Turner     return true;
22472c1f46dcSZachary Turner 
2248b9c1b51eSKate Stone   if (python_function_name && python_function_name[0]) {
22492c1f46dcSZachary Turner     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
22502c1f46dcSZachary Turner     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2251b9c1b51eSKate Stone     if (wp_sp) {
2252b9c1b51eSKate Stone       if (stop_frame_sp && wp_sp) {
22532c1f46dcSZachary Turner         bool ret_val = true;
22542c1f46dcSZachary Turner         {
2255b9c1b51eSKate Stone           Locker py_lock(python_interpreter, Locker::AcquireLock |
2256b9c1b51eSKate Stone                                                  Locker::InitSession |
2257b9c1b51eSKate Stone                                                  Locker::NoSTDIN);
225805495c5dSJonas Devlieghere           ret_val = LLDBSwigPythonWatchpointCallbackFunction(
2259b9c1b51eSKate Stone               python_function_name,
2260b9c1b51eSKate Stone               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
22612c1f46dcSZachary Turner               wp_sp);
22622c1f46dcSZachary Turner         }
22632c1f46dcSZachary Turner         return ret_val;
22642c1f46dcSZachary Turner       }
22652c1f46dcSZachary Turner     }
22662c1f46dcSZachary Turner   }
22672c1f46dcSZachary Turner   // We currently always true so we stop in case anything goes wrong when
22682c1f46dcSZachary Turner   // trying to call the script function
22692c1f46dcSZachary Turner   return true;
22702c1f46dcSZachary Turner }
22712c1f46dcSZachary Turner 
227263dd5d25SJonas Devlieghere size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2273b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
22742c1f46dcSZachary Turner   if (!implementor_sp)
22752c1f46dcSZachary Turner     return 0;
22762c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
22772c1f46dcSZachary Turner   if (!generic)
22782c1f46dcSZachary Turner     return 0;
22799a14adeaSPavel Labath   auto *implementor = static_cast<PyObject *>(generic->GetValue());
22802c1f46dcSZachary Turner   if (!implementor)
22812c1f46dcSZachary Turner     return 0;
22822c1f46dcSZachary Turner 
22832c1f46dcSZachary Turner   size_t ret_val = 0;
22842c1f46dcSZachary Turner 
22852c1f46dcSZachary Turner   {
2286b9c1b51eSKate Stone     Locker py_lock(this,
2287b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
228805495c5dSJonas Devlieghere     ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max);
22892c1f46dcSZachary Turner   }
22902c1f46dcSZachary Turner 
22912c1f46dcSZachary Turner   return ret_val;
22922c1f46dcSZachary Turner }
22932c1f46dcSZachary Turner 
229463dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
2295b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
22962c1f46dcSZachary Turner   if (!implementor_sp)
22972c1f46dcSZachary Turner     return lldb::ValueObjectSP();
22982c1f46dcSZachary Turner 
22992c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
23002c1f46dcSZachary Turner   if (!generic)
23012c1f46dcSZachary Turner     return lldb::ValueObjectSP();
23029a14adeaSPavel Labath   auto *implementor = static_cast<PyObject *>(generic->GetValue());
23032c1f46dcSZachary Turner   if (!implementor)
23042c1f46dcSZachary Turner     return lldb::ValueObjectSP();
23052c1f46dcSZachary Turner 
23062c1f46dcSZachary Turner   lldb::ValueObjectSP ret_val;
23072c1f46dcSZachary Turner   {
2308b9c1b51eSKate Stone     Locker py_lock(this,
2309b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
23109a14adeaSPavel Labath     PyObject *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx);
2311b9c1b51eSKate Stone     if (child_ptr != nullptr && child_ptr != Py_None) {
2312b9c1b51eSKate Stone       lldb::SBValue *sb_value_ptr =
231305495c5dSJonas Devlieghere           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
23142c1f46dcSZachary Turner       if (sb_value_ptr == nullptr)
23152c1f46dcSZachary Turner         Py_XDECREF(child_ptr);
23162c1f46dcSZachary Turner       else
231705495c5dSJonas Devlieghere         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2318b9c1b51eSKate Stone     } else {
23192c1f46dcSZachary Turner       Py_XDECREF(child_ptr);
23202c1f46dcSZachary Turner     }
23212c1f46dcSZachary Turner   }
23222c1f46dcSZachary Turner 
23232c1f46dcSZachary Turner   return ret_val;
23242c1f46dcSZachary Turner }
23252c1f46dcSZachary Turner 
232663dd5d25SJonas Devlieghere int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2327b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
23282c1f46dcSZachary Turner   if (!implementor_sp)
23292c1f46dcSZachary Turner     return UINT32_MAX;
23302c1f46dcSZachary Turner 
23312c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
23322c1f46dcSZachary Turner   if (!generic)
23332c1f46dcSZachary Turner     return UINT32_MAX;
23349a14adeaSPavel Labath   auto *implementor = static_cast<PyObject *>(generic->GetValue());
23352c1f46dcSZachary Turner   if (!implementor)
23362c1f46dcSZachary Turner     return UINT32_MAX;
23372c1f46dcSZachary Turner 
23382c1f46dcSZachary Turner   int ret_val = UINT32_MAX;
23392c1f46dcSZachary Turner 
23402c1f46dcSZachary Turner   {
2341b9c1b51eSKate Stone     Locker py_lock(this,
2342b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
234305495c5dSJonas Devlieghere     ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
23442c1f46dcSZachary Turner   }
23452c1f46dcSZachary Turner 
23462c1f46dcSZachary Turner   return ret_val;
23472c1f46dcSZachary Turner }
23482c1f46dcSZachary Turner 
234963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2350b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
23512c1f46dcSZachary Turner   bool ret_val = false;
23522c1f46dcSZachary Turner 
23532c1f46dcSZachary Turner   if (!implementor_sp)
23542c1f46dcSZachary Turner     return ret_val;
23552c1f46dcSZachary Turner 
23562c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
23572c1f46dcSZachary Turner   if (!generic)
23582c1f46dcSZachary Turner     return ret_val;
23599a14adeaSPavel Labath   auto *implementor = static_cast<PyObject *>(generic->GetValue());
23602c1f46dcSZachary Turner   if (!implementor)
23612c1f46dcSZachary Turner     return ret_val;
23622c1f46dcSZachary Turner 
23632c1f46dcSZachary Turner   {
2364b9c1b51eSKate Stone     Locker py_lock(this,
2365b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
236605495c5dSJonas Devlieghere     ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor);
23672c1f46dcSZachary Turner   }
23682c1f46dcSZachary Turner 
23692c1f46dcSZachary Turner   return ret_val;
23702c1f46dcSZachary Turner }
23712c1f46dcSZachary Turner 
237263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2373b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
23742c1f46dcSZachary Turner   bool ret_val = false;
23752c1f46dcSZachary Turner 
23762c1f46dcSZachary Turner   if (!implementor_sp)
23772c1f46dcSZachary Turner     return ret_val;
23782c1f46dcSZachary Turner 
23792c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
23802c1f46dcSZachary Turner   if (!generic)
23812c1f46dcSZachary Turner     return ret_val;
23829a14adeaSPavel Labath   auto *implementor = static_cast<PyObject *>(generic->GetValue());
23832c1f46dcSZachary Turner   if (!implementor)
23842c1f46dcSZachary Turner     return ret_val;
23852c1f46dcSZachary Turner 
23862c1f46dcSZachary Turner   {
2387b9c1b51eSKate Stone     Locker py_lock(this,
2388b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
238905495c5dSJonas Devlieghere     ret_val =
239005495c5dSJonas Devlieghere         LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor);
23912c1f46dcSZachary Turner   }
23922c1f46dcSZachary Turner 
23932c1f46dcSZachary Turner   return ret_val;
23942c1f46dcSZachary Turner }
23952c1f46dcSZachary Turner 
239663dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
2397b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
23982c1f46dcSZachary Turner   lldb::ValueObjectSP ret_val(nullptr);
23992c1f46dcSZachary Turner 
24002c1f46dcSZachary Turner   if (!implementor_sp)
24012c1f46dcSZachary Turner     return ret_val;
24022c1f46dcSZachary Turner 
24032c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24042c1f46dcSZachary Turner   if (!generic)
24052c1f46dcSZachary Turner     return ret_val;
24069a14adeaSPavel Labath   auto *implementor = static_cast<PyObject *>(generic->GetValue());
24072c1f46dcSZachary Turner   if (!implementor)
24082c1f46dcSZachary Turner     return ret_val;
24092c1f46dcSZachary Turner 
24102c1f46dcSZachary Turner   {
2411b9c1b51eSKate Stone     Locker py_lock(this,
2412b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
24139a14adeaSPavel Labath     PyObject *child_ptr =
24149a14adeaSPavel Labath         LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2415b9c1b51eSKate Stone     if (child_ptr != nullptr && child_ptr != Py_None) {
2416b9c1b51eSKate Stone       lldb::SBValue *sb_value_ptr =
241705495c5dSJonas Devlieghere           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
24182c1f46dcSZachary Turner       if (sb_value_ptr == nullptr)
24192c1f46dcSZachary Turner         Py_XDECREF(child_ptr);
24202c1f46dcSZachary Turner       else
242105495c5dSJonas Devlieghere         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2422b9c1b51eSKate Stone     } else {
24232c1f46dcSZachary Turner       Py_XDECREF(child_ptr);
24242c1f46dcSZachary Turner     }
24252c1f46dcSZachary Turner   }
24262c1f46dcSZachary Turner 
24272c1f46dcSZachary Turner   return ret_val;
24282c1f46dcSZachary Turner }
24292c1f46dcSZachary Turner 
243063dd5d25SJonas Devlieghere ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2431b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
2432b9c1b51eSKate Stone   Locker py_lock(this,
2433b9c1b51eSKate Stone                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
24346eec8d6cSEnrico Granata 
24356eec8d6cSEnrico Granata   static char callee_name[] = "get_type_name";
24366eec8d6cSEnrico Granata 
24376eec8d6cSEnrico Granata   ConstString ret_val;
24386eec8d6cSEnrico Granata   bool got_string = false;
24396eec8d6cSEnrico Granata   std::string buffer;
24406eec8d6cSEnrico Granata 
24416eec8d6cSEnrico Granata   if (!implementor_sp)
24426eec8d6cSEnrico Granata     return ret_val;
24436eec8d6cSEnrico Granata 
24446eec8d6cSEnrico Granata   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24456eec8d6cSEnrico Granata   if (!generic)
24466eec8d6cSEnrico Granata     return ret_val;
2447b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
2448b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
24496eec8d6cSEnrico Granata   if (!implementor.IsAllocated())
24506eec8d6cSEnrico Granata     return ret_val;
24516eec8d6cSEnrico Granata 
2452b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
2453b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
24546eec8d6cSEnrico Granata 
24556eec8d6cSEnrico Granata   if (PyErr_Occurred())
24566eec8d6cSEnrico Granata     PyErr_Clear();
24576eec8d6cSEnrico Granata 
24586eec8d6cSEnrico Granata   if (!pmeth.IsAllocated())
24596eec8d6cSEnrico Granata     return ret_val;
24606eec8d6cSEnrico Granata 
2461b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
24626eec8d6cSEnrico Granata     if (PyErr_Occurred())
24636eec8d6cSEnrico Granata       PyErr_Clear();
24646eec8d6cSEnrico Granata     return ret_val;
24656eec8d6cSEnrico Granata   }
24666eec8d6cSEnrico Granata 
24676eec8d6cSEnrico Granata   if (PyErr_Occurred())
24686eec8d6cSEnrico Granata     PyErr_Clear();
24696eec8d6cSEnrico Granata 
24706eec8d6cSEnrico Granata   // right now we know this function exists and is callable..
2471b9c1b51eSKate Stone   PythonObject py_return(
2472b9c1b51eSKate Stone       PyRefType::Owned,
2473b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
24746eec8d6cSEnrico Granata 
24756eec8d6cSEnrico Granata   // if it fails, print the error but otherwise go on
2476b9c1b51eSKate Stone   if (PyErr_Occurred()) {
24776eec8d6cSEnrico Granata     PyErr_Print();
24786eec8d6cSEnrico Granata     PyErr_Clear();
24796eec8d6cSEnrico Granata   }
24806eec8d6cSEnrico Granata 
2481b9c1b51eSKate Stone   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
24826eec8d6cSEnrico Granata     PythonString py_string(PyRefType::Borrowed, py_return.get());
24836eec8d6cSEnrico Granata     llvm::StringRef return_data(py_string.GetString());
2484b9c1b51eSKate Stone     if (!return_data.empty()) {
24856eec8d6cSEnrico Granata       buffer.assign(return_data.data(), return_data.size());
24866eec8d6cSEnrico Granata       got_string = true;
24876eec8d6cSEnrico Granata     }
24886eec8d6cSEnrico Granata   }
24896eec8d6cSEnrico Granata 
24906eec8d6cSEnrico Granata   if (got_string)
24916eec8d6cSEnrico Granata     ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
24926eec8d6cSEnrico Granata 
24936eec8d6cSEnrico Granata   return ret_val;
24946eec8d6cSEnrico Granata }
24956eec8d6cSEnrico Granata 
249663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
249763dd5d25SJonas Devlieghere     const char *impl_function, Process *process, std::string &output,
249897206d57SZachary Turner     Status &error) {
24992c1f46dcSZachary Turner   bool ret_val;
2500b9c1b51eSKate Stone   if (!process) {
25012c1f46dcSZachary Turner     error.SetErrorString("no process");
25022c1f46dcSZachary Turner     return false;
25032c1f46dcSZachary Turner   }
2504b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
25052c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
25062c1f46dcSZachary Turner     return false;
25072c1f46dcSZachary Turner   }
250805495c5dSJonas Devlieghere 
25092c1f46dcSZachary Turner   {
2510b9c1b51eSKate Stone     Locker py_lock(this,
2511b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
251205495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordProcess(
25137f09ab08SPavel Labath         impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
25147f09ab08SPavel Labath         output);
25152c1f46dcSZachary Turner     if (!ret_val)
25162c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
25172c1f46dcSZachary Turner   }
25182c1f46dcSZachary Turner   return ret_val;
25192c1f46dcSZachary Turner }
25202c1f46dcSZachary Turner 
252163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
252263dd5d25SJonas Devlieghere     const char *impl_function, Thread *thread, std::string &output,
252397206d57SZachary Turner     Status &error) {
2524b9c1b51eSKate Stone   if (!thread) {
25252c1f46dcSZachary Turner     error.SetErrorString("no thread");
25262c1f46dcSZachary Turner     return false;
25272c1f46dcSZachary Turner   }
2528b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
25292c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
25302c1f46dcSZachary Turner     return false;
25312c1f46dcSZachary Turner   }
253205495c5dSJonas Devlieghere 
2533b9c1b51eSKate Stone   Locker py_lock(this,
2534b9c1b51eSKate Stone                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2535*7406d236SPavel Labath   if (llvm::Optional<std::string> result = LLDBSWIGPythonRunScriptKeywordThread(
2536*7406d236SPavel Labath           impl_function, m_dictionary_name.c_str(),
2537*7406d236SPavel Labath           thread->shared_from_this())) {
2538*7406d236SPavel Labath     output = std::move(*result);
2539*7406d236SPavel Labath     return true;
25402c1f46dcSZachary Turner   }
2541*7406d236SPavel Labath   error.SetErrorString("python script evaluation failed");
2542*7406d236SPavel Labath   return false;
25432c1f46dcSZachary Turner }
25442c1f46dcSZachary Turner 
254563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
254663dd5d25SJonas Devlieghere     const char *impl_function, Target *target, std::string &output,
254797206d57SZachary Turner     Status &error) {
25482c1f46dcSZachary Turner   bool ret_val;
2549b9c1b51eSKate Stone   if (!target) {
25502c1f46dcSZachary Turner     error.SetErrorString("no thread");
25512c1f46dcSZachary Turner     return false;
25522c1f46dcSZachary Turner   }
2553b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
25542c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
25552c1f46dcSZachary Turner     return false;
25562c1f46dcSZachary Turner   }
255705495c5dSJonas Devlieghere 
25582c1f46dcSZachary Turner   {
25592c1f46dcSZachary Turner     TargetSP target_sp(target->shared_from_this());
2560b9c1b51eSKate Stone     Locker py_lock(this,
2561b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
256205495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordTarget(
2563b9c1b51eSKate Stone         impl_function, m_dictionary_name.c_str(), target_sp, output);
25642c1f46dcSZachary Turner     if (!ret_val)
25652c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
25662c1f46dcSZachary Turner   }
25672c1f46dcSZachary Turner   return ret_val;
25682c1f46dcSZachary Turner }
25692c1f46dcSZachary Turner 
257063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
257163dd5d25SJonas Devlieghere     const char *impl_function, StackFrame *frame, std::string &output,
257297206d57SZachary Turner     Status &error) {
2573b9c1b51eSKate Stone   if (!frame) {
25742c1f46dcSZachary Turner     error.SetErrorString("no frame");
25752c1f46dcSZachary Turner     return false;
25762c1f46dcSZachary Turner   }
2577b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
25782c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
25792c1f46dcSZachary Turner     return false;
25802c1f46dcSZachary Turner   }
258105495c5dSJonas Devlieghere 
2582b9c1b51eSKate Stone   Locker py_lock(this,
2583b9c1b51eSKate Stone                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2584*7406d236SPavel Labath   if (llvm::Optional<std::string> result = LLDBSWIGPythonRunScriptKeywordFrame(
2585*7406d236SPavel Labath           impl_function, m_dictionary_name.c_str(),
2586*7406d236SPavel Labath           frame->shared_from_this())) {
2587*7406d236SPavel Labath     output = std::move(*result);
2588*7406d236SPavel Labath     return true;
25892c1f46dcSZachary Turner   }
2590*7406d236SPavel Labath   error.SetErrorString("python script evaluation failed");
2591*7406d236SPavel Labath   return false;
25922c1f46dcSZachary Turner }
25932c1f46dcSZachary Turner 
259463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
259563dd5d25SJonas Devlieghere     const char *impl_function, ValueObject *value, std::string &output,
259697206d57SZachary Turner     Status &error) {
25972c1f46dcSZachary Turner   bool ret_val;
2598b9c1b51eSKate Stone   if (!value) {
25992c1f46dcSZachary Turner     error.SetErrorString("no value");
26002c1f46dcSZachary Turner     return false;
26012c1f46dcSZachary Turner   }
2602b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
26032c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
26042c1f46dcSZachary Turner     return false;
26052c1f46dcSZachary Turner   }
260605495c5dSJonas Devlieghere 
26072c1f46dcSZachary Turner   {
2608b9c1b51eSKate Stone     Locker py_lock(this,
2609b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
261005495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordValue(
26117f09ab08SPavel Labath         impl_function, m_dictionary_name.c_str(), value->GetSP(), output);
26122c1f46dcSZachary Turner     if (!ret_val)
26132c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
26142c1f46dcSZachary Turner   }
26152c1f46dcSZachary Turner   return ret_val;
26162c1f46dcSZachary Turner }
26172c1f46dcSZachary Turner 
2618b9c1b51eSKate Stone uint64_t replace_all(std::string &str, const std::string &oldStr,
2619b9c1b51eSKate Stone                      const std::string &newStr) {
26202c1f46dcSZachary Turner   size_t pos = 0;
26212c1f46dcSZachary Turner   uint64_t matches = 0;
2622b9c1b51eSKate Stone   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
26232c1f46dcSZachary Turner     matches++;
26242c1f46dcSZachary Turner     str.replace(pos, oldStr.length(), newStr);
26252c1f46dcSZachary Turner     pos += newStr.length();
26262c1f46dcSZachary Turner   }
26272c1f46dcSZachary Turner   return matches;
26282c1f46dcSZachary Turner }
26292c1f46dcSZachary Turner 
263063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2631f9517353SJonas Devlieghere     const char *pathname, const LoadScriptOptions &options,
2632f9517353SJonas Devlieghere     lldb_private::Status &error, StructuredData::ObjectSP *module_sp,
2633f9517353SJonas Devlieghere     FileSpec extra_search_dir) {
26343b33b416SJonas Devlieghere   namespace fs = llvm::sys::fs;
263500bb397bSJonas Devlieghere   namespace path = llvm::sys::path;
26363b33b416SJonas Devlieghere 
2637f9517353SJonas Devlieghere   ExecuteScriptOptions exc_options = ExecuteScriptOptions()
2638f9517353SJonas Devlieghere                                          .SetEnableIO(!options.GetSilent())
2639f9517353SJonas Devlieghere                                          .SetSetLLDBGlobals(false);
2640f9517353SJonas Devlieghere 
2641b9c1b51eSKate Stone   if (!pathname || !pathname[0]) {
26422c1f46dcSZachary Turner     error.SetErrorString("invalid pathname");
26432c1f46dcSZachary Turner     return false;
26442c1f46dcSZachary Turner   }
26452c1f46dcSZachary Turner 
2646f9517353SJonas Devlieghere   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2647f9517353SJonas Devlieghere       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2648f9517353SJonas Devlieghere           exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2649f9517353SJonas Devlieghere 
2650f9517353SJonas Devlieghere   if (!io_redirect_or_error) {
2651f9517353SJonas Devlieghere     error = io_redirect_or_error.takeError();
2652f9517353SJonas Devlieghere     return false;
2653f9517353SJonas Devlieghere   }
2654f9517353SJonas Devlieghere 
2655f9517353SJonas Devlieghere   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
26562c1f46dcSZachary Turner 
2657f9f36097SAdrian McCarthy   // Before executing Python code, lock the GIL.
265820b52c33SJonas Devlieghere   Locker py_lock(this,
265920b52c33SJonas Devlieghere                  Locker::AcquireLock |
2660f9517353SJonas Devlieghere                      (options.GetInitSession() ? Locker::InitSession : 0) |
2661f9517353SJonas Devlieghere                      Locker::NoSTDIN,
2662b9c1b51eSKate Stone                  Locker::FreeAcquiredLock |
2663f9517353SJonas Devlieghere                      (options.GetInitSession() ? Locker::TearDownSession : 0),
2664f9517353SJonas Devlieghere                  io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2665f9517353SJonas Devlieghere                  io_redirect.GetErrorFile());
26662c1f46dcSZachary Turner 
2667f9517353SJonas Devlieghere   auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
266800bb397bSJonas Devlieghere     if (directory.empty()) {
266900bb397bSJonas Devlieghere       return llvm::make_error<llvm::StringError>(
267000bb397bSJonas Devlieghere           "invalid directory name", llvm::inconvertibleErrorCode());
267142a9da7bSStefan Granitz     }
267242a9da7bSStefan Granitz 
2673f9f36097SAdrian McCarthy     replace_all(directory, "\\", "\\\\");
26742c1f46dcSZachary Turner     replace_all(directory, "'", "\\'");
26752c1f46dcSZachary Turner 
267600bb397bSJonas Devlieghere     // Make sure that Python has "directory" in the search path.
26772c1f46dcSZachary Turner     StreamString command_stream;
2678b9c1b51eSKate Stone     command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
2679b9c1b51eSKate Stone                           "sys.path.insert(1,'%s');\n\n",
2680b9c1b51eSKate Stone                           directory.c_str(), directory.c_str());
2681b9c1b51eSKate Stone     bool syspath_retval =
2682f9517353SJonas Devlieghere         ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
2683b9c1b51eSKate Stone     if (!syspath_retval) {
268400bb397bSJonas Devlieghere       return llvm::make_error<llvm::StringError>(
268500bb397bSJonas Devlieghere           "Python sys.path handling failed", llvm::inconvertibleErrorCode());
26862c1f46dcSZachary Turner     }
26872c1f46dcSZachary Turner 
268800bb397bSJonas Devlieghere     return llvm::Error::success();
268900bb397bSJonas Devlieghere   };
269000bb397bSJonas Devlieghere 
269100bb397bSJonas Devlieghere   std::string module_name(pathname);
2692d6e80578SJonas Devlieghere   bool possible_package = false;
269300bb397bSJonas Devlieghere 
269400bb397bSJonas Devlieghere   if (extra_search_dir) {
269500bb397bSJonas Devlieghere     if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
269600bb397bSJonas Devlieghere       error = std::move(e);
269700bb397bSJonas Devlieghere       return false;
269800bb397bSJonas Devlieghere     }
269900bb397bSJonas Devlieghere   } else {
270000bb397bSJonas Devlieghere     FileSpec module_file(pathname);
270100bb397bSJonas Devlieghere     FileSystem::Instance().Resolve(module_file);
270200bb397bSJonas Devlieghere     FileSystem::Instance().Collect(module_file);
270300bb397bSJonas Devlieghere 
270400bb397bSJonas Devlieghere     fs::file_status st;
270500bb397bSJonas Devlieghere     std::error_code ec = status(module_file.GetPath(), st);
270600bb397bSJonas Devlieghere 
270700bb397bSJonas Devlieghere     if (ec || st.type() == fs::file_type::status_error ||
270800bb397bSJonas Devlieghere         st.type() == fs::file_type::type_unknown ||
270900bb397bSJonas Devlieghere         st.type() == fs::file_type::file_not_found) {
271000bb397bSJonas Devlieghere       // if not a valid file of any sort, check if it might be a filename still
271100bb397bSJonas Devlieghere       // dot can't be used but / and \ can, and if either is found, reject
271200bb397bSJonas Devlieghere       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
271300bb397bSJonas Devlieghere         error.SetErrorString("invalid pathname");
271400bb397bSJonas Devlieghere         return false;
271500bb397bSJonas Devlieghere       }
271600bb397bSJonas Devlieghere       // Not a filename, probably a package of some sort, let it go through.
2717d6e80578SJonas Devlieghere       possible_package = true;
271800bb397bSJonas Devlieghere     } else if (is_directory(st) || is_regular_file(st)) {
271900bb397bSJonas Devlieghere       if (module_file.GetDirectory().IsEmpty()) {
272000bb397bSJonas Devlieghere         error.SetErrorString("invalid directory name");
272100bb397bSJonas Devlieghere         return false;
272200bb397bSJonas Devlieghere       }
272300bb397bSJonas Devlieghere       if (llvm::Error e =
272400bb397bSJonas Devlieghere               ExtendSysPath(module_file.GetDirectory().GetCString())) {
272500bb397bSJonas Devlieghere         error = std::move(e);
272600bb397bSJonas Devlieghere         return false;
272700bb397bSJonas Devlieghere       }
272800bb397bSJonas Devlieghere       module_name = module_file.GetFilename().GetCString();
2729b9c1b51eSKate Stone     } else {
27302c1f46dcSZachary Turner       error.SetErrorString("no known way to import this module specification");
27312c1f46dcSZachary Turner       return false;
27322c1f46dcSZachary Turner     }
273300bb397bSJonas Devlieghere   }
27342c1f46dcSZachary Turner 
27351197ee35SJonas Devlieghere   // Strip .py or .pyc extension
273600bb397bSJonas Devlieghere   llvm::StringRef extension = llvm::sys::path::extension(module_name);
27371197ee35SJonas Devlieghere   if (!extension.empty()) {
27381197ee35SJonas Devlieghere     if (extension == ".py")
273900bb397bSJonas Devlieghere       module_name.resize(module_name.length() - 3);
27401197ee35SJonas Devlieghere     else if (extension == ".pyc")
274100bb397bSJonas Devlieghere       module_name.resize(module_name.length() - 4);
27421197ee35SJonas Devlieghere   }
27431197ee35SJonas Devlieghere 
2744d6e80578SJonas Devlieghere   if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2745d6e80578SJonas Devlieghere     error.SetErrorStringWithFormat(
2746d6e80578SJonas Devlieghere         "Python does not allow dots in module names: %s", module_name.c_str());
2747d6e80578SJonas Devlieghere     return false;
2748d6e80578SJonas Devlieghere   }
2749d6e80578SJonas Devlieghere 
2750d6e80578SJonas Devlieghere   if (module_name.find('-') != llvm::StringRef::npos) {
2751d6e80578SJonas Devlieghere     error.SetErrorStringWithFormat(
2752d6e80578SJonas Devlieghere         "Python discourages dashes in module names: %s", module_name.c_str());
2753d6e80578SJonas Devlieghere     return false;
2754d6e80578SJonas Devlieghere   }
2755d6e80578SJonas Devlieghere 
2756f9517353SJonas Devlieghere   // Check if the module is already imported.
275700bb397bSJonas Devlieghere   StreamString command_stream;
27582c1f46dcSZachary Turner   command_stream.Clear();
275900bb397bSJonas Devlieghere   command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
27602c1f46dcSZachary Turner   bool does_contain = false;
2761f9517353SJonas Devlieghere   // This call will succeed if the module was ever imported in any Debugger in
2762f9517353SJonas Devlieghere   // the lifetime of the process in which this LLDB framework is living.
2763f9517353SJonas Devlieghere   const bool does_contain_executed = ExecuteOneLineWithReturn(
2764b9c1b51eSKate Stone       command_stream.GetData(),
2765f9517353SJonas Devlieghere       ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options);
2766f9517353SJonas Devlieghere 
2767f9517353SJonas Devlieghere   const bool was_imported_globally = does_contain_executed && does_contain;
2768612384f6SJonas Devlieghere   const bool was_imported_locally =
2769612384f6SJonas Devlieghere       GetSessionDictionary()
277000bb397bSJonas Devlieghere           .GetItemForKey(PythonString(module_name))
2771b9c1b51eSKate Stone           .IsAllocated();
27722c1f46dcSZachary Turner 
27732c1f46dcSZachary Turner   // now actually do the import
27742c1f46dcSZachary Turner   command_stream.Clear();
27752c1f46dcSZachary Turner 
2776612384f6SJonas Devlieghere   if (was_imported_globally || was_imported_locally) {
27772c1f46dcSZachary Turner     if (!was_imported_locally)
277800bb397bSJonas Devlieghere       command_stream.Printf("import %s ; reload_module(%s)",
277900bb397bSJonas Devlieghere                             module_name.c_str(), module_name.c_str());
27802c1f46dcSZachary Turner     else
278100bb397bSJonas Devlieghere       command_stream.Printf("reload_module(%s)", module_name.c_str());
2782b9c1b51eSKate Stone   } else
278300bb397bSJonas Devlieghere     command_stream.Printf("import %s", module_name.c_str());
27842c1f46dcSZachary Turner 
2785f9517353SJonas Devlieghere   error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
27862c1f46dcSZachary Turner   if (error.Fail())
27872c1f46dcSZachary Turner     return false;
27882c1f46dcSZachary Turner 
27892c1f46dcSZachary Turner   // if we are here, everything worked
27902c1f46dcSZachary Turner   // call __lldb_init_module(debugger,dict)
279100bb397bSJonas Devlieghere   if (!LLDBSwigPythonCallModuleInit(module_name.c_str(),
2792*7406d236SPavel Labath                                     m_dictionary_name.c_str(),
2793*7406d236SPavel Labath                                     m_debugger.shared_from_this())) {
27942c1f46dcSZachary Turner     error.SetErrorString("calling __lldb_init_module failed");
27952c1f46dcSZachary Turner     return false;
27962c1f46dcSZachary Turner   }
27972c1f46dcSZachary Turner 
2798b9c1b51eSKate Stone   if (module_sp) {
27992c1f46dcSZachary Turner     // everything went just great, now set the module object
28002c1f46dcSZachary Turner     command_stream.Clear();
280100bb397bSJonas Devlieghere     command_stream.Printf("%s", module_name.c_str());
28022c1f46dcSZachary Turner     void *module_pyobj = nullptr;
2803b9c1b51eSKate Stone     if (ExecuteOneLineWithReturn(
2804b9c1b51eSKate Stone             command_stream.GetData(),
2805f9517353SJonas Devlieghere             ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2806f9517353SJonas Devlieghere             exc_options) &&
2807b9c1b51eSKate Stone         module_pyobj)
2808796ac80bSJonas Devlieghere       *module_sp = std::make_shared<StructuredPythonObject>(module_pyobj);
28092c1f46dcSZachary Turner   }
28102c1f46dcSZachary Turner 
28112c1f46dcSZachary Turner   return true;
28122c1f46dcSZachary Turner }
28132c1f46dcSZachary Turner 
281463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
28152c1f46dcSZachary Turner   if (!word || !word[0])
28162c1f46dcSZachary Turner     return false;
28172c1f46dcSZachary Turner 
28182c1f46dcSZachary Turner   llvm::StringRef word_sr(word);
28192c1f46dcSZachary Turner 
282005097246SAdrian Prantl   // filter out a few characters that would just confuse us and that are
282105097246SAdrian Prantl   // clearly not keyword material anyway
282210b113e8SJonas Devlieghere   if (word_sr.find('"') != llvm::StringRef::npos ||
282310b113e8SJonas Devlieghere       word_sr.find('\'') != llvm::StringRef::npos)
28242c1f46dcSZachary Turner     return false;
28252c1f46dcSZachary Turner 
28262c1f46dcSZachary Turner   StreamString command_stream;
28272c1f46dcSZachary Turner   command_stream.Printf("keyword.iskeyword('%s')", word);
28282c1f46dcSZachary Turner   bool result;
28292c1f46dcSZachary Turner   ExecuteScriptOptions options;
28302c1f46dcSZachary Turner   options.SetEnableIO(false);
28312c1f46dcSZachary Turner   options.SetMaskoutErrors(true);
28322c1f46dcSZachary Turner   options.SetSetLLDBGlobals(false);
2833b9c1b51eSKate Stone   if (ExecuteOneLineWithReturn(command_stream.GetData(),
2834b9c1b51eSKate Stone                                ScriptInterpreter::eScriptReturnTypeBool,
2835b9c1b51eSKate Stone                                &result, options))
28362c1f46dcSZachary Turner     return result;
28372c1f46dcSZachary Turner   return false;
28382c1f46dcSZachary Turner }
28392c1f46dcSZachary Turner 
284063dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2841b9c1b51eSKate Stone     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2842b9c1b51eSKate Stone     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2843b9c1b51eSKate Stone       m_old_asynch(debugger_sp->GetAsyncExecution()) {
28442c1f46dcSZachary Turner   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
28452c1f46dcSZachary Turner     m_debugger_sp->SetAsyncExecution(false);
28462c1f46dcSZachary Turner   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
28472c1f46dcSZachary Turner     m_debugger_sp->SetAsyncExecution(true);
28482c1f46dcSZachary Turner }
28492c1f46dcSZachary Turner 
285063dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
28512c1f46dcSZachary Turner   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
28522c1f46dcSZachary Turner     m_debugger_sp->SetAsyncExecution(m_old_asynch);
28532c1f46dcSZachary Turner }
28542c1f46dcSZachary Turner 
285563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
28564d51a902SRaphael Isemann     const char *impl_function, llvm::StringRef args,
28572c1f46dcSZachary Turner     ScriptedCommandSynchronicity synchronicity,
285897206d57SZachary Turner     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2859b9c1b51eSKate Stone     const lldb_private::ExecutionContext &exe_ctx) {
2860b9c1b51eSKate Stone   if (!impl_function) {
28612c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
28622c1f46dcSZachary Turner     return false;
28632c1f46dcSZachary Turner   }
28642c1f46dcSZachary Turner 
28658d1fb843SJonas Devlieghere   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
28662c1f46dcSZachary Turner   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
28672c1f46dcSZachary Turner 
2868b9c1b51eSKate Stone   if (!debugger_sp.get()) {
28692c1f46dcSZachary Turner     error.SetErrorString("invalid Debugger pointer");
28702c1f46dcSZachary Turner     return false;
28712c1f46dcSZachary Turner   }
28722c1f46dcSZachary Turner 
28732c1f46dcSZachary Turner   bool ret_val = false;
28742c1f46dcSZachary Turner 
28752c1f46dcSZachary Turner   std::string err_msg;
28762c1f46dcSZachary Turner 
28772c1f46dcSZachary Turner   {
28782c1f46dcSZachary Turner     Locker py_lock(this,
2879b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession |
2880b9c1b51eSKate Stone                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
28812c1f46dcSZachary Turner                    Locker::FreeLock | Locker::TearDownSession);
28822c1f46dcSZachary Turner 
2883b9c1b51eSKate Stone     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
28842c1f46dcSZachary Turner 
28854d51a902SRaphael Isemann     std::string args_str = args.str();
288605495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCallCommand(
288705495c5dSJonas Devlieghere         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
288805495c5dSJonas Devlieghere         cmd_retobj, exe_ctx_ref_sp);
28892c1f46dcSZachary Turner   }
28902c1f46dcSZachary Turner 
28912c1f46dcSZachary Turner   if (!ret_val)
28922c1f46dcSZachary Turner     error.SetErrorString("unable to execute script function");
28932c1f46dcSZachary Turner   else
28942c1f46dcSZachary Turner     error.Clear();
28952c1f46dcSZachary Turner 
28962c1f46dcSZachary Turner   return ret_val;
28972c1f46dcSZachary Turner }
28982c1f46dcSZachary Turner 
289963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
29004d51a902SRaphael Isemann     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
29012c1f46dcSZachary Turner     ScriptedCommandSynchronicity synchronicity,
290297206d57SZachary Turner     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2903b9c1b51eSKate Stone     const lldb_private::ExecutionContext &exe_ctx) {
2904b9c1b51eSKate Stone   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
29052c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
29062c1f46dcSZachary Turner     return false;
29072c1f46dcSZachary Turner   }
29082c1f46dcSZachary Turner 
29098d1fb843SJonas Devlieghere   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
29102c1f46dcSZachary Turner   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
29112c1f46dcSZachary Turner 
2912b9c1b51eSKate Stone   if (!debugger_sp.get()) {
29132c1f46dcSZachary Turner     error.SetErrorString("invalid Debugger pointer");
29142c1f46dcSZachary Turner     return false;
29152c1f46dcSZachary Turner   }
29162c1f46dcSZachary Turner 
29172c1f46dcSZachary Turner   bool ret_val = false;
29182c1f46dcSZachary Turner 
29192c1f46dcSZachary Turner   std::string err_msg;
29202c1f46dcSZachary Turner 
29212c1f46dcSZachary Turner   {
29222c1f46dcSZachary Turner     Locker py_lock(this,
2923b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession |
2924b9c1b51eSKate Stone                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
29252c1f46dcSZachary Turner                    Locker::FreeLock | Locker::TearDownSession);
29262c1f46dcSZachary Turner 
2927b9c1b51eSKate Stone     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
29282c1f46dcSZachary Turner 
29294d51a902SRaphael Isemann     std::string args_str = args.str();
29309a14adeaSPavel Labath     ret_val = LLDBSwigPythonCallCommandObject(
29319a14adeaSPavel Labath         static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
29329a14adeaSPavel Labath         args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
29332c1f46dcSZachary Turner   }
29342c1f46dcSZachary Turner 
29352c1f46dcSZachary Turner   if (!ret_val)
29362c1f46dcSZachary Turner     error.SetErrorString("unable to execute script function");
29372c1f46dcSZachary Turner   else
29382c1f46dcSZachary Turner     error.Clear();
29392c1f46dcSZachary Turner 
29402c1f46dcSZachary Turner   return ret_val;
29412c1f46dcSZachary Turner }
29422c1f46dcSZachary Turner 
294393571c3cSJonas Devlieghere /// In Python, a special attribute __doc__ contains the docstring for an object
294493571c3cSJonas Devlieghere /// (function, method, class, ...) if any is defined Otherwise, the attribute's
294593571c3cSJonas Devlieghere /// value is None.
294663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
2947b9c1b51eSKate Stone                                                           std::string &dest) {
29482c1f46dcSZachary Turner   dest.clear();
294993571c3cSJonas Devlieghere 
29502c1f46dcSZachary Turner   if (!item || !*item)
29512c1f46dcSZachary Turner     return false;
295293571c3cSJonas Devlieghere 
29532c1f46dcSZachary Turner   std::string command(item);
29542c1f46dcSZachary Turner   command += ".__doc__";
29552c1f46dcSZachary Turner 
295693571c3cSJonas Devlieghere   // Python is going to point this to valid data if ExecuteOneLineWithReturn
295793571c3cSJonas Devlieghere   // returns successfully.
295893571c3cSJonas Devlieghere   char *result_ptr = nullptr;
29592c1f46dcSZachary Turner 
2960b9c1b51eSKate Stone   if (ExecuteOneLineWithReturn(
296193571c3cSJonas Devlieghere           command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
29622c1f46dcSZachary Turner           &result_ptr,
2963fd2433e1SJonas Devlieghere           ExecuteScriptOptions().SetEnableIO(false))) {
29642c1f46dcSZachary Turner     if (result_ptr)
29652c1f46dcSZachary Turner       dest.assign(result_ptr);
29662c1f46dcSZachary Turner     return true;
29672c1f46dcSZachary Turner   }
296893571c3cSJonas Devlieghere 
296993571c3cSJonas Devlieghere   StreamString str_stream;
297093571c3cSJonas Devlieghere   str_stream << "Function " << item
297193571c3cSJonas Devlieghere              << " was not found. Containing module might be missing.";
297293571c3cSJonas Devlieghere   dest = std::string(str_stream.GetString());
297393571c3cSJonas Devlieghere 
297493571c3cSJonas Devlieghere   return false;
29752c1f46dcSZachary Turner }
29762c1f46dcSZachary Turner 
297763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
2978b9c1b51eSKate Stone     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
29792c1f46dcSZachary Turner   dest.clear();
29802c1f46dcSZachary Turner 
2981b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
29822c1f46dcSZachary Turner 
29832c1f46dcSZachary Turner   static char callee_name[] = "get_short_help";
29842c1f46dcSZachary Turner 
29852c1f46dcSZachary Turner   if (!cmd_obj_sp)
29862c1f46dcSZachary Turner     return false;
29872c1f46dcSZachary Turner 
2988b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
2989b9c1b51eSKate Stone                            (PyObject *)cmd_obj_sp->GetValue());
29902c1f46dcSZachary Turner 
2991f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
29922c1f46dcSZachary Turner     return false;
29932c1f46dcSZachary Turner 
2994b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
2995b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
29962c1f46dcSZachary Turner 
29972c1f46dcSZachary Turner   if (PyErr_Occurred())
29982c1f46dcSZachary Turner     PyErr_Clear();
29992c1f46dcSZachary Turner 
3000f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
30012c1f46dcSZachary Turner     return false;
30022c1f46dcSZachary Turner 
3003b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
30042c1f46dcSZachary Turner     if (PyErr_Occurred())
30052c1f46dcSZachary Turner       PyErr_Clear();
30062c1f46dcSZachary Turner     return false;
30072c1f46dcSZachary Turner   }
30082c1f46dcSZachary Turner 
30092c1f46dcSZachary Turner   if (PyErr_Occurred())
30102c1f46dcSZachary Turner     PyErr_Clear();
30112c1f46dcSZachary Turner 
301293571c3cSJonas Devlieghere   // Right now we know this function exists and is callable.
3013b9c1b51eSKate Stone   PythonObject py_return(
3014b9c1b51eSKate Stone       PyRefType::Owned,
3015b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
30162c1f46dcSZachary Turner 
301793571c3cSJonas Devlieghere   // If it fails, print the error but otherwise go on.
3018b9c1b51eSKate Stone   if (PyErr_Occurred()) {
30192c1f46dcSZachary Turner     PyErr_Print();
30202c1f46dcSZachary Turner     PyErr_Clear();
30212c1f46dcSZachary Turner   }
30222c1f46dcSZachary Turner 
3023b9c1b51eSKate Stone   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3024f8b22f8fSZachary Turner     PythonString py_string(PyRefType::Borrowed, py_return.get());
302522c8efcdSZachary Turner     llvm::StringRef return_data(py_string.GetString());
302622c8efcdSZachary Turner     dest.assign(return_data.data(), return_data.size());
302793571c3cSJonas Devlieghere     return true;
30282c1f46dcSZachary Turner   }
302993571c3cSJonas Devlieghere 
303093571c3cSJonas Devlieghere   return false;
30312c1f46dcSZachary Turner }
30322c1f46dcSZachary Turner 
303363dd5d25SJonas Devlieghere uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
3034b9c1b51eSKate Stone     StructuredData::GenericSP cmd_obj_sp) {
30352c1f46dcSZachary Turner   uint32_t result = 0;
30362c1f46dcSZachary Turner 
3037b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
30382c1f46dcSZachary Turner 
30392c1f46dcSZachary Turner   static char callee_name[] = "get_flags";
30402c1f46dcSZachary Turner 
30412c1f46dcSZachary Turner   if (!cmd_obj_sp)
30422c1f46dcSZachary Turner     return result;
30432c1f46dcSZachary Turner 
3044b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
3045b9c1b51eSKate Stone                            (PyObject *)cmd_obj_sp->GetValue());
30462c1f46dcSZachary Turner 
3047f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
30482c1f46dcSZachary Turner     return result;
30492c1f46dcSZachary Turner 
3050b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
3051b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
30522c1f46dcSZachary Turner 
30532c1f46dcSZachary Turner   if (PyErr_Occurred())
30542c1f46dcSZachary Turner     PyErr_Clear();
30552c1f46dcSZachary Turner 
3056f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
30572c1f46dcSZachary Turner     return result;
30582c1f46dcSZachary Turner 
3059b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
30602c1f46dcSZachary Turner     if (PyErr_Occurred())
30612c1f46dcSZachary Turner       PyErr_Clear();
30622c1f46dcSZachary Turner     return result;
30632c1f46dcSZachary Turner   }
30642c1f46dcSZachary Turner 
30652c1f46dcSZachary Turner   if (PyErr_Occurred())
30662c1f46dcSZachary Turner     PyErr_Clear();
30672c1f46dcSZachary Turner 
306852712d3fSLawrence D'Anna   long long py_return = unwrapOrSetPythonException(
306952712d3fSLawrence D'Anna       As<long long>(implementor.CallMethod(callee_name)));
30702c1f46dcSZachary Turner 
30712c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
3072b9c1b51eSKate Stone   if (PyErr_Occurred()) {
30732c1f46dcSZachary Turner     PyErr_Print();
30742c1f46dcSZachary Turner     PyErr_Clear();
307552712d3fSLawrence D'Anna   } else {
307652712d3fSLawrence D'Anna     result = py_return;
30772c1f46dcSZachary Turner   }
30782c1f46dcSZachary Turner 
30792c1f46dcSZachary Turner   return result;
30802c1f46dcSZachary Turner }
30812c1f46dcSZachary Turner 
308263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3083b9c1b51eSKate Stone     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
30842c1f46dcSZachary Turner   bool got_string = false;
30852c1f46dcSZachary Turner   dest.clear();
30862c1f46dcSZachary Turner 
3087b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
30882c1f46dcSZachary Turner 
30892c1f46dcSZachary Turner   static char callee_name[] = "get_long_help";
30902c1f46dcSZachary Turner 
30912c1f46dcSZachary Turner   if (!cmd_obj_sp)
30922c1f46dcSZachary Turner     return false;
30932c1f46dcSZachary Turner 
3094b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
3095b9c1b51eSKate Stone                            (PyObject *)cmd_obj_sp->GetValue());
30962c1f46dcSZachary Turner 
3097f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
30982c1f46dcSZachary Turner     return false;
30992c1f46dcSZachary Turner 
3100b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
3101b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
31022c1f46dcSZachary Turner 
31032c1f46dcSZachary Turner   if (PyErr_Occurred())
31042c1f46dcSZachary Turner     PyErr_Clear();
31052c1f46dcSZachary Turner 
3106f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
31072c1f46dcSZachary Turner     return false;
31082c1f46dcSZachary Turner 
3109b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
31102c1f46dcSZachary Turner     if (PyErr_Occurred())
31112c1f46dcSZachary Turner       PyErr_Clear();
31122c1f46dcSZachary Turner 
31132c1f46dcSZachary Turner     return false;
31142c1f46dcSZachary Turner   }
31152c1f46dcSZachary Turner 
31162c1f46dcSZachary Turner   if (PyErr_Occurred())
31172c1f46dcSZachary Turner     PyErr_Clear();
31182c1f46dcSZachary Turner 
31192c1f46dcSZachary Turner   // right now we know this function exists and is callable..
3120b9c1b51eSKate Stone   PythonObject py_return(
3121b9c1b51eSKate Stone       PyRefType::Owned,
3122b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
31232c1f46dcSZachary Turner 
31242c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
3125b9c1b51eSKate Stone   if (PyErr_Occurred()) {
31262c1f46dcSZachary Turner     PyErr_Print();
31272c1f46dcSZachary Turner     PyErr_Clear();
31282c1f46dcSZachary Turner   }
31292c1f46dcSZachary Turner 
3130b9c1b51eSKate Stone   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3131f8b22f8fSZachary Turner     PythonString str(PyRefType::Borrowed, py_return.get());
313222c8efcdSZachary Turner     llvm::StringRef str_data(str.GetString());
313322c8efcdSZachary Turner     dest.assign(str_data.data(), str_data.size());
31342c1f46dcSZachary Turner     got_string = true;
31352c1f46dcSZachary Turner   }
31362c1f46dcSZachary Turner 
31372c1f46dcSZachary Turner   return got_string;
31382c1f46dcSZachary Turner }
31392c1f46dcSZachary Turner 
31402c1f46dcSZachary Turner std::unique_ptr<ScriptInterpreterLocker>
314163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3142b9c1b51eSKate Stone   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3143b9c1b51eSKate Stone       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
31442c1f46dcSZachary Turner       Locker::FreeLock | Locker::TearDownSession));
31452c1f46dcSZachary Turner   return py_lock;
31462c1f46dcSZachary Turner }
31472c1f46dcSZachary Turner 
314863dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::InitializePrivate() {
314915d1b4e2SEnrico Granata   if (g_initialized)
315015d1b4e2SEnrico Granata     return;
315115d1b4e2SEnrico Granata 
31522c1f46dcSZachary Turner   g_initialized = true;
31532c1f46dcSZachary Turner 
31545c1c8443SJonas Devlieghere   LLDB_SCOPED_TIMER();
31552c1f46dcSZachary Turner 
3156b9c1b51eSKate Stone   // RAII-based initialization which correctly handles multiple-initialization,
315705097246SAdrian Prantl   // version- specific differences among Python 2 and Python 3, and saving and
315805097246SAdrian Prantl   // restoring various other pieces of state that can get mucked with during
315905097246SAdrian Prantl   // initialization.
3160079fe48aSZachary Turner   InitializePythonRAII initialize_guard;
31612c1f46dcSZachary Turner 
316205495c5dSJonas Devlieghere   LLDBSwigPyInit();
31632c1f46dcSZachary Turner 
3164b9c1b51eSKate Stone   // Update the path python uses to search for modules to include the current
3165b9c1b51eSKate Stone   // directory.
31662c1f46dcSZachary Turner 
31672c1f46dcSZachary Turner   PyRun_SimpleString("import sys");
31682c1f46dcSZachary Turner   AddToSysPath(AddLocation::End, ".");
31692c1f46dcSZachary Turner 
3170b9c1b51eSKate Stone   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
317105097246SAdrian Prantl   // that use a backslash as the path separator, this will result in executing
317205097246SAdrian Prantl   // python code containing paths with unescaped backslashes.  But Python also
317305097246SAdrian Prantl   // accepts forward slashes, so to make life easier we just use that.
31742df331b0SPavel Labath   if (FileSpec file_spec = GetPythonDir())
31752c1f46dcSZachary Turner     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
317660f028ffSPavel Labath   if (FileSpec file_spec = HostInfo::GetShlibDir())
31772c1f46dcSZachary Turner     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
31782c1f46dcSZachary Turner 
3179b9c1b51eSKate Stone   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3180b9c1b51eSKate Stone                      "lldb.embedded_interpreter; from "
3181b9c1b51eSKate Stone                      "lldb.embedded_interpreter import run_python_interpreter; "
3182b9c1b51eSKate Stone                      "from lldb.embedded_interpreter import run_one_line");
31832c1f46dcSZachary Turner }
31842c1f46dcSZachary Turner 
318563dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3186b9c1b51eSKate Stone                                                std::string path) {
31872c1f46dcSZachary Turner   std::string path_copy;
31882c1f46dcSZachary Turner 
31892c1f46dcSZachary Turner   std::string statement;
3190b9c1b51eSKate Stone   if (location == AddLocation::Beginning) {
31912c1f46dcSZachary Turner     statement.assign("sys.path.insert(0,\"");
31922c1f46dcSZachary Turner     statement.append(path);
31932c1f46dcSZachary Turner     statement.append("\")");
3194b9c1b51eSKate Stone   } else {
31952c1f46dcSZachary Turner     statement.assign("sys.path.append(\"");
31962c1f46dcSZachary Turner     statement.append(path);
31972c1f46dcSZachary Turner     statement.append("\")");
31982c1f46dcSZachary Turner   }
31992c1f46dcSZachary Turner   PyRun_SimpleString(statement.c_str());
32002c1f46dcSZachary Turner }
32012c1f46dcSZachary Turner 
3202bcadb5a3SPavel Labath // We are intentionally NOT calling Py_Finalize here (this would be the logical
3203bcadb5a3SPavel Labath // place to call it).  Calling Py_Finalize here causes test suite runs to seg
3204bcadb5a3SPavel Labath // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
3205bcadb5a3SPavel Labath // be called 'at_exit'.  When the test suite Python harness finishes up, it
3206bcadb5a3SPavel Labath // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3207bcadb5a3SPavel Labath // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3208bcadb5a3SPavel Labath // which calls ScriptInterpreter::Terminate, which calls
320963dd5d25SJonas Devlieghere // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
321063dd5d25SJonas Devlieghere // end up with Py_Finalize being called from within Py_Finalize, which results
321163dd5d25SJonas Devlieghere // in a seg fault. Since this function only gets called when lldb is shutting
321263dd5d25SJonas Devlieghere // down and going away anyway, the fact that we don't actually call Py_Finalize
3213bcadb5a3SPavel Labath // should not cause any problems (everything should shut down/go away anyway
3214bcadb5a3SPavel Labath // when the process exits).
3215bcadb5a3SPavel Labath //
321663dd5d25SJonas Devlieghere // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3217d68983e3SPavel Labath 
32184e26cf2cSJonas Devlieghere #endif
3219