10b57cec5SDimitry Andric //===-- ScriptInterpreterPython.cpp -----------------------------*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #ifdef LLDB_DISABLE_PYTHON
100b57cec5SDimitry Andric 
110b57cec5SDimitry Andric // Python is disabled in this build
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #else
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric // LLDB Python header must be included first
160b57cec5SDimitry Andric #include "lldb-python.h"
170b57cec5SDimitry Andric 
180b57cec5SDimitry Andric #include "PythonDataObjects.h"
19c14a5a88SDimitry Andric #include "PythonReadline.h"
200b57cec5SDimitry Andric #include "ScriptInterpreterPythonImpl.h"
210b57cec5SDimitry Andric 
220b57cec5SDimitry Andric #include "lldb/API/SBFrame.h"
230b57cec5SDimitry Andric #include "lldb/API/SBValue.h"
240b57cec5SDimitry Andric #include "lldb/Breakpoint/StoppointCallbackContext.h"
250b57cec5SDimitry Andric #include "lldb/Breakpoint/WatchpointOptions.h"
260b57cec5SDimitry Andric #include "lldb/Core/Communication.h"
270b57cec5SDimitry Andric #include "lldb/Core/Debugger.h"
280b57cec5SDimitry Andric #include "lldb/Core/PluginManager.h"
290b57cec5SDimitry Andric #include "lldb/Core/ValueObject.h"
300b57cec5SDimitry Andric #include "lldb/DataFormatters/TypeSummary.h"
310b57cec5SDimitry Andric #include "lldb/Host/ConnectionFileDescriptor.h"
320b57cec5SDimitry Andric #include "lldb/Host/FileSystem.h"
330b57cec5SDimitry Andric #include "lldb/Host/HostInfo.h"
340b57cec5SDimitry Andric #include "lldb/Host/Pipe.h"
350b57cec5SDimitry Andric #include "lldb/Interpreter/CommandInterpreter.h"
360b57cec5SDimitry Andric #include "lldb/Interpreter/CommandReturnObject.h"
370b57cec5SDimitry Andric #include "lldb/Target/Thread.h"
380b57cec5SDimitry Andric #include "lldb/Target/ThreadPlan.h"
390b57cec5SDimitry Andric #include "lldb/Utility/Timer.h"
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric #if defined(_WIN32)
420b57cec5SDimitry Andric #include "lldb/Host/windows/ConnectionGenericFileWindows.h"
430b57cec5SDimitry Andric #endif
440b57cec5SDimitry Andric 
450b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
460b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
470b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
48*9dba64beSDimitry Andric #include "llvm/Support/FormatAdapters.h"
490b57cec5SDimitry Andric 
500b57cec5SDimitry Andric #include <memory>
510b57cec5SDimitry Andric #include <mutex>
520b57cec5SDimitry Andric #include <stdio.h>
530b57cec5SDimitry Andric #include <stdlib.h>
540b57cec5SDimitry Andric #include <string>
550b57cec5SDimitry Andric 
560b57cec5SDimitry Andric using namespace lldb;
570b57cec5SDimitry Andric using namespace lldb_private;
58*9dba64beSDimitry Andric using namespace lldb_private::python;
59*9dba64beSDimitry Andric using llvm::Expected;
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric // Defined in the SWIG source file
620b57cec5SDimitry Andric #if PY_MAJOR_VERSION >= 3
630b57cec5SDimitry Andric extern "C" PyObject *PyInit__lldb(void);
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric #define LLDBSwigPyInit PyInit__lldb
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric #else
680b57cec5SDimitry Andric extern "C" void init_lldb(void);
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric #define LLDBSwigPyInit init_lldb
710b57cec5SDimitry Andric #endif
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric // These prototypes are the Pythonic implementations of the required callbacks.
740b57cec5SDimitry Andric // Although these are scripting-language specific, their definition depends on
750b57cec5SDimitry Andric // the public API.
760b57cec5SDimitry Andric extern "C" bool LLDBSwigPythonBreakpointCallbackFunction(
770b57cec5SDimitry Andric     const char *python_function_name, const char *session_dictionary_name,
780b57cec5SDimitry Andric     const lldb::StackFrameSP &sb_frame,
790b57cec5SDimitry Andric     const lldb::BreakpointLocationSP &sb_bp_loc);
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric extern "C" bool LLDBSwigPythonWatchpointCallbackFunction(
820b57cec5SDimitry Andric     const char *python_function_name, const char *session_dictionary_name,
830b57cec5SDimitry Andric     const lldb::StackFrameSP &sb_frame, const lldb::WatchpointSP &sb_wp);
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric extern "C" bool LLDBSwigPythonCallTypeScript(
860b57cec5SDimitry Andric     const char *python_function_name, void *session_dictionary,
870b57cec5SDimitry Andric     const lldb::ValueObjectSP &valobj_sp, void **pyfunct_wrapper,
880b57cec5SDimitry Andric     const lldb::TypeSummaryOptionsSP &options_sp, std::string &retval);
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric extern "C" void *
910b57cec5SDimitry Andric LLDBSwigPythonCreateSyntheticProvider(const char *python_class_name,
920b57cec5SDimitry Andric                                       const char *session_dictionary_name,
930b57cec5SDimitry Andric                                       const lldb::ValueObjectSP &valobj_sp);
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric extern "C" void *
960b57cec5SDimitry Andric LLDBSwigPythonCreateCommandObject(const char *python_class_name,
970b57cec5SDimitry Andric                                   const char *session_dictionary_name,
980b57cec5SDimitry Andric                                   const lldb::DebuggerSP debugger_sp);
990b57cec5SDimitry Andric 
1000b57cec5SDimitry Andric extern "C" void *LLDBSwigPythonCreateScriptedThreadPlan(
1010b57cec5SDimitry Andric     const char *python_class_name, const char *session_dictionary_name,
102*9dba64beSDimitry Andric     StructuredDataImpl *args_data,
103*9dba64beSDimitry Andric     std::string &error_string,
1040b57cec5SDimitry Andric     const lldb::ThreadPlanSP &thread_plan_sp);
1050b57cec5SDimitry Andric 
1060b57cec5SDimitry Andric extern "C" bool LLDBSWIGPythonCallThreadPlan(void *implementor,
1070b57cec5SDimitry Andric                                              const char *method_name,
1080b57cec5SDimitry Andric                                              Event *event_sp, bool &got_error);
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric extern "C" void *LLDBSwigPythonCreateScriptedBreakpointResolver(
1110b57cec5SDimitry Andric     const char *python_class_name, const char *session_dictionary_name,
1120b57cec5SDimitry Andric     lldb_private::StructuredDataImpl *args, lldb::BreakpointSP &bkpt_sp);
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric extern "C" unsigned int
1150b57cec5SDimitry Andric LLDBSwigPythonCallBreakpointResolver(void *implementor, const char *method_name,
1160b57cec5SDimitry Andric                                      lldb_private::SymbolContext *sym_ctx);
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric extern "C" size_t LLDBSwigPython_CalculateNumChildren(void *implementor,
1190b57cec5SDimitry Andric                                                       uint32_t max);
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric extern "C" void *LLDBSwigPython_GetChildAtIndex(void *implementor,
1220b57cec5SDimitry Andric                                                 uint32_t idx);
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric extern "C" int LLDBSwigPython_GetIndexOfChildWithName(void *implementor,
1250b57cec5SDimitry Andric                                                       const char *child_name);
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric extern "C" void *LLDBSWIGPython_CastPyObjectToSBValue(void *data);
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric extern lldb::ValueObjectSP
1300b57cec5SDimitry Andric LLDBSWIGPython_GetValueObjectSPFromSBValue(void *data);
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric extern "C" bool LLDBSwigPython_UpdateSynthProviderInstance(void *implementor);
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric extern "C" bool
1350b57cec5SDimitry Andric LLDBSwigPython_MightHaveChildrenSynthProviderInstance(void *implementor);
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric extern "C" void *
1380b57cec5SDimitry Andric LLDBSwigPython_GetValueSynthProviderInstance(void *implementor);
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric extern "C" bool
1410b57cec5SDimitry Andric LLDBSwigPythonCallCommand(const char *python_function_name,
1420b57cec5SDimitry Andric                           const char *session_dictionary_name,
1430b57cec5SDimitry Andric                           lldb::DebuggerSP &debugger, const char *args,
1440b57cec5SDimitry Andric                           lldb_private::CommandReturnObject &cmd_retobj,
1450b57cec5SDimitry Andric                           lldb::ExecutionContextRefSP exe_ctx_ref_sp);
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric extern "C" bool
1480b57cec5SDimitry Andric LLDBSwigPythonCallCommandObject(void *implementor, lldb::DebuggerSP &debugger,
1490b57cec5SDimitry Andric                                 const char *args,
1500b57cec5SDimitry Andric                                 lldb_private::CommandReturnObject &cmd_retobj,
1510b57cec5SDimitry Andric                                 lldb::ExecutionContextRefSP exe_ctx_ref_sp);
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric extern "C" bool
1540b57cec5SDimitry Andric LLDBSwigPythonCallModuleInit(const char *python_module_name,
1550b57cec5SDimitry Andric                              const char *session_dictionary_name,
1560b57cec5SDimitry Andric                              lldb::DebuggerSP &debugger);
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric extern "C" void *
1590b57cec5SDimitry Andric LLDBSWIGPythonCreateOSPlugin(const char *python_class_name,
1600b57cec5SDimitry Andric                              const char *session_dictionary_name,
1610b57cec5SDimitry Andric                              const lldb::ProcessSP &process_sp);
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric extern "C" void *
1640b57cec5SDimitry Andric LLDBSWIGPython_CreateFrameRecognizer(const char *python_class_name,
1650b57cec5SDimitry Andric                                      const char *session_dictionary_name);
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric extern "C" void *
1680b57cec5SDimitry Andric LLDBSwigPython_GetRecognizedArguments(void *implementor,
1690b57cec5SDimitry Andric                                       const lldb::StackFrameSP &frame_sp);
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric extern "C" bool LLDBSWIGPythonRunScriptKeywordProcess(
1720b57cec5SDimitry Andric     const char *python_function_name, const char *session_dictionary_name,
1730b57cec5SDimitry Andric     lldb::ProcessSP &process, std::string &output);
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric extern "C" bool LLDBSWIGPythonRunScriptKeywordThread(
1760b57cec5SDimitry Andric     const char *python_function_name, const char *session_dictionary_name,
1770b57cec5SDimitry Andric     lldb::ThreadSP &thread, std::string &output);
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric extern "C" bool LLDBSWIGPythonRunScriptKeywordTarget(
1800b57cec5SDimitry Andric     const char *python_function_name, const char *session_dictionary_name,
1810b57cec5SDimitry Andric     lldb::TargetSP &target, std::string &output);
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric extern "C" bool LLDBSWIGPythonRunScriptKeywordFrame(
1840b57cec5SDimitry Andric     const char *python_function_name, const char *session_dictionary_name,
1850b57cec5SDimitry Andric     lldb::StackFrameSP &frame, std::string &output);
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric extern "C" bool LLDBSWIGPythonRunScriptKeywordValue(
1880b57cec5SDimitry Andric     const char *python_function_name, const char *session_dictionary_name,
1890b57cec5SDimitry Andric     lldb::ValueObjectSP &value, std::string &output);
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric extern "C" void *
1920b57cec5SDimitry Andric LLDBSWIGPython_GetDynamicSetting(void *module, const char *setting,
1930b57cec5SDimitry Andric                                  const lldb::TargetSP &target_sp);
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric static bool g_initialized = false;
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric namespace {
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric // Initializing Python is not a straightforward process.  We cannot control
2000b57cec5SDimitry Andric // what external code may have done before getting to this point in LLDB,
2010b57cec5SDimitry Andric // including potentially having already initialized Python, so we need to do a
2020b57cec5SDimitry Andric // lot of work to ensure that the existing state of the system is maintained
2030b57cec5SDimitry Andric // across our initialization.  We do this by using an RAII pattern where we
2040b57cec5SDimitry Andric // save off initial state at the beginning, and restore it at the end
2050b57cec5SDimitry Andric struct InitializePythonRAII {
2060b57cec5SDimitry Andric public:
2070b57cec5SDimitry Andric   InitializePythonRAII()
2080b57cec5SDimitry Andric       : m_gil_state(PyGILState_UNLOCKED), m_was_already_initialized(false) {
2090b57cec5SDimitry Andric     // Python will muck with STDIN terminal state, so save off any current TTY
2100b57cec5SDimitry Andric     // settings so we can restore them.
2110b57cec5SDimitry Andric     m_stdin_tty_state.Save(STDIN_FILENO, false);
2120b57cec5SDimitry Andric 
2130b57cec5SDimitry Andric     InitializePythonHome();
2140b57cec5SDimitry Andric 
215c14a5a88SDimitry Andric #ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
216c14a5a88SDimitry Andric     // Python's readline is incompatible with libedit being linked into lldb.
217c14a5a88SDimitry Andric     // Provide a patched version local to the embedded interpreter.
218c14a5a88SDimitry Andric     bool ReadlinePatched = false;
219c14a5a88SDimitry Andric     for (auto *p = PyImport_Inittab; p->name != NULL; p++) {
220c14a5a88SDimitry Andric       if (strcmp(p->name, "readline") == 0) {
221c14a5a88SDimitry Andric         p->initfunc = initlldb_readline;
222c14a5a88SDimitry Andric         break;
223c14a5a88SDimitry Andric       }
224c14a5a88SDimitry Andric     }
225c14a5a88SDimitry Andric     if (!ReadlinePatched) {
226c14a5a88SDimitry Andric       PyImport_AppendInittab("readline", initlldb_readline);
227c14a5a88SDimitry Andric       ReadlinePatched = true;
228c14a5a88SDimitry Andric     }
229c14a5a88SDimitry Andric #endif
230c14a5a88SDimitry Andric 
2310b57cec5SDimitry Andric     // Register _lldb as a built-in module.
2320b57cec5SDimitry Andric     PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
2350b57cec5SDimitry Andric // calling `Py_Initialize` and `PyEval_InitThreads`.  < 3.2 requires that you
2360b57cec5SDimitry Andric // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
2370b57cec5SDimitry Andric #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
2380b57cec5SDimitry Andric     Py_InitializeEx(0);
2390b57cec5SDimitry Andric     InitializeThreadsPrivate();
2400b57cec5SDimitry Andric #else
2410b57cec5SDimitry Andric     InitializeThreadsPrivate();
2420b57cec5SDimitry Andric     Py_InitializeEx(0);
2430b57cec5SDimitry Andric #endif
2440b57cec5SDimitry Andric   }
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric   ~InitializePythonRAII() {
2470b57cec5SDimitry Andric     if (m_was_already_initialized) {
2480b57cec5SDimitry Andric       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
2490b57cec5SDimitry Andric       LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
2500b57cec5SDimitry Andric                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
2510b57cec5SDimitry Andric       PyGILState_Release(m_gil_state);
2520b57cec5SDimitry Andric     } else {
2530b57cec5SDimitry Andric       // We initialized the threads in this function, just unlock the GIL.
2540b57cec5SDimitry Andric       PyEval_SaveThread();
2550b57cec5SDimitry Andric     }
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric     m_stdin_tty_state.Restore();
2580b57cec5SDimitry Andric   }
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric private:
2610b57cec5SDimitry Andric   void InitializePythonHome() {
2620b57cec5SDimitry Andric #if defined(LLDB_PYTHON_HOME)
2630b57cec5SDimitry Andric #if PY_MAJOR_VERSION >= 3
2640b57cec5SDimitry Andric     size_t size = 0;
2650b57cec5SDimitry Andric     static wchar_t *g_python_home = Py_DecodeLocale(LLDB_PYTHON_HOME, &size);
2660b57cec5SDimitry Andric #else
2670b57cec5SDimitry Andric     static char g_python_home[] = LLDB_PYTHON_HOME;
2680b57cec5SDimitry Andric #endif
2690b57cec5SDimitry Andric     Py_SetPythonHome(g_python_home);
2700b57cec5SDimitry Andric #else
2710b57cec5SDimitry Andric #if defined(__APPLE__) && PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION == 7
2720b57cec5SDimitry Andric     // For Darwin, the only Python version supported is the one shipped in the
2730b57cec5SDimitry Andric     // OS OS and linked with lldb. Other installation of Python may have higher
2740b57cec5SDimitry Andric     // priorities in the path, overriding PYTHONHOME and causing
2750b57cec5SDimitry Andric     // problems/incompatibilities. In order to avoid confusion, always hardcode
2760b57cec5SDimitry Andric     // the PythonHome to be right, as it's not going to change.
2770b57cec5SDimitry Andric     static char path[] =
2780b57cec5SDimitry Andric         "/System/Library/Frameworks/Python.framework/Versions/2.7";
2790b57cec5SDimitry Andric     Py_SetPythonHome(path);
2800b57cec5SDimitry Andric #endif
2810b57cec5SDimitry Andric #endif
2820b57cec5SDimitry Andric   }
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric   void InitializeThreadsPrivate() {
2850b57cec5SDimitry Andric // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself,
2860b57cec5SDimitry Andric // so there is no way to determine whether the embedded interpreter
2870b57cec5SDimitry Andric // was already initialized by some external code. `PyEval_ThreadsInitialized`
2880b57cec5SDimitry Andric // would always return `true` and `PyGILState_Ensure/Release` flow would be
2890b57cec5SDimitry Andric // executed instead of unlocking GIL with `PyEval_SaveThread`. When
2900b57cec5SDimitry Andric // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock.
2910b57cec5SDimitry Andric #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3)
2920b57cec5SDimitry Andric     // The only case we should go further and acquire the GIL: it is unlocked.
2930b57cec5SDimitry Andric     if (PyGILState_Check())
2940b57cec5SDimitry Andric       return;
2950b57cec5SDimitry Andric #endif
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric     if (PyEval_ThreadsInitialized()) {
2980b57cec5SDimitry Andric       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric       m_was_already_initialized = true;
3010b57cec5SDimitry Andric       m_gil_state = PyGILState_Ensure();
3020b57cec5SDimitry Andric       LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n",
3030b57cec5SDimitry Andric                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
3040b57cec5SDimitry Andric       return;
3050b57cec5SDimitry Andric     }
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric     // InitThreads acquires the GIL if it hasn't been called before.
3080b57cec5SDimitry Andric     PyEval_InitThreads();
3090b57cec5SDimitry Andric   }
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric   TerminalState m_stdin_tty_state;
3120b57cec5SDimitry Andric   PyGILState_STATE m_gil_state;
3130b57cec5SDimitry Andric   bool m_was_already_initialized;
3140b57cec5SDimitry Andric };
3150b57cec5SDimitry Andric } // namespace
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric void ScriptInterpreterPython::ComputePythonDirForApple(
3180b57cec5SDimitry Andric     llvm::SmallVectorImpl<char> &path) {
3190b57cec5SDimitry Andric   auto style = llvm::sys::path::Style::posix;
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric   llvm::StringRef path_ref(path.begin(), path.size());
3220b57cec5SDimitry Andric   auto rbegin = llvm::sys::path::rbegin(path_ref, style);
3230b57cec5SDimitry Andric   auto rend = llvm::sys::path::rend(path_ref);
3240b57cec5SDimitry Andric   auto framework = std::find(rbegin, rend, "LLDB.framework");
3250b57cec5SDimitry Andric   if (framework == rend) {
326*9dba64beSDimitry Andric     ComputePythonDir(path);
3270b57cec5SDimitry Andric     return;
3280b57cec5SDimitry Andric   }
3290b57cec5SDimitry Andric   path.resize(framework - rend);
3300b57cec5SDimitry Andric   llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
3310b57cec5SDimitry Andric }
3320b57cec5SDimitry Andric 
333*9dba64beSDimitry Andric void ScriptInterpreterPython::ComputePythonDir(
3340b57cec5SDimitry Andric     llvm::SmallVectorImpl<char> &path) {
3350b57cec5SDimitry Andric   // Build the path by backing out of the lib dir, then building with whatever
3360b57cec5SDimitry Andric   // the real python interpreter uses.  (e.g. lib for most, lib64 on RHEL
337*9dba64beSDimitry Andric   // x86_64, or bin on Windows).
338*9dba64beSDimitry Andric   llvm::sys::path::remove_filename(path);
339*9dba64beSDimitry Andric   llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
3400b57cec5SDimitry Andric 
341*9dba64beSDimitry Andric #if defined(_WIN32)
3420b57cec5SDimitry Andric   // This will be injected directly through FileSpec.GetDirectory().SetString(),
3430b57cec5SDimitry Andric   // so we need to normalize manually.
3440b57cec5SDimitry Andric   std::replace(path.begin(), path.end(), '\\', '/');
345*9dba64beSDimitry Andric #endif
3460b57cec5SDimitry Andric }
3470b57cec5SDimitry Andric 
3480b57cec5SDimitry Andric FileSpec ScriptInterpreterPython::GetPythonDir() {
3490b57cec5SDimitry Andric   static FileSpec g_spec = []() {
3500b57cec5SDimitry Andric     FileSpec spec = HostInfo::GetShlibDir();
3510b57cec5SDimitry Andric     if (!spec)
3520b57cec5SDimitry Andric       return FileSpec();
3530b57cec5SDimitry Andric     llvm::SmallString<64> path;
3540b57cec5SDimitry Andric     spec.GetPath(path);
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric #if defined(__APPLE__)
3570b57cec5SDimitry Andric     ComputePythonDirForApple(path);
3580b57cec5SDimitry Andric #else
359*9dba64beSDimitry Andric     ComputePythonDir(path);
3600b57cec5SDimitry Andric #endif
3610b57cec5SDimitry Andric     spec.GetDirectory().SetString(path);
3620b57cec5SDimitry Andric     return spec;
3630b57cec5SDimitry Andric   }();
3640b57cec5SDimitry Andric   return g_spec;
3650b57cec5SDimitry Andric }
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric lldb_private::ConstString ScriptInterpreterPython::GetPluginNameStatic() {
3680b57cec5SDimitry Andric   static ConstString g_name("script-python");
3690b57cec5SDimitry Andric   return g_name;
3700b57cec5SDimitry Andric }
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric const char *ScriptInterpreterPython::GetPluginDescriptionStatic() {
3730b57cec5SDimitry Andric   return "Embedded Python interpreter";
3740b57cec5SDimitry Andric }
3750b57cec5SDimitry Andric 
3760b57cec5SDimitry Andric void ScriptInterpreterPython::Initialize() {
3770b57cec5SDimitry Andric   static llvm::once_flag g_once_flag;
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric   llvm::call_once(g_once_flag, []() {
3800b57cec5SDimitry Andric     PluginManager::RegisterPlugin(GetPluginNameStatic(),
3810b57cec5SDimitry Andric                                   GetPluginDescriptionStatic(),
3820b57cec5SDimitry Andric                                   lldb::eScriptLanguagePython,
3830b57cec5SDimitry Andric                                   ScriptInterpreterPythonImpl::CreateInstance);
3840b57cec5SDimitry Andric   });
3850b57cec5SDimitry Andric }
3860b57cec5SDimitry Andric 
3870b57cec5SDimitry Andric void ScriptInterpreterPython::Terminate() {}
3880b57cec5SDimitry Andric 
3890b57cec5SDimitry Andric ScriptInterpreterPythonImpl::Locker::Locker(
3900b57cec5SDimitry Andric     ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
391*9dba64beSDimitry Andric     uint16_t on_leave, FileSP in, FileSP out, FileSP err)
3920b57cec5SDimitry Andric     : ScriptInterpreterLocker(),
3930b57cec5SDimitry Andric       m_teardown_session((on_leave & TearDownSession) == TearDownSession),
3940b57cec5SDimitry Andric       m_python_interpreter(py_interpreter) {
3950b57cec5SDimitry Andric   DoAcquireLock();
3960b57cec5SDimitry Andric   if ((on_entry & InitSession) == InitSession) {
3970b57cec5SDimitry Andric     if (!DoInitSession(on_entry, in, out, err)) {
3980b57cec5SDimitry Andric       // Don't teardown the session if we didn't init it.
3990b57cec5SDimitry Andric       m_teardown_session = false;
4000b57cec5SDimitry Andric     }
4010b57cec5SDimitry Andric   }
4020b57cec5SDimitry Andric }
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
4050b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
4060b57cec5SDimitry Andric   m_GILState = PyGILState_Ensure();
4070b57cec5SDimitry Andric   LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked",
4080b57cec5SDimitry Andric             m_GILState == PyGILState_UNLOCKED ? "un" : "");
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric   // we need to save the thread state when we first start the command because
4110b57cec5SDimitry Andric   // we might decide to interrupt it while some action is taking place outside
4120b57cec5SDimitry Andric   // of Python (e.g. printing to screen, waiting for the network, ...) in that
4130b57cec5SDimitry Andric   // case, _PyThreadState_Current will be NULL - and we would be unable to set
4140b57cec5SDimitry Andric   // the asynchronous exception - not a desirable situation
4150b57cec5SDimitry Andric   m_python_interpreter->SetThreadState(PyThreadState_Get());
4160b57cec5SDimitry Andric   m_python_interpreter->IncrementLockCount();
4170b57cec5SDimitry Andric   return true;
4180b57cec5SDimitry Andric }
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
421*9dba64beSDimitry Andric                                                         FileSP in, FileSP out,
422*9dba64beSDimitry Andric                                                         FileSP err) {
4230b57cec5SDimitry Andric   if (!m_python_interpreter)
4240b57cec5SDimitry Andric     return false;
4250b57cec5SDimitry Andric   return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
4260b57cec5SDimitry Andric }
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
4290b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
4300b57cec5SDimitry Andric   LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
4310b57cec5SDimitry Andric             m_GILState == PyGILState_UNLOCKED ? "un" : "");
4320b57cec5SDimitry Andric   PyGILState_Release(m_GILState);
4330b57cec5SDimitry Andric   m_python_interpreter->DecrementLockCount();
4340b57cec5SDimitry Andric   return true;
4350b57cec5SDimitry Andric }
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
4380b57cec5SDimitry Andric   if (!m_python_interpreter)
4390b57cec5SDimitry Andric     return false;
4400b57cec5SDimitry Andric   m_python_interpreter->LeaveSession();
4410b57cec5SDimitry Andric   return true;
4420b57cec5SDimitry Andric }
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric ScriptInterpreterPythonImpl::Locker::~Locker() {
4450b57cec5SDimitry Andric   if (m_teardown_session)
4460b57cec5SDimitry Andric     DoTearDownSession();
4470b57cec5SDimitry Andric   DoFreeLock();
4480b57cec5SDimitry Andric }
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger)
4510b57cec5SDimitry Andric     : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
4520b57cec5SDimitry Andric       m_saved_stderr(), m_main_module(),
4530b57cec5SDimitry Andric       m_session_dict(PyInitialValue::Invalid),
4540b57cec5SDimitry Andric       m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(),
4550b57cec5SDimitry Andric       m_run_one_line_str_global(),
4560b57cec5SDimitry Andric       m_dictionary_name(m_debugger.GetInstanceName().AsCString()),
457*9dba64beSDimitry Andric       m_active_io_handler(eIOHandlerNone), m_session_is_active(false),
458*9dba64beSDimitry Andric       m_pty_slave_is_open(false), m_valid_session(true), m_lock_count(0),
459*9dba64beSDimitry Andric       m_command_thread_state(nullptr) {
4600b57cec5SDimitry Andric   InitializePrivate();
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric   m_dictionary_name.append("_dict");
4630b57cec5SDimitry Andric   StreamString run_string;
4640b57cec5SDimitry Andric   run_string.Printf("%s = dict()", m_dictionary_name.c_str());
4650b57cec5SDimitry Andric 
4660b57cec5SDimitry Andric   Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock);
4670b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   run_string.Clear();
4700b57cec5SDimitry Andric   run_string.Printf(
4710b57cec5SDimitry Andric       "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
4720b57cec5SDimitry Andric       m_dictionary_name.c_str());
4730b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
4740b57cec5SDimitry Andric 
4750b57cec5SDimitry Andric   // Reloading modules requires a different syntax in Python 2 and Python 3.
4760b57cec5SDimitry Andric   // This provides a consistent syntax no matter what version of Python.
4770b57cec5SDimitry Andric   run_string.Clear();
4780b57cec5SDimitry Andric   run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')",
4790b57cec5SDimitry Andric                     m_dictionary_name.c_str());
4800b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
4810b57cec5SDimitry Andric 
4820b57cec5SDimitry Andric   // WARNING: temporary code that loads Cocoa formatters - this should be done
4830b57cec5SDimitry Andric   // on a per-platform basis rather than loading the whole set and letting the
4840b57cec5SDimitry Andric   // individual formatter classes exploit APIs to check whether they can/cannot
4850b57cec5SDimitry Andric   // do their task
4860b57cec5SDimitry Andric   run_string.Clear();
4870b57cec5SDimitry Andric   run_string.Printf(
4880b57cec5SDimitry Andric       "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')",
4890b57cec5SDimitry Andric       m_dictionary_name.c_str());
4900b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
4910b57cec5SDimitry Andric   run_string.Clear();
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric   run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
4940b57cec5SDimitry Andric                     "lldb.embedded_interpreter import run_python_interpreter; "
4950b57cec5SDimitry Andric                     "from lldb.embedded_interpreter import run_one_line')",
4960b57cec5SDimitry Andric                     m_dictionary_name.c_str());
4970b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
4980b57cec5SDimitry Andric   run_string.Clear();
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric   run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
5010b57cec5SDimitry Andric                     "; pydoc.pager = pydoc.plainpager')",
5020b57cec5SDimitry Andric                     m_dictionary_name.c_str(), m_debugger.GetID());
5030b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
5040b57cec5SDimitry Andric }
5050b57cec5SDimitry Andric 
5060b57cec5SDimitry Andric ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
5070b57cec5SDimitry Andric   // the session dictionary may hold objects with complex state which means
5080b57cec5SDimitry Andric   // that they may need to be torn down with some level of smarts and that, in
5090b57cec5SDimitry Andric   // turn, requires a valid thread state force Python to procure itself such a
5100b57cec5SDimitry Andric   // thread state, nuke the session dictionary and then release it for others
5110b57cec5SDimitry Andric   // to use and proceed with the rest of the shutdown
5120b57cec5SDimitry Andric   auto gil_state = PyGILState_Ensure();
5130b57cec5SDimitry Andric   m_session_dict.Reset();
5140b57cec5SDimitry Andric   PyGILState_Release(gil_state);
5150b57cec5SDimitry Andric }
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric lldb_private::ConstString ScriptInterpreterPythonImpl::GetPluginName() {
5180b57cec5SDimitry Andric   return GetPluginNameStatic();
5190b57cec5SDimitry Andric }
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric uint32_t ScriptInterpreterPythonImpl::GetPluginVersion() { return 1; }
5220b57cec5SDimitry Andric 
5230b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler,
5240b57cec5SDimitry Andric                                                      bool interactive) {
5250b57cec5SDimitry Andric   const char *instructions = nullptr;
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric   switch (m_active_io_handler) {
5280b57cec5SDimitry Andric   case eIOHandlerNone:
5290b57cec5SDimitry Andric     break;
5300b57cec5SDimitry Andric   case eIOHandlerBreakpoint:
5310b57cec5SDimitry Andric     instructions = R"(Enter your Python command(s). Type 'DONE' to end.
5320b57cec5SDimitry Andric def function (frame, bp_loc, internal_dict):
5330b57cec5SDimitry Andric     """frame: the lldb.SBFrame for the location at which you stopped
5340b57cec5SDimitry Andric        bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
5350b57cec5SDimitry Andric        internal_dict: an LLDB support object not to be used"""
5360b57cec5SDimitry Andric )";
5370b57cec5SDimitry Andric     break;
5380b57cec5SDimitry Andric   case eIOHandlerWatchpoint:
5390b57cec5SDimitry Andric     instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
5400b57cec5SDimitry Andric     break;
5410b57cec5SDimitry Andric   }
5420b57cec5SDimitry Andric 
5430b57cec5SDimitry Andric   if (instructions) {
544*9dba64beSDimitry Andric     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
5450b57cec5SDimitry Andric     if (output_sp && interactive) {
5460b57cec5SDimitry Andric       output_sp->PutCString(instructions);
5470b57cec5SDimitry Andric       output_sp->Flush();
5480b57cec5SDimitry Andric     }
5490b57cec5SDimitry Andric   }
5500b57cec5SDimitry Andric }
5510b57cec5SDimitry Andric 
5520b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler,
5530b57cec5SDimitry Andric                                                          std::string &data) {
5540b57cec5SDimitry Andric   io_handler.SetIsDone(true);
5550b57cec5SDimitry Andric   bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
5560b57cec5SDimitry Andric 
5570b57cec5SDimitry Andric   switch (m_active_io_handler) {
5580b57cec5SDimitry Andric   case eIOHandlerNone:
5590b57cec5SDimitry Andric     break;
5600b57cec5SDimitry Andric   case eIOHandlerBreakpoint: {
5610b57cec5SDimitry Andric     std::vector<BreakpointOptions *> *bp_options_vec =
5620b57cec5SDimitry Andric         (std::vector<BreakpointOptions *> *)io_handler.GetUserData();
5630b57cec5SDimitry Andric     for (auto bp_options : *bp_options_vec) {
5640b57cec5SDimitry Andric       if (!bp_options)
5650b57cec5SDimitry Andric         continue;
5660b57cec5SDimitry Andric 
567*9dba64beSDimitry Andric       auto data_up = std::make_unique<CommandDataPython>();
5680b57cec5SDimitry Andric       if (!data_up)
5690b57cec5SDimitry Andric         break;
5700b57cec5SDimitry Andric       data_up->user_source.SplitIntoLines(data);
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric       if (GenerateBreakpointCommandCallbackData(data_up->user_source,
5730b57cec5SDimitry Andric                                                 data_up->script_source)
5740b57cec5SDimitry Andric               .Success()) {
5750b57cec5SDimitry Andric         auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
5760b57cec5SDimitry Andric             std::move(data_up));
5770b57cec5SDimitry Andric         bp_options->SetCallback(
5780b57cec5SDimitry Andric             ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
5790b57cec5SDimitry Andric       } else if (!batch_mode) {
580*9dba64beSDimitry Andric         StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
5810b57cec5SDimitry Andric         if (error_sp) {
5820b57cec5SDimitry Andric           error_sp->Printf("Warning: No command attached to breakpoint.\n");
5830b57cec5SDimitry Andric           error_sp->Flush();
5840b57cec5SDimitry Andric         }
5850b57cec5SDimitry Andric       }
5860b57cec5SDimitry Andric     }
5870b57cec5SDimitry Andric     m_active_io_handler = eIOHandlerNone;
5880b57cec5SDimitry Andric   } break;
5890b57cec5SDimitry Andric   case eIOHandlerWatchpoint: {
5900b57cec5SDimitry Andric     WatchpointOptions *wp_options =
5910b57cec5SDimitry Andric         (WatchpointOptions *)io_handler.GetUserData();
592*9dba64beSDimitry Andric     auto data_up = std::make_unique<WatchpointOptions::CommandData>();
5930b57cec5SDimitry Andric     data_up->user_source.SplitIntoLines(data);
5940b57cec5SDimitry Andric 
5950b57cec5SDimitry Andric     if (GenerateWatchpointCommandCallbackData(data_up->user_source,
5960b57cec5SDimitry Andric                                               data_up->script_source)) {
5970b57cec5SDimitry Andric       auto baton_sp =
5980b57cec5SDimitry Andric           std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
5990b57cec5SDimitry Andric       wp_options->SetCallback(
6000b57cec5SDimitry Andric           ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
6010b57cec5SDimitry Andric     } else if (!batch_mode) {
602*9dba64beSDimitry Andric       StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
6030b57cec5SDimitry Andric       if (error_sp) {
6040b57cec5SDimitry Andric         error_sp->Printf("Warning: No command attached to breakpoint.\n");
6050b57cec5SDimitry Andric         error_sp->Flush();
6060b57cec5SDimitry Andric       }
6070b57cec5SDimitry Andric     }
6080b57cec5SDimitry Andric     m_active_io_handler = eIOHandlerNone;
6090b57cec5SDimitry Andric   } break;
6100b57cec5SDimitry Andric   }
6110b57cec5SDimitry Andric }
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric lldb::ScriptInterpreterSP
6140b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) {
6150b57cec5SDimitry Andric   return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
6160b57cec5SDimitry Andric }
6170b57cec5SDimitry Andric 
6180b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::LeaveSession() {
6190b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
6200b57cec5SDimitry Andric   if (log)
6210b57cec5SDimitry Andric     log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
6220b57cec5SDimitry Andric 
623*9dba64beSDimitry Andric   // Unset the LLDB global variables.
624*9dba64beSDimitry Andric   PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
625*9dba64beSDimitry Andric                      "= None; lldb.thread = None; lldb.frame = None");
626*9dba64beSDimitry Andric 
6270b57cec5SDimitry Andric   // checking that we have a valid thread state - since we use our own
6280b57cec5SDimitry Andric   // threading and locking in some (rare) cases during cleanup Python may end
6290b57cec5SDimitry Andric   // up believing we have no thread state and PyImport_AddModule will crash if
6300b57cec5SDimitry Andric   // that is the case - since that seems to only happen when destroying the
6310b57cec5SDimitry Andric   // SBDebugger, we can make do without clearing up stdout and stderr
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric   // rdar://problem/11292882
6340b57cec5SDimitry Andric   // When the current thread state is NULL, PyThreadState_Get() issues a fatal
6350b57cec5SDimitry Andric   // error.
6360b57cec5SDimitry Andric   if (PyThreadState_GetDict()) {
6370b57cec5SDimitry Andric     PythonDictionary &sys_module_dict = GetSysModuleDictionary();
6380b57cec5SDimitry Andric     if (sys_module_dict.IsValid()) {
6390b57cec5SDimitry Andric       if (m_saved_stdin.IsValid()) {
6400b57cec5SDimitry Andric         sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
6410b57cec5SDimitry Andric         m_saved_stdin.Reset();
6420b57cec5SDimitry Andric       }
6430b57cec5SDimitry Andric       if (m_saved_stdout.IsValid()) {
6440b57cec5SDimitry Andric         sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
6450b57cec5SDimitry Andric         m_saved_stdout.Reset();
6460b57cec5SDimitry Andric       }
6470b57cec5SDimitry Andric       if (m_saved_stderr.IsValid()) {
6480b57cec5SDimitry Andric         sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
6490b57cec5SDimitry Andric         m_saved_stderr.Reset();
6500b57cec5SDimitry Andric       }
6510b57cec5SDimitry Andric     }
6520b57cec5SDimitry Andric   }
6530b57cec5SDimitry Andric 
6540b57cec5SDimitry Andric   m_session_is_active = false;
6550b57cec5SDimitry Andric }
6560b57cec5SDimitry Andric 
657*9dba64beSDimitry Andric bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp,
658*9dba64beSDimitry Andric                                                const char *py_name,
659*9dba64beSDimitry Andric                                                PythonObject &save_file,
6600b57cec5SDimitry Andric                                                const char *mode) {
661*9dba64beSDimitry Andric   if (!file_sp || !*file_sp) {
662*9dba64beSDimitry Andric     save_file.Reset();
663*9dba64beSDimitry Andric     return false;
664*9dba64beSDimitry Andric   }
665*9dba64beSDimitry Andric   File &file = *file_sp;
666*9dba64beSDimitry Andric 
6670b57cec5SDimitry Andric   // Flush the file before giving it to python to avoid interleaved output.
6680b57cec5SDimitry Andric   file.Flush();
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
6710b57cec5SDimitry Andric 
672*9dba64beSDimitry Andric   auto new_file = PythonFile::FromFile(file, mode);
673*9dba64beSDimitry Andric   if (!new_file) {
674*9dba64beSDimitry Andric     llvm::consumeError(new_file.takeError());
6750b57cec5SDimitry Andric     return false;
6760b57cec5SDimitry Andric   }
6770b57cec5SDimitry Andric 
678*9dba64beSDimitry Andric   save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
679*9dba64beSDimitry Andric 
680*9dba64beSDimitry Andric   sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
681*9dba64beSDimitry Andric   return true;
682*9dba64beSDimitry Andric }
683*9dba64beSDimitry Andric 
6840b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
685*9dba64beSDimitry Andric                                                FileSP in_sp, FileSP out_sp,
686*9dba64beSDimitry Andric                                                FileSP err_sp) {
6870b57cec5SDimitry Andric   // If we have already entered the session, without having officially 'left'
6880b57cec5SDimitry Andric   // it, then there is no need to 'enter' it again.
6890b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
6900b57cec5SDimitry Andric   if (m_session_is_active) {
691*9dba64beSDimitry Andric     LLDB_LOGF(
692*9dba64beSDimitry Andric         log,
6930b57cec5SDimitry Andric         "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
6940b57cec5SDimitry Andric         ") session is already active, returning without doing anything",
6950b57cec5SDimitry Andric         on_entry_flags);
6960b57cec5SDimitry Andric     return false;
6970b57cec5SDimitry Andric   }
6980b57cec5SDimitry Andric 
699*9dba64beSDimitry Andric   LLDB_LOGF(
700*9dba64beSDimitry Andric       log,
701*9dba64beSDimitry Andric       "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
7020b57cec5SDimitry Andric       on_entry_flags);
7030b57cec5SDimitry Andric 
7040b57cec5SDimitry Andric   m_session_is_active = true;
7050b57cec5SDimitry Andric 
7060b57cec5SDimitry Andric   StreamString run_string;
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric   if (on_entry_flags & Locker::InitGlobals) {
7090b57cec5SDimitry Andric     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
7100b57cec5SDimitry Andric                       m_dictionary_name.c_str(), m_debugger.GetID());
7110b57cec5SDimitry Andric     run_string.Printf(
7120b57cec5SDimitry Andric         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
7130b57cec5SDimitry Andric         m_debugger.GetID());
7140b57cec5SDimitry Andric     run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
7150b57cec5SDimitry Andric     run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
7160b57cec5SDimitry Andric     run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
7170b57cec5SDimitry Andric     run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
7180b57cec5SDimitry Andric     run_string.PutCString("')");
7190b57cec5SDimitry Andric   } else {
7200b57cec5SDimitry Andric     // If we aren't initing the globals, we should still always set the
7210b57cec5SDimitry Andric     // debugger (since that is always unique.)
7220b57cec5SDimitry Andric     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
7230b57cec5SDimitry Andric                       m_dictionary_name.c_str(), m_debugger.GetID());
7240b57cec5SDimitry Andric     run_string.Printf(
7250b57cec5SDimitry Andric         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
7260b57cec5SDimitry Andric         m_debugger.GetID());
7270b57cec5SDimitry Andric     run_string.PutCString("')");
7280b57cec5SDimitry Andric   }
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric   PyRun_SimpleString(run_string.GetData());
7310b57cec5SDimitry Andric   run_string.Clear();
7320b57cec5SDimitry Andric 
7330b57cec5SDimitry Andric   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
7340b57cec5SDimitry Andric   if (sys_module_dict.IsValid()) {
735*9dba64beSDimitry Andric     lldb::FileSP top_in_sp;
736*9dba64beSDimitry Andric     lldb::StreamFileSP top_out_sp, top_err_sp;
737*9dba64beSDimitry Andric     if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
738*9dba64beSDimitry Andric       m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
739*9dba64beSDimitry Andric                                                  top_err_sp);
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric     if (on_entry_flags & Locker::NoSTDIN) {
7420b57cec5SDimitry Andric       m_saved_stdin.Reset();
7430b57cec5SDimitry Andric     } else {
744*9dba64beSDimitry Andric       if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
745*9dba64beSDimitry Andric         if (top_in_sp)
746*9dba64beSDimitry Andric           SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
7470b57cec5SDimitry Andric       }
7480b57cec5SDimitry Andric     }
7490b57cec5SDimitry Andric 
750*9dba64beSDimitry Andric     if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
751*9dba64beSDimitry Andric       if (top_out_sp)
752*9dba64beSDimitry Andric         SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w");
7530b57cec5SDimitry Andric     }
7540b57cec5SDimitry Andric 
755*9dba64beSDimitry Andric     if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
756*9dba64beSDimitry Andric       if (top_err_sp)
757*9dba64beSDimitry Andric         SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w");
7580b57cec5SDimitry Andric     }
7590b57cec5SDimitry Andric   }
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric   if (PyErr_Occurred())
7620b57cec5SDimitry Andric     PyErr_Clear();
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric   return true;
7650b57cec5SDimitry Andric }
7660b57cec5SDimitry Andric 
767*9dba64beSDimitry Andric PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
7680b57cec5SDimitry Andric   if (!m_main_module.IsValid())
769*9dba64beSDimitry Andric     m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__"));
7700b57cec5SDimitry Andric   return m_main_module;
7710b57cec5SDimitry Andric }
7720b57cec5SDimitry Andric 
7730b57cec5SDimitry Andric PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
7740b57cec5SDimitry Andric   if (m_session_dict.IsValid())
7750b57cec5SDimitry Andric     return m_session_dict;
7760b57cec5SDimitry Andric 
7770b57cec5SDimitry Andric   PythonObject &main_module = GetMainModule();
7780b57cec5SDimitry Andric   if (!main_module.IsValid())
7790b57cec5SDimitry Andric     return m_session_dict;
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric   PythonDictionary main_dict(PyRefType::Borrowed,
7820b57cec5SDimitry Andric                              PyModule_GetDict(main_module.get()));
7830b57cec5SDimitry Andric   if (!main_dict.IsValid())
7840b57cec5SDimitry Andric     return m_session_dict;
7850b57cec5SDimitry Andric 
786*9dba64beSDimitry Andric   m_session_dict = unwrapIgnoringErrors(
787*9dba64beSDimitry Andric       As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
7880b57cec5SDimitry Andric   return m_session_dict;
7890b57cec5SDimitry Andric }
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
7920b57cec5SDimitry Andric   if (m_sys_module_dict.IsValid())
7930b57cec5SDimitry Andric     return m_sys_module_dict;
794*9dba64beSDimitry Andric   PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys"));
795*9dba64beSDimitry Andric   m_sys_module_dict = sys_module.GetDictionary();
7960b57cec5SDimitry Andric   return m_sys_module_dict;
7970b57cec5SDimitry Andric }
7980b57cec5SDimitry Andric 
7990b57cec5SDimitry Andric static std::string GenerateUniqueName(const char *base_name_wanted,
8000b57cec5SDimitry Andric                                       uint32_t &functions_counter,
8010b57cec5SDimitry Andric                                       const void *name_token = nullptr) {
8020b57cec5SDimitry Andric   StreamString sstr;
8030b57cec5SDimitry Andric 
8040b57cec5SDimitry Andric   if (!base_name_wanted)
8050b57cec5SDimitry Andric     return std::string();
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric   if (!name_token)
8080b57cec5SDimitry Andric     sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
8090b57cec5SDimitry Andric   else
8100b57cec5SDimitry Andric     sstr.Printf("%s_%p", base_name_wanted, name_token);
8110b57cec5SDimitry Andric 
8120b57cec5SDimitry Andric   return sstr.GetString();
8130b57cec5SDimitry Andric }
8140b57cec5SDimitry Andric 
8150b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
8160b57cec5SDimitry Andric   if (m_run_one_line_function.IsValid())
8170b57cec5SDimitry Andric     return true;
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric   PythonObject module(PyRefType::Borrowed,
8200b57cec5SDimitry Andric                       PyImport_AddModule("lldb.embedded_interpreter"));
8210b57cec5SDimitry Andric   if (!module.IsValid())
8220b57cec5SDimitry Andric     return false;
8230b57cec5SDimitry Andric 
8240b57cec5SDimitry Andric   PythonDictionary module_dict(PyRefType::Borrowed,
8250b57cec5SDimitry Andric                                PyModule_GetDict(module.get()));
8260b57cec5SDimitry Andric   if (!module_dict.IsValid())
8270b57cec5SDimitry Andric     return false;
8280b57cec5SDimitry Andric 
8290b57cec5SDimitry Andric   m_run_one_line_function =
8300b57cec5SDimitry Andric       module_dict.GetItemForKey(PythonString("run_one_line"));
8310b57cec5SDimitry Andric   m_run_one_line_str_global =
8320b57cec5SDimitry Andric       module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
8330b57cec5SDimitry Andric   return m_run_one_line_function.IsValid();
8340b57cec5SDimitry Andric }
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric static void ReadThreadBytesReceived(void *baton, const void *src,
8370b57cec5SDimitry Andric                                     size_t src_len) {
8380b57cec5SDimitry Andric   if (src && src_len) {
8390b57cec5SDimitry Andric     Stream *strm = (Stream *)baton;
8400b57cec5SDimitry Andric     strm->Write(src, src_len);
8410b57cec5SDimitry Andric     strm->Flush();
8420b57cec5SDimitry Andric   }
8430b57cec5SDimitry Andric }
8440b57cec5SDimitry Andric 
8450b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ExecuteOneLine(
8460b57cec5SDimitry Andric     llvm::StringRef command, CommandReturnObject *result,
8470b57cec5SDimitry Andric     const ExecuteScriptOptions &options) {
8480b57cec5SDimitry Andric   std::string command_str = command.str();
8490b57cec5SDimitry Andric 
8500b57cec5SDimitry Andric   if (!m_valid_session)
8510b57cec5SDimitry Andric     return false;
8520b57cec5SDimitry Andric 
8530b57cec5SDimitry Andric   if (!command.empty()) {
8540b57cec5SDimitry Andric     // We want to call run_one_line, passing in the dictionary and the command
8550b57cec5SDimitry Andric     // string.  We cannot do this through PyRun_SimpleString here because the
8560b57cec5SDimitry Andric     // command string may contain escaped characters, and putting it inside
8570b57cec5SDimitry Andric     // another string to pass to PyRun_SimpleString messes up the escaping.  So
8580b57cec5SDimitry Andric     // we use the following more complicated method to pass the command string
8590b57cec5SDimitry Andric     // directly down to Python.
8600b57cec5SDimitry Andric     Debugger &debugger = m_debugger;
8610b57cec5SDimitry Andric 
862*9dba64beSDimitry Andric     FileSP input_file_sp;
8630b57cec5SDimitry Andric     StreamFileSP output_file_sp;
8640b57cec5SDimitry Andric     StreamFileSP error_file_sp;
8650b57cec5SDimitry Andric     Communication output_comm(
8660b57cec5SDimitry Andric         "lldb.ScriptInterpreterPythonImpl.ExecuteOneLine.comm");
8670b57cec5SDimitry Andric     bool join_read_thread = false;
8680b57cec5SDimitry Andric     if (options.GetEnableIO()) {
8690b57cec5SDimitry Andric       if (result) {
870*9dba64beSDimitry Andric         input_file_sp = debugger.GetInputFileSP();
8710b57cec5SDimitry Andric         // Set output to a temporary file so we can forward the results on to
8720b57cec5SDimitry Andric         // the result object
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric         Pipe pipe;
8750b57cec5SDimitry Andric         Status pipe_result = pipe.CreateNew(false);
8760b57cec5SDimitry Andric         if (pipe_result.Success()) {
8770b57cec5SDimitry Andric #if defined(_WIN32)
8780b57cec5SDimitry Andric           lldb::file_t read_file = pipe.GetReadNativeHandle();
8790b57cec5SDimitry Andric           pipe.ReleaseReadFileDescriptor();
8800b57cec5SDimitry Andric           std::unique_ptr<ConnectionGenericFile> conn_up(
8810b57cec5SDimitry Andric               new ConnectionGenericFile(read_file, true));
8820b57cec5SDimitry Andric #else
8830b57cec5SDimitry Andric           std::unique_ptr<ConnectionFileDescriptor> conn_up(
8840b57cec5SDimitry Andric               new ConnectionFileDescriptor(pipe.ReleaseReadFileDescriptor(),
8850b57cec5SDimitry Andric                                            true));
8860b57cec5SDimitry Andric #endif
8870b57cec5SDimitry Andric           if (conn_up->IsConnected()) {
8880b57cec5SDimitry Andric             output_comm.SetConnection(conn_up.release());
8890b57cec5SDimitry Andric             output_comm.SetReadThreadBytesReceivedCallback(
8900b57cec5SDimitry Andric                 ReadThreadBytesReceived, &result->GetOutputStream());
8910b57cec5SDimitry Andric             output_comm.StartReadThread();
8920b57cec5SDimitry Andric             join_read_thread = true;
8930b57cec5SDimitry Andric             FILE *outfile_handle =
8940b57cec5SDimitry Andric                 fdopen(pipe.ReleaseWriteFileDescriptor(), "w");
8950b57cec5SDimitry Andric             output_file_sp = std::make_shared<StreamFile>(outfile_handle, true);
8960b57cec5SDimitry Andric             error_file_sp = output_file_sp;
8970b57cec5SDimitry Andric             if (outfile_handle)
8980b57cec5SDimitry Andric               ::setbuf(outfile_handle, nullptr);
8990b57cec5SDimitry Andric 
9000b57cec5SDimitry Andric             result->SetImmediateOutputFile(
901*9dba64beSDimitry Andric                 debugger.GetOutputStream().GetFileSP());
9020b57cec5SDimitry Andric             result->SetImmediateErrorFile(
903*9dba64beSDimitry Andric                 debugger.GetErrorStream().GetFileSP());
9040b57cec5SDimitry Andric           }
9050b57cec5SDimitry Andric         }
9060b57cec5SDimitry Andric       }
9070b57cec5SDimitry Andric       if (!input_file_sp || !output_file_sp || !error_file_sp)
9080b57cec5SDimitry Andric         debugger.AdoptTopIOHandlerFilesIfInvalid(input_file_sp, output_file_sp,
9090b57cec5SDimitry Andric                                                  error_file_sp);
9100b57cec5SDimitry Andric     } else {
911*9dba64beSDimitry Andric       auto nullin = FileSystem::Instance().Open(
9120b57cec5SDimitry Andric                                   FileSpec(FileSystem::DEV_NULL),
9130b57cec5SDimitry Andric                                   File::eOpenOptionRead);
914*9dba64beSDimitry Andric       auto nullout = FileSystem::Instance().Open(
9150b57cec5SDimitry Andric                                   FileSpec(FileSystem::DEV_NULL),
9160b57cec5SDimitry Andric                                   File::eOpenOptionWrite);
917*9dba64beSDimitry Andric       if (!nullin) {
918*9dba64beSDimitry Andric         result->AppendErrorWithFormatv("failed to open /dev/null: {0}\n",
919*9dba64beSDimitry Andric                                        llvm::fmt_consume(nullin.takeError()));
920*9dba64beSDimitry Andric         return false;
921*9dba64beSDimitry Andric       }
922*9dba64beSDimitry Andric       if (!nullout) {
923*9dba64beSDimitry Andric         result->AppendErrorWithFormatv("failed to open /dev/null: {0}\n",
924*9dba64beSDimitry Andric                                        llvm::fmt_consume(nullout.takeError()));
925*9dba64beSDimitry Andric         return false;
926*9dba64beSDimitry Andric       }
927*9dba64beSDimitry Andric       input_file_sp = std::move(nullin.get());
928*9dba64beSDimitry Andric       error_file_sp = output_file_sp = std::make_shared<StreamFile>(std::move(nullout.get()));
9290b57cec5SDimitry Andric     }
9300b57cec5SDimitry Andric 
9310b57cec5SDimitry Andric     bool success = false;
9320b57cec5SDimitry Andric     {
9330b57cec5SDimitry Andric       // WARNING!  It's imperative that this RAII scope be as tight as
9340b57cec5SDimitry Andric       // possible. In particular, the scope must end *before* we try to join
9350b57cec5SDimitry Andric       // the read thread.  The reason for this is that a pre-requisite for
9360b57cec5SDimitry Andric       // joining the read thread is that we close the write handle (to break
9370b57cec5SDimitry Andric       // the pipe and cause it to wake up and exit).  But acquiring the GIL as
9380b57cec5SDimitry Andric       // below will redirect Python's stdio to use this same handle.  If we
9390b57cec5SDimitry Andric       // close the handle while Python is still using it, bad things will
9400b57cec5SDimitry Andric       // happen.
9410b57cec5SDimitry Andric       Locker locker(
9420b57cec5SDimitry Andric           this,
9430b57cec5SDimitry Andric           Locker::AcquireLock | Locker::InitSession |
9440b57cec5SDimitry Andric               (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
9450b57cec5SDimitry Andric               ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
946*9dba64beSDimitry Andric           Locker::FreeAcquiredLock | Locker::TearDownSession, input_file_sp,
947*9dba64beSDimitry Andric           output_file_sp->GetFileSP(), error_file_sp->GetFileSP());
9480b57cec5SDimitry Andric 
9490b57cec5SDimitry Andric       // Find the correct script interpreter dictionary in the main module.
9500b57cec5SDimitry Andric       PythonDictionary &session_dict = GetSessionDictionary();
9510b57cec5SDimitry Andric       if (session_dict.IsValid()) {
9520b57cec5SDimitry Andric         if (GetEmbeddedInterpreterModuleObjects()) {
9530b57cec5SDimitry Andric           if (PyCallable_Check(m_run_one_line_function.get())) {
9540b57cec5SDimitry Andric             PythonObject pargs(
9550b57cec5SDimitry Andric                 PyRefType::Owned,
9560b57cec5SDimitry Andric                 Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
9570b57cec5SDimitry Andric             if (pargs.IsValid()) {
9580b57cec5SDimitry Andric               PythonObject return_value(
9590b57cec5SDimitry Andric                   PyRefType::Owned,
9600b57cec5SDimitry Andric                   PyObject_CallObject(m_run_one_line_function.get(),
9610b57cec5SDimitry Andric                                       pargs.get()));
9620b57cec5SDimitry Andric               if (return_value.IsValid())
9630b57cec5SDimitry Andric                 success = true;
9640b57cec5SDimitry Andric               else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
9650b57cec5SDimitry Andric                 PyErr_Print();
9660b57cec5SDimitry Andric                 PyErr_Clear();
9670b57cec5SDimitry Andric               }
9680b57cec5SDimitry Andric             }
9690b57cec5SDimitry Andric           }
9700b57cec5SDimitry Andric         }
9710b57cec5SDimitry Andric       }
9720b57cec5SDimitry Andric 
9730b57cec5SDimitry Andric       // Flush our output and error file handles
974*9dba64beSDimitry Andric       output_file_sp->Flush();
975*9dba64beSDimitry Andric       error_file_sp->Flush();
9760b57cec5SDimitry Andric     }
9770b57cec5SDimitry Andric 
9780b57cec5SDimitry Andric     if (join_read_thread) {
9790b57cec5SDimitry Andric       // Close the write end of the pipe since we are done with our one line
9800b57cec5SDimitry Andric       // script. This should cause the read thread that output_comm is using to
9810b57cec5SDimitry Andric       // exit
9820b57cec5SDimitry Andric       output_file_sp->GetFile().Close();
9830b57cec5SDimitry Andric       // The close above should cause this thread to exit when it gets to the
9840b57cec5SDimitry Andric       // end of file, so let it get all its data
9850b57cec5SDimitry Andric       output_comm.JoinReadThread();
9860b57cec5SDimitry Andric       // Now we can close the read end of the pipe
9870b57cec5SDimitry Andric       output_comm.Disconnect();
9880b57cec5SDimitry Andric     }
9890b57cec5SDimitry Andric 
9900b57cec5SDimitry Andric     if (success)
9910b57cec5SDimitry Andric       return true;
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric     // The one-liner failed.  Append the error message.
9940b57cec5SDimitry Andric     if (result) {
9950b57cec5SDimitry Andric       result->AppendErrorWithFormat(
9960b57cec5SDimitry Andric           "python failed attempting to evaluate '%s'\n", command_str.c_str());
9970b57cec5SDimitry Andric     }
9980b57cec5SDimitry Andric     return false;
9990b57cec5SDimitry Andric   }
10000b57cec5SDimitry Andric 
10010b57cec5SDimitry Andric   if (result)
10020b57cec5SDimitry Andric     result->AppendError("empty command passed to python\n");
10030b57cec5SDimitry Andric   return false;
10040b57cec5SDimitry Andric }
10050b57cec5SDimitry Andric 
10060b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
10070b57cec5SDimitry Andric   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
10080b57cec5SDimitry Andric   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
10090b57cec5SDimitry Andric 
10100b57cec5SDimitry Andric   Debugger &debugger = m_debugger;
10110b57cec5SDimitry Andric 
10120b57cec5SDimitry Andric   // At the moment, the only time the debugger does not have an input file
10130b57cec5SDimitry Andric   // handle is when this is called directly from Python, in which case it is
10140b57cec5SDimitry Andric   // both dangerous and unnecessary (not to mention confusing) to try to embed
10150b57cec5SDimitry Andric   // a running interpreter loop inside the already running Python interpreter
10160b57cec5SDimitry Andric   // loop, so we won't do it.
10170b57cec5SDimitry Andric 
1018*9dba64beSDimitry Andric   if (!debugger.GetInputFile().IsValid())
10190b57cec5SDimitry Andric     return;
10200b57cec5SDimitry Andric 
10210b57cec5SDimitry Andric   IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
10220b57cec5SDimitry Andric   if (io_handler_sp) {
10230b57cec5SDimitry Andric     debugger.PushIOHandler(io_handler_sp);
10240b57cec5SDimitry Andric   }
10250b57cec5SDimitry Andric }
10260b57cec5SDimitry Andric 
10270b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Interrupt() {
10280b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
10290b57cec5SDimitry Andric 
10300b57cec5SDimitry Andric   if (IsExecutingPython()) {
10310b57cec5SDimitry Andric     PyThreadState *state = PyThreadState_GET();
10320b57cec5SDimitry Andric     if (!state)
10330b57cec5SDimitry Andric       state = GetThreadState();
10340b57cec5SDimitry Andric     if (state) {
10350b57cec5SDimitry Andric       long tid = state->thread_id;
10360b57cec5SDimitry Andric       PyThreadState_Swap(state);
10370b57cec5SDimitry Andric       int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
1038*9dba64beSDimitry Andric       LLDB_LOGF(log,
1039*9dba64beSDimitry Andric                 "ScriptInterpreterPythonImpl::Interrupt() sending "
10400b57cec5SDimitry Andric                 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
10410b57cec5SDimitry Andric                 tid, num_threads);
10420b57cec5SDimitry Andric       return true;
10430b57cec5SDimitry Andric     }
10440b57cec5SDimitry Andric   }
1045*9dba64beSDimitry Andric   LLDB_LOGF(log,
10460b57cec5SDimitry Andric             "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
10470b57cec5SDimitry Andric             "can't interrupt");
10480b57cec5SDimitry Andric   return false;
10490b57cec5SDimitry Andric }
1050*9dba64beSDimitry Andric 
10510b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
10520b57cec5SDimitry Andric     llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
10530b57cec5SDimitry Andric     void *ret_value, const ExecuteScriptOptions &options) {
10540b57cec5SDimitry Andric 
10550b57cec5SDimitry Andric   Locker locker(this,
10560b57cec5SDimitry Andric                 Locker::AcquireLock | Locker::InitSession |
10570b57cec5SDimitry Andric                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
10580b57cec5SDimitry Andric                     Locker::NoSTDIN,
10590b57cec5SDimitry Andric                 Locker::FreeAcquiredLock | Locker::TearDownSession);
10600b57cec5SDimitry Andric 
1061*9dba64beSDimitry Andric   PythonModule &main_module = GetMainModule();
1062*9dba64beSDimitry Andric   PythonDictionary globals = main_module.GetDictionary();
10630b57cec5SDimitry Andric 
10640b57cec5SDimitry Andric   PythonDictionary locals = GetSessionDictionary();
1065*9dba64beSDimitry Andric   if (!locals.IsValid())
1066*9dba64beSDimitry Andric     locals = unwrapIgnoringErrors(
1067*9dba64beSDimitry Andric         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
10680b57cec5SDimitry Andric   if (!locals.IsValid())
10690b57cec5SDimitry Andric     locals = globals;
10700b57cec5SDimitry Andric 
1071*9dba64beSDimitry Andric   Expected<PythonObject> maybe_py_return =
1072*9dba64beSDimitry Andric       runStringOneLine(in_string, globals, locals);
10730b57cec5SDimitry Andric 
1074*9dba64beSDimitry Andric   if (!maybe_py_return) {
1075*9dba64beSDimitry Andric     llvm::handleAllErrors(
1076*9dba64beSDimitry Andric         maybe_py_return.takeError(),
1077*9dba64beSDimitry Andric         [&](PythonException &E) {
1078*9dba64beSDimitry Andric           E.Restore();
1079*9dba64beSDimitry Andric           if (options.GetMaskoutErrors()) {
1080*9dba64beSDimitry Andric             if (E.Matches(PyExc_SyntaxError)) {
1081*9dba64beSDimitry Andric               PyErr_Print();
10820b57cec5SDimitry Andric             }
1083*9dba64beSDimitry Andric             PyErr_Clear();
1084*9dba64beSDimitry Andric           }
1085*9dba64beSDimitry Andric         },
1086*9dba64beSDimitry Andric         [](const llvm::ErrorInfoBase &E) {});
1087*9dba64beSDimitry Andric     return false;
10880b57cec5SDimitry Andric   }
10890b57cec5SDimitry Andric 
1090*9dba64beSDimitry Andric   PythonObject py_return = std::move(maybe_py_return.get());
1091*9dba64beSDimitry Andric   assert(py_return.IsValid());
1092*9dba64beSDimitry Andric 
10930b57cec5SDimitry Andric   switch (return_type) {
10940b57cec5SDimitry Andric   case eScriptReturnTypeCharPtr: // "char *"
10950b57cec5SDimitry Andric   {
10960b57cec5SDimitry Andric     const char format[3] = "s#";
1097*9dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
10980b57cec5SDimitry Andric   }
10990b57cec5SDimitry Andric   case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
11000b57cec5SDimitry Andric                                        // Py_None
11010b57cec5SDimitry Andric   {
11020b57cec5SDimitry Andric     const char format[3] = "z";
1103*9dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
11040b57cec5SDimitry Andric   }
11050b57cec5SDimitry Andric   case eScriptReturnTypeBool: {
11060b57cec5SDimitry Andric     const char format[2] = "b";
1107*9dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
11080b57cec5SDimitry Andric   }
11090b57cec5SDimitry Andric   case eScriptReturnTypeShortInt: {
11100b57cec5SDimitry Andric     const char format[2] = "h";
1111*9dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (short *)ret_value);
11120b57cec5SDimitry Andric   }
11130b57cec5SDimitry Andric   case eScriptReturnTypeShortIntUnsigned: {
11140b57cec5SDimitry Andric     const char format[2] = "H";
1115*9dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
11160b57cec5SDimitry Andric   }
11170b57cec5SDimitry Andric   case eScriptReturnTypeInt: {
11180b57cec5SDimitry Andric     const char format[2] = "i";
1119*9dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (int *)ret_value);
11200b57cec5SDimitry Andric   }
11210b57cec5SDimitry Andric   case eScriptReturnTypeIntUnsigned: {
11220b57cec5SDimitry Andric     const char format[2] = "I";
1123*9dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
11240b57cec5SDimitry Andric   }
11250b57cec5SDimitry Andric   case eScriptReturnTypeLongInt: {
11260b57cec5SDimitry Andric     const char format[2] = "l";
1127*9dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (long *)ret_value);
11280b57cec5SDimitry Andric   }
11290b57cec5SDimitry Andric   case eScriptReturnTypeLongIntUnsigned: {
11300b57cec5SDimitry Andric     const char format[2] = "k";
1131*9dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
11320b57cec5SDimitry Andric   }
11330b57cec5SDimitry Andric   case eScriptReturnTypeLongLong: {
11340b57cec5SDimitry Andric     const char format[2] = "L";
1135*9dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
11360b57cec5SDimitry Andric   }
11370b57cec5SDimitry Andric   case eScriptReturnTypeLongLongUnsigned: {
11380b57cec5SDimitry Andric     const char format[2] = "K";
1139*9dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format,
1140*9dba64beSDimitry Andric                        (unsigned long long *)ret_value);
11410b57cec5SDimitry Andric   }
11420b57cec5SDimitry Andric   case eScriptReturnTypeFloat: {
11430b57cec5SDimitry Andric     const char format[2] = "f";
1144*9dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (float *)ret_value);
11450b57cec5SDimitry Andric   }
11460b57cec5SDimitry Andric   case eScriptReturnTypeDouble: {
11470b57cec5SDimitry Andric     const char format[2] = "d";
1148*9dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (double *)ret_value);
11490b57cec5SDimitry Andric   }
11500b57cec5SDimitry Andric   case eScriptReturnTypeChar: {
11510b57cec5SDimitry Andric     const char format[2] = "c";
1152*9dba64beSDimitry Andric     return PyArg_Parse(py_return.get(), format, (char *)ret_value);
11530b57cec5SDimitry Andric   }
11540b57cec5SDimitry Andric   case eScriptReturnTypeOpaqueObject: {
1155*9dba64beSDimitry Andric     *((PyObject **)ret_value) = py_return.release();
1156*9dba64beSDimitry Andric     return true;
11570b57cec5SDimitry Andric   }
11580b57cec5SDimitry Andric   }
11590b57cec5SDimitry Andric }
11600b57cec5SDimitry Andric 
11610b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
11620b57cec5SDimitry Andric     const char *in_string, const ExecuteScriptOptions &options) {
1163*9dba64beSDimitry Andric 
1164*9dba64beSDimitry Andric   if (in_string == nullptr)
1165*9dba64beSDimitry Andric     return Status();
11660b57cec5SDimitry Andric 
11670b57cec5SDimitry Andric   Locker locker(this,
11680b57cec5SDimitry Andric                 Locker::AcquireLock | Locker::InitSession |
11690b57cec5SDimitry Andric                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
11700b57cec5SDimitry Andric                     Locker::NoSTDIN,
11710b57cec5SDimitry Andric                 Locker::FreeAcquiredLock | Locker::TearDownSession);
11720b57cec5SDimitry Andric 
1173*9dba64beSDimitry Andric   PythonModule &main_module = GetMainModule();
1174*9dba64beSDimitry Andric   PythonDictionary globals = main_module.GetDictionary();
11750b57cec5SDimitry Andric 
11760b57cec5SDimitry Andric   PythonDictionary locals = GetSessionDictionary();
11770b57cec5SDimitry Andric   if (!locals.IsValid())
1178*9dba64beSDimitry Andric     locals = unwrapIgnoringErrors(
1179*9dba64beSDimitry Andric         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
11800b57cec5SDimitry Andric   if (!locals.IsValid())
11810b57cec5SDimitry Andric     locals = globals;
11820b57cec5SDimitry Andric 
1183*9dba64beSDimitry Andric   Expected<PythonObject> return_value =
1184*9dba64beSDimitry Andric       runStringMultiLine(in_string, globals, locals);
11850b57cec5SDimitry Andric 
1186*9dba64beSDimitry Andric   if (!return_value) {
1187*9dba64beSDimitry Andric     llvm::Error error =
1188*9dba64beSDimitry Andric         llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
1189*9dba64beSDimitry Andric           llvm::Error error = llvm::createStringError(
1190*9dba64beSDimitry Andric               llvm::inconvertibleErrorCode(), E.ReadBacktrace());
1191*9dba64beSDimitry Andric           if (!options.GetMaskoutErrors())
1192*9dba64beSDimitry Andric             E.Restore();
11930b57cec5SDimitry Andric           return error;
1194*9dba64beSDimitry Andric         });
1195*9dba64beSDimitry Andric     return Status(std::move(error));
1196*9dba64beSDimitry Andric   }
1197*9dba64beSDimitry Andric 
1198*9dba64beSDimitry Andric   return Status();
11990b57cec5SDimitry Andric }
12000b57cec5SDimitry Andric 
12010b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
12020b57cec5SDimitry Andric     std::vector<BreakpointOptions *> &bp_options_vec,
12030b57cec5SDimitry Andric     CommandReturnObject &result) {
12040b57cec5SDimitry Andric   m_active_io_handler = eIOHandlerBreakpoint;
12050b57cec5SDimitry Andric   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
12060b57cec5SDimitry Andric       "    ", *this, true, &bp_options_vec);
12070b57cec5SDimitry Andric }
12080b57cec5SDimitry Andric 
12090b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
12100b57cec5SDimitry Andric     WatchpointOptions *wp_options, CommandReturnObject &result) {
12110b57cec5SDimitry Andric   m_active_io_handler = eIOHandlerWatchpoint;
12120b57cec5SDimitry Andric   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
12130b57cec5SDimitry Andric       "    ", *this, true, wp_options);
12140b57cec5SDimitry Andric }
12150b57cec5SDimitry Andric 
12160b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
12170b57cec5SDimitry Andric     BreakpointOptions *bp_options, const char *function_name) {
12180b57cec5SDimitry Andric   // For now just cons up a oneliner that calls the provided function.
12190b57cec5SDimitry Andric   std::string oneliner("return ");
12200b57cec5SDimitry Andric   oneliner += function_name;
12210b57cec5SDimitry Andric   oneliner += "(frame, bp_loc, internal_dict)";
12220b57cec5SDimitry Andric   m_debugger.GetScriptInterpreter()->SetBreakpointCommandCallback(
12230b57cec5SDimitry Andric       bp_options, oneliner.c_str());
12240b57cec5SDimitry Andric }
12250b57cec5SDimitry Andric 
12260b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
12270b57cec5SDimitry Andric     BreakpointOptions *bp_options,
12280b57cec5SDimitry Andric     std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
12290b57cec5SDimitry Andric   Status error;
12300b57cec5SDimitry Andric   error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
12310b57cec5SDimitry Andric                                                 cmd_data_up->script_source);
12320b57cec5SDimitry Andric   if (error.Fail()) {
12330b57cec5SDimitry Andric     return error;
12340b57cec5SDimitry Andric   }
12350b57cec5SDimitry Andric   auto baton_sp =
12360b57cec5SDimitry Andric       std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
12370b57cec5SDimitry Andric   bp_options->SetCallback(
12380b57cec5SDimitry Andric       ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
12390b57cec5SDimitry Andric   return error;
12400b57cec5SDimitry Andric }
12410b57cec5SDimitry Andric 
12420b57cec5SDimitry Andric // Set a Python one-liner as the callback for the breakpoint.
12430b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
12440b57cec5SDimitry Andric     BreakpointOptions *bp_options, const char *command_body_text) {
1245*9dba64beSDimitry Andric   auto data_up = std::make_unique<CommandDataPython>();
12460b57cec5SDimitry Andric 
12470b57cec5SDimitry Andric   // Split the command_body_text into lines, and pass that to
12480b57cec5SDimitry Andric   // GenerateBreakpointCommandCallbackData.  That will wrap the body in an
12490b57cec5SDimitry Andric   // auto-generated function, and return the function name in script_source.
12500b57cec5SDimitry Andric   // That is what the callback will actually invoke.
12510b57cec5SDimitry Andric 
12520b57cec5SDimitry Andric   data_up->user_source.SplitIntoLines(command_body_text);
12530b57cec5SDimitry Andric   Status error = GenerateBreakpointCommandCallbackData(data_up->user_source,
12540b57cec5SDimitry Andric                                                        data_up->script_source);
12550b57cec5SDimitry Andric   if (error.Success()) {
12560b57cec5SDimitry Andric     auto baton_sp =
12570b57cec5SDimitry Andric         std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
12580b57cec5SDimitry Andric     bp_options->SetCallback(
12590b57cec5SDimitry Andric         ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
12600b57cec5SDimitry Andric     return error;
12610b57cec5SDimitry Andric   } else
12620b57cec5SDimitry Andric     return error;
12630b57cec5SDimitry Andric }
12640b57cec5SDimitry Andric 
12650b57cec5SDimitry Andric // Set a Python one-liner as the callback for the watchpoint.
12660b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
12670b57cec5SDimitry Andric     WatchpointOptions *wp_options, const char *oneliner) {
1268*9dba64beSDimitry Andric   auto data_up = std::make_unique<WatchpointOptions::CommandData>();
12690b57cec5SDimitry Andric 
12700b57cec5SDimitry Andric   // It's necessary to set both user_source and script_source to the oneliner.
12710b57cec5SDimitry Andric   // The former is used to generate callback description (as in watchpoint
12720b57cec5SDimitry Andric   // command list) while the latter is used for Python to interpret during the
12730b57cec5SDimitry Andric   // actual callback.
12740b57cec5SDimitry Andric 
12750b57cec5SDimitry Andric   data_up->user_source.AppendString(oneliner);
12760b57cec5SDimitry Andric   data_up->script_source.assign(oneliner);
12770b57cec5SDimitry Andric 
12780b57cec5SDimitry Andric   if (GenerateWatchpointCommandCallbackData(data_up->user_source,
12790b57cec5SDimitry Andric                                             data_up->script_source)) {
12800b57cec5SDimitry Andric     auto baton_sp =
12810b57cec5SDimitry Andric         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
12820b57cec5SDimitry Andric     wp_options->SetCallback(
12830b57cec5SDimitry Andric         ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
12840b57cec5SDimitry Andric   }
12850b57cec5SDimitry Andric 
12860b57cec5SDimitry Andric   return;
12870b57cec5SDimitry Andric }
12880b57cec5SDimitry Andric 
12890b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
12900b57cec5SDimitry Andric     StringList &function_def) {
12910b57cec5SDimitry Andric   // Convert StringList to one long, newline delimited, const char *.
12920b57cec5SDimitry Andric   std::string function_def_string(function_def.CopyList());
12930b57cec5SDimitry Andric 
12940b57cec5SDimitry Andric   Status error = ExecuteMultipleLines(
12950b57cec5SDimitry Andric       function_def_string.c_str(),
12960b57cec5SDimitry Andric       ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false));
12970b57cec5SDimitry Andric   return error;
12980b57cec5SDimitry Andric }
12990b57cec5SDimitry Andric 
13000b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature,
13010b57cec5SDimitry Andric                                                      const StringList &input) {
13020b57cec5SDimitry Andric   Status error;
13030b57cec5SDimitry Andric   int num_lines = input.GetSize();
13040b57cec5SDimitry Andric   if (num_lines == 0) {
13050b57cec5SDimitry Andric     error.SetErrorString("No input data.");
13060b57cec5SDimitry Andric     return error;
13070b57cec5SDimitry Andric   }
13080b57cec5SDimitry Andric 
13090b57cec5SDimitry Andric   if (!signature || *signature == 0) {
13100b57cec5SDimitry Andric     error.SetErrorString("No output function name.");
13110b57cec5SDimitry Andric     return error;
13120b57cec5SDimitry Andric   }
13130b57cec5SDimitry Andric 
13140b57cec5SDimitry Andric   StreamString sstr;
13150b57cec5SDimitry Andric   StringList auto_generated_function;
13160b57cec5SDimitry Andric   auto_generated_function.AppendString(signature);
13170b57cec5SDimitry Andric   auto_generated_function.AppendString(
13180b57cec5SDimitry Andric       "     global_dict = globals()"); // Grab the global dictionary
13190b57cec5SDimitry Andric   auto_generated_function.AppendString(
13200b57cec5SDimitry Andric       "     new_keys = internal_dict.keys()"); // Make a list of keys in the
13210b57cec5SDimitry Andric                                                // session dict
13220b57cec5SDimitry Andric   auto_generated_function.AppendString(
13230b57cec5SDimitry Andric       "     old_keys = global_dict.keys()"); // Save list of keys in global dict
13240b57cec5SDimitry Andric   auto_generated_function.AppendString(
13250b57cec5SDimitry Andric       "     global_dict.update (internal_dict)"); // Add the session dictionary
13260b57cec5SDimitry Andric                                                   // to the
13270b57cec5SDimitry Andric   // global dictionary.
13280b57cec5SDimitry Andric 
13290b57cec5SDimitry Andric   // Wrap everything up inside the function, increasing the indentation.
13300b57cec5SDimitry Andric 
13310b57cec5SDimitry Andric   auto_generated_function.AppendString("     if True:");
13320b57cec5SDimitry Andric   for (int i = 0; i < num_lines; ++i) {
13330b57cec5SDimitry Andric     sstr.Clear();
13340b57cec5SDimitry Andric     sstr.Printf("       %s", input.GetStringAtIndex(i));
13350b57cec5SDimitry Andric     auto_generated_function.AppendString(sstr.GetData());
13360b57cec5SDimitry Andric   }
13370b57cec5SDimitry Andric   auto_generated_function.AppendString(
13380b57cec5SDimitry Andric       "     for key in new_keys:"); // Iterate over all the keys from session
13390b57cec5SDimitry Andric                                     // dict
13400b57cec5SDimitry Andric   auto_generated_function.AppendString(
13410b57cec5SDimitry Andric       "         internal_dict[key] = global_dict[key]"); // Update session dict
13420b57cec5SDimitry Andric                                                          // values
13430b57cec5SDimitry Andric   auto_generated_function.AppendString(
13440b57cec5SDimitry Andric       "         if key not in old_keys:"); // If key was not originally in
13450b57cec5SDimitry Andric                                            // global dict
13460b57cec5SDimitry Andric   auto_generated_function.AppendString(
13470b57cec5SDimitry Andric       "             del global_dict[key]"); //  ...then remove key/value from
13480b57cec5SDimitry Andric                                             //  global dict
13490b57cec5SDimitry Andric 
13500b57cec5SDimitry Andric   // Verify that the results are valid Python.
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric   error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
13530b57cec5SDimitry Andric 
13540b57cec5SDimitry Andric   return error;
13550b57cec5SDimitry Andric }
13560b57cec5SDimitry Andric 
13570b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
13580b57cec5SDimitry Andric     StringList &user_input, std::string &output, const void *name_token) {
13590b57cec5SDimitry Andric   static uint32_t num_created_functions = 0;
13600b57cec5SDimitry Andric   user_input.RemoveBlankLines();
13610b57cec5SDimitry Andric   StreamString sstr;
13620b57cec5SDimitry Andric 
13630b57cec5SDimitry Andric   // Check to see if we have any data; if not, just return.
13640b57cec5SDimitry Andric   if (user_input.GetSize() == 0)
13650b57cec5SDimitry Andric     return false;
13660b57cec5SDimitry Andric 
13670b57cec5SDimitry Andric   // Take what the user wrote, wrap it all up inside one big auto-generated
13680b57cec5SDimitry Andric   // Python function, passing in the ValueObject as parameter to the function.
13690b57cec5SDimitry Andric 
13700b57cec5SDimitry Andric   std::string auto_generated_function_name(
13710b57cec5SDimitry Andric       GenerateUniqueName("lldb_autogen_python_type_print_func",
13720b57cec5SDimitry Andric                          num_created_functions, name_token));
13730b57cec5SDimitry Andric   sstr.Printf("def %s (valobj, internal_dict):",
13740b57cec5SDimitry Andric               auto_generated_function_name.c_str());
13750b57cec5SDimitry Andric 
13760b57cec5SDimitry Andric   if (!GenerateFunction(sstr.GetData(), user_input).Success())
13770b57cec5SDimitry Andric     return false;
13780b57cec5SDimitry Andric 
13790b57cec5SDimitry Andric   // Store the name of the auto-generated function to be called.
13800b57cec5SDimitry Andric   output.assign(auto_generated_function_name);
13810b57cec5SDimitry Andric   return true;
13820b57cec5SDimitry Andric }
13830b57cec5SDimitry Andric 
13840b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
13850b57cec5SDimitry Andric     StringList &user_input, std::string &output) {
13860b57cec5SDimitry Andric   static uint32_t num_created_functions = 0;
13870b57cec5SDimitry Andric   user_input.RemoveBlankLines();
13880b57cec5SDimitry Andric   StreamString sstr;
13890b57cec5SDimitry Andric 
13900b57cec5SDimitry Andric   // Check to see if we have any data; if not, just return.
13910b57cec5SDimitry Andric   if (user_input.GetSize() == 0)
13920b57cec5SDimitry Andric     return false;
13930b57cec5SDimitry Andric 
13940b57cec5SDimitry Andric   std::string auto_generated_function_name(GenerateUniqueName(
13950b57cec5SDimitry Andric       "lldb_autogen_python_cmd_alias_func", num_created_functions));
13960b57cec5SDimitry Andric 
13970b57cec5SDimitry Andric   sstr.Printf("def %s (debugger, args, result, internal_dict):",
13980b57cec5SDimitry Andric               auto_generated_function_name.c_str());
13990b57cec5SDimitry Andric 
14000b57cec5SDimitry Andric   if (!GenerateFunction(sstr.GetData(), user_input).Success())
14010b57cec5SDimitry Andric     return false;
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric   // Store the name of the auto-generated function to be called.
14040b57cec5SDimitry Andric   output.assign(auto_generated_function_name);
14050b57cec5SDimitry Andric   return true;
14060b57cec5SDimitry Andric }
14070b57cec5SDimitry Andric 
14080b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
14090b57cec5SDimitry Andric     StringList &user_input, std::string &output, const void *name_token) {
14100b57cec5SDimitry Andric   static uint32_t num_created_classes = 0;
14110b57cec5SDimitry Andric   user_input.RemoveBlankLines();
14120b57cec5SDimitry Andric   int num_lines = user_input.GetSize();
14130b57cec5SDimitry Andric   StreamString sstr;
14140b57cec5SDimitry Andric 
14150b57cec5SDimitry Andric   // Check to see if we have any data; if not, just return.
14160b57cec5SDimitry Andric   if (user_input.GetSize() == 0)
14170b57cec5SDimitry Andric     return false;
14180b57cec5SDimitry Andric 
14190b57cec5SDimitry Andric   // Wrap all user input into a Python class
14200b57cec5SDimitry Andric 
14210b57cec5SDimitry Andric   std::string auto_generated_class_name(GenerateUniqueName(
14220b57cec5SDimitry Andric       "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
14230b57cec5SDimitry Andric 
14240b57cec5SDimitry Andric   StringList auto_generated_class;
14250b57cec5SDimitry Andric 
14260b57cec5SDimitry Andric   // Create the function name & definition string.
14270b57cec5SDimitry Andric 
14280b57cec5SDimitry Andric   sstr.Printf("class %s:", auto_generated_class_name.c_str());
14290b57cec5SDimitry Andric   auto_generated_class.AppendString(sstr.GetString());
14300b57cec5SDimitry Andric 
14310b57cec5SDimitry Andric   // Wrap everything up inside the class, increasing the indentation. we don't
14320b57cec5SDimitry Andric   // need to play any fancy indentation tricks here because there is no
14330b57cec5SDimitry Andric   // surrounding code whose indentation we need to honor
14340b57cec5SDimitry Andric   for (int i = 0; i < num_lines; ++i) {
14350b57cec5SDimitry Andric     sstr.Clear();
14360b57cec5SDimitry Andric     sstr.Printf("     %s", user_input.GetStringAtIndex(i));
14370b57cec5SDimitry Andric     auto_generated_class.AppendString(sstr.GetString());
14380b57cec5SDimitry Andric   }
14390b57cec5SDimitry Andric 
14400b57cec5SDimitry Andric   // Verify that the results are valid Python. (even though the method is
14410b57cec5SDimitry Andric   // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
14420b57cec5SDimitry Andric   // (TODO: rename that method to ExportDefinitionToInterpreter)
14430b57cec5SDimitry Andric   if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
14440b57cec5SDimitry Andric     return false;
14450b57cec5SDimitry Andric 
14460b57cec5SDimitry Andric   // Store the name of the auto-generated class
14470b57cec5SDimitry Andric 
14480b57cec5SDimitry Andric   output.assign(auto_generated_class_name);
14490b57cec5SDimitry Andric   return true;
14500b57cec5SDimitry Andric }
14510b57cec5SDimitry Andric 
14520b57cec5SDimitry Andric StructuredData::GenericSP
14530b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
14540b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
14550b57cec5SDimitry Andric     return StructuredData::GenericSP();
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric   void *ret_val;
14580b57cec5SDimitry Andric 
14590b57cec5SDimitry Andric   {
14600b57cec5SDimitry Andric     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
14610b57cec5SDimitry Andric                    Locker::FreeLock);
14620b57cec5SDimitry Andric     ret_val = LLDBSWIGPython_CreateFrameRecognizer(class_name,
14630b57cec5SDimitry Andric                                                    m_dictionary_name.c_str());
14640b57cec5SDimitry Andric   }
14650b57cec5SDimitry Andric 
14660b57cec5SDimitry Andric   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
14670b57cec5SDimitry Andric }
14680b57cec5SDimitry Andric 
14690b57cec5SDimitry Andric lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
14700b57cec5SDimitry Andric     const StructuredData::ObjectSP &os_plugin_object_sp,
14710b57cec5SDimitry Andric     lldb::StackFrameSP frame_sp) {
14720b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
14730b57cec5SDimitry Andric 
14740b57cec5SDimitry Andric   if (!os_plugin_object_sp)
14750b57cec5SDimitry Andric     return ValueObjectListSP();
14760b57cec5SDimitry Andric 
14770b57cec5SDimitry Andric   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
14780b57cec5SDimitry Andric   if (!generic)
14790b57cec5SDimitry Andric     return nullptr;
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
14820b57cec5SDimitry Andric                            (PyObject *)generic->GetValue());
14830b57cec5SDimitry Andric 
14840b57cec5SDimitry Andric   if (!implementor.IsAllocated())
14850b57cec5SDimitry Andric     return ValueObjectListSP();
14860b57cec5SDimitry Andric 
14870b57cec5SDimitry Andric   PythonObject py_return(PyRefType::Owned,
14880b57cec5SDimitry Andric                          (PyObject *)LLDBSwigPython_GetRecognizedArguments(
14890b57cec5SDimitry Andric                              implementor.get(), frame_sp));
14900b57cec5SDimitry Andric 
14910b57cec5SDimitry Andric   // if it fails, print the error but otherwise go on
14920b57cec5SDimitry Andric   if (PyErr_Occurred()) {
14930b57cec5SDimitry Andric     PyErr_Print();
14940b57cec5SDimitry Andric     PyErr_Clear();
14950b57cec5SDimitry Andric   }
14960b57cec5SDimitry Andric   if (py_return.get()) {
14970b57cec5SDimitry Andric     PythonList result_list(PyRefType::Borrowed, py_return.get());
14980b57cec5SDimitry Andric     ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
14990b57cec5SDimitry Andric     for (size_t i = 0; i < result_list.GetSize(); i++) {
15000b57cec5SDimitry Andric       PyObject *item = result_list.GetItemAtIndex(i).get();
15010b57cec5SDimitry Andric       lldb::SBValue *sb_value_ptr =
15020b57cec5SDimitry Andric           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
15030b57cec5SDimitry Andric       auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
15040b57cec5SDimitry Andric       if (valobj_sp)
15050b57cec5SDimitry Andric         result->Append(valobj_sp);
15060b57cec5SDimitry Andric     }
15070b57cec5SDimitry Andric     return result;
15080b57cec5SDimitry Andric   }
15090b57cec5SDimitry Andric   return ValueObjectListSP();
15100b57cec5SDimitry Andric }
15110b57cec5SDimitry Andric 
15120b57cec5SDimitry Andric StructuredData::GenericSP
15130b57cec5SDimitry Andric ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject(
15140b57cec5SDimitry Andric     const char *class_name, lldb::ProcessSP process_sp) {
15150b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
15160b57cec5SDimitry Andric     return StructuredData::GenericSP();
15170b57cec5SDimitry Andric 
15180b57cec5SDimitry Andric   if (!process_sp)
15190b57cec5SDimitry Andric     return StructuredData::GenericSP();
15200b57cec5SDimitry Andric 
15210b57cec5SDimitry Andric   void *ret_val;
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric   {
15240b57cec5SDimitry Andric     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
15250b57cec5SDimitry Andric                    Locker::FreeLock);
15260b57cec5SDimitry Andric     ret_val = LLDBSWIGPythonCreateOSPlugin(
15270b57cec5SDimitry Andric         class_name, m_dictionary_name.c_str(), process_sp);
15280b57cec5SDimitry Andric   }
15290b57cec5SDimitry Andric 
15300b57cec5SDimitry Andric   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
15310b57cec5SDimitry Andric }
15320b57cec5SDimitry Andric 
15330b57cec5SDimitry Andric StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo(
15340b57cec5SDimitry Andric     StructuredData::ObjectSP os_plugin_object_sp) {
15350b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
15360b57cec5SDimitry Andric 
15370b57cec5SDimitry Andric   static char callee_name[] = "get_register_info";
15380b57cec5SDimitry Andric 
15390b57cec5SDimitry Andric   if (!os_plugin_object_sp)
15400b57cec5SDimitry Andric     return StructuredData::DictionarySP();
15410b57cec5SDimitry Andric 
15420b57cec5SDimitry Andric   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
15430b57cec5SDimitry Andric   if (!generic)
15440b57cec5SDimitry Andric     return nullptr;
15450b57cec5SDimitry Andric 
15460b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
15470b57cec5SDimitry Andric                            (PyObject *)generic->GetValue());
15480b57cec5SDimitry Andric 
15490b57cec5SDimitry Andric   if (!implementor.IsAllocated())
15500b57cec5SDimitry Andric     return StructuredData::DictionarySP();
15510b57cec5SDimitry Andric 
15520b57cec5SDimitry Andric   PythonObject pmeth(PyRefType::Owned,
15530b57cec5SDimitry Andric                      PyObject_GetAttrString(implementor.get(), callee_name));
15540b57cec5SDimitry Andric 
15550b57cec5SDimitry Andric   if (PyErr_Occurred())
15560b57cec5SDimitry Andric     PyErr_Clear();
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric   if (!pmeth.IsAllocated())
15590b57cec5SDimitry Andric     return StructuredData::DictionarySP();
15600b57cec5SDimitry Andric 
15610b57cec5SDimitry Andric   if (PyCallable_Check(pmeth.get()) == 0) {
15620b57cec5SDimitry Andric     if (PyErr_Occurred())
15630b57cec5SDimitry Andric       PyErr_Clear();
15640b57cec5SDimitry Andric 
15650b57cec5SDimitry Andric     return StructuredData::DictionarySP();
15660b57cec5SDimitry Andric   }
15670b57cec5SDimitry Andric 
15680b57cec5SDimitry Andric   if (PyErr_Occurred())
15690b57cec5SDimitry Andric     PyErr_Clear();
15700b57cec5SDimitry Andric 
15710b57cec5SDimitry Andric   // right now we know this function exists and is callable..
15720b57cec5SDimitry Andric   PythonObject py_return(
15730b57cec5SDimitry Andric       PyRefType::Owned,
15740b57cec5SDimitry Andric       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
15750b57cec5SDimitry Andric 
15760b57cec5SDimitry Andric   // if it fails, print the error but otherwise go on
15770b57cec5SDimitry Andric   if (PyErr_Occurred()) {
15780b57cec5SDimitry Andric     PyErr_Print();
15790b57cec5SDimitry Andric     PyErr_Clear();
15800b57cec5SDimitry Andric   }
15810b57cec5SDimitry Andric   if (py_return.get()) {
15820b57cec5SDimitry Andric     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
15830b57cec5SDimitry Andric     return result_dict.CreateStructuredDictionary();
15840b57cec5SDimitry Andric   }
15850b57cec5SDimitry Andric   return StructuredData::DictionarySP();
15860b57cec5SDimitry Andric }
15870b57cec5SDimitry Andric 
15880b57cec5SDimitry Andric StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo(
15890b57cec5SDimitry Andric     StructuredData::ObjectSP os_plugin_object_sp) {
15900b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
15910b57cec5SDimitry Andric 
15920b57cec5SDimitry Andric   static char callee_name[] = "get_thread_info";
15930b57cec5SDimitry Andric 
15940b57cec5SDimitry Andric   if (!os_plugin_object_sp)
15950b57cec5SDimitry Andric     return StructuredData::ArraySP();
15960b57cec5SDimitry Andric 
15970b57cec5SDimitry Andric   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
15980b57cec5SDimitry Andric   if (!generic)
15990b57cec5SDimitry Andric     return nullptr;
16000b57cec5SDimitry Andric 
16010b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
16020b57cec5SDimitry Andric                            (PyObject *)generic->GetValue());
16030b57cec5SDimitry Andric 
16040b57cec5SDimitry Andric   if (!implementor.IsAllocated())
16050b57cec5SDimitry Andric     return StructuredData::ArraySP();
16060b57cec5SDimitry Andric 
16070b57cec5SDimitry Andric   PythonObject pmeth(PyRefType::Owned,
16080b57cec5SDimitry Andric                      PyObject_GetAttrString(implementor.get(), callee_name));
16090b57cec5SDimitry Andric 
16100b57cec5SDimitry Andric   if (PyErr_Occurred())
16110b57cec5SDimitry Andric     PyErr_Clear();
16120b57cec5SDimitry Andric 
16130b57cec5SDimitry Andric   if (!pmeth.IsAllocated())
16140b57cec5SDimitry Andric     return StructuredData::ArraySP();
16150b57cec5SDimitry Andric 
16160b57cec5SDimitry Andric   if (PyCallable_Check(pmeth.get()) == 0) {
16170b57cec5SDimitry Andric     if (PyErr_Occurred())
16180b57cec5SDimitry Andric       PyErr_Clear();
16190b57cec5SDimitry Andric 
16200b57cec5SDimitry Andric     return StructuredData::ArraySP();
16210b57cec5SDimitry Andric   }
16220b57cec5SDimitry Andric 
16230b57cec5SDimitry Andric   if (PyErr_Occurred())
16240b57cec5SDimitry Andric     PyErr_Clear();
16250b57cec5SDimitry Andric 
16260b57cec5SDimitry Andric   // right now we know this function exists and is callable..
16270b57cec5SDimitry Andric   PythonObject py_return(
16280b57cec5SDimitry Andric       PyRefType::Owned,
16290b57cec5SDimitry Andric       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
16300b57cec5SDimitry Andric 
16310b57cec5SDimitry Andric   // if it fails, print the error but otherwise go on
16320b57cec5SDimitry Andric   if (PyErr_Occurred()) {
16330b57cec5SDimitry Andric     PyErr_Print();
16340b57cec5SDimitry Andric     PyErr_Clear();
16350b57cec5SDimitry Andric   }
16360b57cec5SDimitry Andric 
16370b57cec5SDimitry Andric   if (py_return.get()) {
16380b57cec5SDimitry Andric     PythonList result_list(PyRefType::Borrowed, py_return.get());
16390b57cec5SDimitry Andric     return result_list.CreateStructuredArray();
16400b57cec5SDimitry Andric   }
16410b57cec5SDimitry Andric   return StructuredData::ArraySP();
16420b57cec5SDimitry Andric }
16430b57cec5SDimitry Andric 
16440b57cec5SDimitry Andric // GetPythonValueFormatString provides a system independent type safe way to
16450b57cec5SDimitry Andric // convert a variable's type into a python value format. Python value formats
16460b57cec5SDimitry Andric // are defined in terms of builtin C types and could change from system to as
16470b57cec5SDimitry Andric // the underlying typedef for uint* types, size_t, off_t and other values
16480b57cec5SDimitry Andric // change.
16490b57cec5SDimitry Andric 
16500b57cec5SDimitry Andric template <typename T> const char *GetPythonValueFormatString(T t);
16510b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(char *) { return "s"; }
16520b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(char) { return "b"; }
16530b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(unsigned char) {
16540b57cec5SDimitry Andric   return "B";
16550b57cec5SDimitry Andric }
16560b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(short) { return "h"; }
16570b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(unsigned short) {
16580b57cec5SDimitry Andric   return "H";
16590b57cec5SDimitry Andric }
16600b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(int) { return "i"; }
16610b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(unsigned int) { return "I"; }
16620b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(long) { return "l"; }
16630b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(unsigned long) {
16640b57cec5SDimitry Andric   return "k";
16650b57cec5SDimitry Andric }
16660b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(long long) { return "L"; }
16670b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(unsigned long long) {
16680b57cec5SDimitry Andric   return "K";
16690b57cec5SDimitry Andric }
16700b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(float t) { return "f"; }
16710b57cec5SDimitry Andric template <> const char *GetPythonValueFormatString(double t) { return "d"; }
16720b57cec5SDimitry Andric 
16730b57cec5SDimitry Andric StructuredData::StringSP
16740b57cec5SDimitry Andric ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData(
16750b57cec5SDimitry Andric     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
16760b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
16770b57cec5SDimitry Andric 
16780b57cec5SDimitry Andric   static char callee_name[] = "get_register_data";
16790b57cec5SDimitry Andric   static char *param_format =
16800b57cec5SDimitry Andric       const_cast<char *>(GetPythonValueFormatString(tid));
16810b57cec5SDimitry Andric 
16820b57cec5SDimitry Andric   if (!os_plugin_object_sp)
16830b57cec5SDimitry Andric     return StructuredData::StringSP();
16840b57cec5SDimitry Andric 
16850b57cec5SDimitry Andric   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
16860b57cec5SDimitry Andric   if (!generic)
16870b57cec5SDimitry Andric     return nullptr;
16880b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
16890b57cec5SDimitry Andric                            (PyObject *)generic->GetValue());
16900b57cec5SDimitry Andric 
16910b57cec5SDimitry Andric   if (!implementor.IsAllocated())
16920b57cec5SDimitry Andric     return StructuredData::StringSP();
16930b57cec5SDimitry Andric 
16940b57cec5SDimitry Andric   PythonObject pmeth(PyRefType::Owned,
16950b57cec5SDimitry Andric                      PyObject_GetAttrString(implementor.get(), callee_name));
16960b57cec5SDimitry Andric 
16970b57cec5SDimitry Andric   if (PyErr_Occurred())
16980b57cec5SDimitry Andric     PyErr_Clear();
16990b57cec5SDimitry Andric 
17000b57cec5SDimitry Andric   if (!pmeth.IsAllocated())
17010b57cec5SDimitry Andric     return StructuredData::StringSP();
17020b57cec5SDimitry Andric 
17030b57cec5SDimitry Andric   if (PyCallable_Check(pmeth.get()) == 0) {
17040b57cec5SDimitry Andric     if (PyErr_Occurred())
17050b57cec5SDimitry Andric       PyErr_Clear();
17060b57cec5SDimitry Andric     return StructuredData::StringSP();
17070b57cec5SDimitry Andric   }
17080b57cec5SDimitry Andric 
17090b57cec5SDimitry Andric   if (PyErr_Occurred())
17100b57cec5SDimitry Andric     PyErr_Clear();
17110b57cec5SDimitry Andric 
17120b57cec5SDimitry Andric   // right now we know this function exists and is callable..
17130b57cec5SDimitry Andric   PythonObject py_return(
17140b57cec5SDimitry Andric       PyRefType::Owned,
17150b57cec5SDimitry Andric       PyObject_CallMethod(implementor.get(), callee_name, param_format, tid));
17160b57cec5SDimitry Andric 
17170b57cec5SDimitry Andric   // if it fails, print the error but otherwise go on
17180b57cec5SDimitry Andric   if (PyErr_Occurred()) {
17190b57cec5SDimitry Andric     PyErr_Print();
17200b57cec5SDimitry Andric     PyErr_Clear();
17210b57cec5SDimitry Andric   }
17220b57cec5SDimitry Andric 
17230b57cec5SDimitry Andric   if (py_return.get()) {
17240b57cec5SDimitry Andric     PythonBytes result(PyRefType::Borrowed, py_return.get());
17250b57cec5SDimitry Andric     return result.CreateStructuredString();
17260b57cec5SDimitry Andric   }
17270b57cec5SDimitry Andric   return StructuredData::StringSP();
17280b57cec5SDimitry Andric }
17290b57cec5SDimitry Andric 
17300b57cec5SDimitry Andric StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread(
17310b57cec5SDimitry Andric     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
17320b57cec5SDimitry Andric     lldb::addr_t context) {
17330b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
17340b57cec5SDimitry Andric 
17350b57cec5SDimitry Andric   static char callee_name[] = "create_thread";
17360b57cec5SDimitry Andric   std::string param_format;
17370b57cec5SDimitry Andric   param_format += GetPythonValueFormatString(tid);
17380b57cec5SDimitry Andric   param_format += GetPythonValueFormatString(context);
17390b57cec5SDimitry Andric 
17400b57cec5SDimitry Andric   if (!os_plugin_object_sp)
17410b57cec5SDimitry Andric     return StructuredData::DictionarySP();
17420b57cec5SDimitry Andric 
17430b57cec5SDimitry Andric   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
17440b57cec5SDimitry Andric   if (!generic)
17450b57cec5SDimitry Andric     return nullptr;
17460b57cec5SDimitry Andric 
17470b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
17480b57cec5SDimitry Andric                            (PyObject *)generic->GetValue());
17490b57cec5SDimitry Andric 
17500b57cec5SDimitry Andric   if (!implementor.IsAllocated())
17510b57cec5SDimitry Andric     return StructuredData::DictionarySP();
17520b57cec5SDimitry Andric 
17530b57cec5SDimitry Andric   PythonObject pmeth(PyRefType::Owned,
17540b57cec5SDimitry Andric                      PyObject_GetAttrString(implementor.get(), callee_name));
17550b57cec5SDimitry Andric 
17560b57cec5SDimitry Andric   if (PyErr_Occurred())
17570b57cec5SDimitry Andric     PyErr_Clear();
17580b57cec5SDimitry Andric 
17590b57cec5SDimitry Andric   if (!pmeth.IsAllocated())
17600b57cec5SDimitry Andric     return StructuredData::DictionarySP();
17610b57cec5SDimitry Andric 
17620b57cec5SDimitry Andric   if (PyCallable_Check(pmeth.get()) == 0) {
17630b57cec5SDimitry Andric     if (PyErr_Occurred())
17640b57cec5SDimitry Andric       PyErr_Clear();
17650b57cec5SDimitry Andric     return StructuredData::DictionarySP();
17660b57cec5SDimitry Andric   }
17670b57cec5SDimitry Andric 
17680b57cec5SDimitry Andric   if (PyErr_Occurred())
17690b57cec5SDimitry Andric     PyErr_Clear();
17700b57cec5SDimitry Andric 
17710b57cec5SDimitry Andric   // right now we know this function exists and is callable..
17720b57cec5SDimitry Andric   PythonObject py_return(PyRefType::Owned,
17730b57cec5SDimitry Andric                          PyObject_CallMethod(implementor.get(), callee_name,
17740b57cec5SDimitry Andric                                              &param_format[0], tid, context));
17750b57cec5SDimitry Andric 
17760b57cec5SDimitry Andric   // if it fails, print the error but otherwise go on
17770b57cec5SDimitry Andric   if (PyErr_Occurred()) {
17780b57cec5SDimitry Andric     PyErr_Print();
17790b57cec5SDimitry Andric     PyErr_Clear();
17800b57cec5SDimitry Andric   }
17810b57cec5SDimitry Andric 
17820b57cec5SDimitry Andric   if (py_return.get()) {
17830b57cec5SDimitry Andric     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
17840b57cec5SDimitry Andric     return result_dict.CreateStructuredDictionary();
17850b57cec5SDimitry Andric   }
17860b57cec5SDimitry Andric   return StructuredData::DictionarySP();
17870b57cec5SDimitry Andric }
17880b57cec5SDimitry Andric 
17890b57cec5SDimitry Andric StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan(
1790*9dba64beSDimitry Andric     const char *class_name, StructuredDataImpl *args_data,
1791*9dba64beSDimitry Andric     std::string &error_str,
1792*9dba64beSDimitry Andric     lldb::ThreadPlanSP thread_plan_sp) {
17930b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
17940b57cec5SDimitry Andric     return StructuredData::ObjectSP();
17950b57cec5SDimitry Andric 
17960b57cec5SDimitry Andric   if (!thread_plan_sp.get())
1797*9dba64beSDimitry Andric     return {};
17980b57cec5SDimitry Andric 
17990b57cec5SDimitry Andric   Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
18000b57cec5SDimitry Andric   ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
18010b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
18020b57cec5SDimitry Andric       static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
18030b57cec5SDimitry Andric 
18040b57cec5SDimitry Andric   if (!script_interpreter)
1805*9dba64beSDimitry Andric     return {};
18060b57cec5SDimitry Andric 
18070b57cec5SDimitry Andric   void *ret_val;
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric   {
18100b57cec5SDimitry Andric     Locker py_lock(this,
18110b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
18120b57cec5SDimitry Andric     ret_val = LLDBSwigPythonCreateScriptedThreadPlan(
18130b57cec5SDimitry Andric         class_name, python_interpreter->m_dictionary_name.c_str(),
1814*9dba64beSDimitry Andric         args_data, error_str, thread_plan_sp);
1815*9dba64beSDimitry Andric     if (!ret_val)
1816*9dba64beSDimitry Andric       return {};
18170b57cec5SDimitry Andric   }
18180b57cec5SDimitry Andric 
18190b57cec5SDimitry Andric   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
18200b57cec5SDimitry Andric }
18210b57cec5SDimitry Andric 
18220b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop(
18230b57cec5SDimitry Andric     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
18240b57cec5SDimitry Andric   bool explains_stop = true;
18250b57cec5SDimitry Andric   StructuredData::Generic *generic = nullptr;
18260b57cec5SDimitry Andric   if (implementor_sp)
18270b57cec5SDimitry Andric     generic = implementor_sp->GetAsGeneric();
18280b57cec5SDimitry Andric   if (generic) {
18290b57cec5SDimitry Andric     Locker py_lock(this,
18300b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
18310b57cec5SDimitry Andric     explains_stop = LLDBSWIGPythonCallThreadPlan(
18320b57cec5SDimitry Andric         generic->GetValue(), "explains_stop", event, script_error);
18330b57cec5SDimitry Andric     if (script_error)
18340b57cec5SDimitry Andric       return true;
18350b57cec5SDimitry Andric   }
18360b57cec5SDimitry Andric   return explains_stop;
18370b57cec5SDimitry Andric }
18380b57cec5SDimitry Andric 
18390b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop(
18400b57cec5SDimitry Andric     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
18410b57cec5SDimitry Andric   bool should_stop = true;
18420b57cec5SDimitry Andric   StructuredData::Generic *generic = nullptr;
18430b57cec5SDimitry Andric   if (implementor_sp)
18440b57cec5SDimitry Andric     generic = implementor_sp->GetAsGeneric();
18450b57cec5SDimitry Andric   if (generic) {
18460b57cec5SDimitry Andric     Locker py_lock(this,
18470b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
18480b57cec5SDimitry Andric     should_stop = LLDBSWIGPythonCallThreadPlan(
18490b57cec5SDimitry Andric         generic->GetValue(), "should_stop", event, script_error);
18500b57cec5SDimitry Andric     if (script_error)
18510b57cec5SDimitry Andric       return true;
18520b57cec5SDimitry Andric   }
18530b57cec5SDimitry Andric   return should_stop;
18540b57cec5SDimitry Andric }
18550b57cec5SDimitry Andric 
18560b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale(
18570b57cec5SDimitry Andric     StructuredData::ObjectSP implementor_sp, bool &script_error) {
18580b57cec5SDimitry Andric   bool is_stale = true;
18590b57cec5SDimitry Andric   StructuredData::Generic *generic = nullptr;
18600b57cec5SDimitry Andric   if (implementor_sp)
18610b57cec5SDimitry Andric     generic = implementor_sp->GetAsGeneric();
18620b57cec5SDimitry Andric   if (generic) {
18630b57cec5SDimitry Andric     Locker py_lock(this,
18640b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
18650b57cec5SDimitry Andric     is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale",
18660b57cec5SDimitry Andric                                             nullptr, script_error);
18670b57cec5SDimitry Andric     if (script_error)
18680b57cec5SDimitry Andric       return true;
18690b57cec5SDimitry Andric   }
18700b57cec5SDimitry Andric   return is_stale;
18710b57cec5SDimitry Andric }
18720b57cec5SDimitry Andric 
18730b57cec5SDimitry Andric lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState(
18740b57cec5SDimitry Andric     StructuredData::ObjectSP implementor_sp, bool &script_error) {
18750b57cec5SDimitry Andric   bool should_step = false;
18760b57cec5SDimitry Andric   StructuredData::Generic *generic = nullptr;
18770b57cec5SDimitry Andric   if (implementor_sp)
18780b57cec5SDimitry Andric     generic = implementor_sp->GetAsGeneric();
18790b57cec5SDimitry Andric   if (generic) {
18800b57cec5SDimitry Andric     Locker py_lock(this,
18810b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
18820b57cec5SDimitry Andric     should_step = LLDBSWIGPythonCallThreadPlan(
18830b57cec5SDimitry Andric         generic->GetValue(), "should_step", nullptr, script_error);
18840b57cec5SDimitry Andric     if (script_error)
18850b57cec5SDimitry Andric       should_step = true;
18860b57cec5SDimitry Andric   }
18870b57cec5SDimitry Andric   if (should_step)
18880b57cec5SDimitry Andric     return lldb::eStateStepping;
18890b57cec5SDimitry Andric   else
18900b57cec5SDimitry Andric     return lldb::eStateRunning;
18910b57cec5SDimitry Andric }
18920b57cec5SDimitry Andric 
18930b57cec5SDimitry Andric StructuredData::GenericSP
18940b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
18950b57cec5SDimitry Andric     const char *class_name, StructuredDataImpl *args_data,
18960b57cec5SDimitry Andric     lldb::BreakpointSP &bkpt_sp) {
18970b57cec5SDimitry Andric 
18980b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
18990b57cec5SDimitry Andric     return StructuredData::GenericSP();
19000b57cec5SDimitry Andric 
19010b57cec5SDimitry Andric   if (!bkpt_sp.get())
19020b57cec5SDimitry Andric     return StructuredData::GenericSP();
19030b57cec5SDimitry Andric 
19040b57cec5SDimitry Andric   Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
19050b57cec5SDimitry Andric   ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
19060b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
19070b57cec5SDimitry Andric       static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
19080b57cec5SDimitry Andric 
19090b57cec5SDimitry Andric   if (!script_interpreter)
19100b57cec5SDimitry Andric     return StructuredData::GenericSP();
19110b57cec5SDimitry Andric 
19120b57cec5SDimitry Andric   void *ret_val;
19130b57cec5SDimitry Andric 
19140b57cec5SDimitry Andric   {
19150b57cec5SDimitry Andric     Locker py_lock(this,
19160b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19170b57cec5SDimitry Andric 
19180b57cec5SDimitry Andric     ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver(
19190b57cec5SDimitry Andric         class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
19200b57cec5SDimitry Andric         bkpt_sp);
19210b57cec5SDimitry Andric   }
19220b57cec5SDimitry Andric 
19230b57cec5SDimitry Andric   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
19240b57cec5SDimitry Andric }
19250b57cec5SDimitry Andric 
19260b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
19270b57cec5SDimitry Andric     StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
19280b57cec5SDimitry Andric   bool should_continue = false;
19290b57cec5SDimitry Andric 
19300b57cec5SDimitry Andric   if (implementor_sp) {
19310b57cec5SDimitry Andric     Locker py_lock(this,
19320b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19330b57cec5SDimitry Andric     should_continue = LLDBSwigPythonCallBreakpointResolver(
19340b57cec5SDimitry Andric         implementor_sp->GetValue(), "__callback__", sym_ctx);
19350b57cec5SDimitry Andric     if (PyErr_Occurred()) {
19360b57cec5SDimitry Andric       PyErr_Print();
19370b57cec5SDimitry Andric       PyErr_Clear();
19380b57cec5SDimitry Andric     }
19390b57cec5SDimitry Andric   }
19400b57cec5SDimitry Andric   return should_continue;
19410b57cec5SDimitry Andric }
19420b57cec5SDimitry Andric 
19430b57cec5SDimitry Andric lldb::SearchDepth
19440b57cec5SDimitry Andric ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
19450b57cec5SDimitry Andric     StructuredData::GenericSP implementor_sp) {
19460b57cec5SDimitry Andric   int depth_as_int = lldb::eSearchDepthModule;
19470b57cec5SDimitry Andric   if (implementor_sp) {
19480b57cec5SDimitry Andric     Locker py_lock(this,
19490b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19500b57cec5SDimitry Andric     depth_as_int = LLDBSwigPythonCallBreakpointResolver(
19510b57cec5SDimitry Andric         implementor_sp->GetValue(), "__get_depth__", nullptr);
19520b57cec5SDimitry Andric     if (PyErr_Occurred()) {
19530b57cec5SDimitry Andric       PyErr_Print();
19540b57cec5SDimitry Andric       PyErr_Clear();
19550b57cec5SDimitry Andric     }
19560b57cec5SDimitry Andric   }
19570b57cec5SDimitry Andric   if (depth_as_int == lldb::eSearchDepthInvalid)
19580b57cec5SDimitry Andric     return lldb::eSearchDepthModule;
19590b57cec5SDimitry Andric 
19600b57cec5SDimitry Andric   if (depth_as_int <= lldb::kLastSearchDepthKind)
19610b57cec5SDimitry Andric     return (lldb::SearchDepth)depth_as_int;
19620b57cec5SDimitry Andric   else
19630b57cec5SDimitry Andric     return lldb::eSearchDepthModule;
19640b57cec5SDimitry Andric }
19650b57cec5SDimitry Andric 
19660b57cec5SDimitry Andric StructuredData::ObjectSP
19670b57cec5SDimitry Andric ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
19680b57cec5SDimitry Andric                                               lldb_private::Status &error) {
19690b57cec5SDimitry Andric   if (!FileSystem::Instance().Exists(file_spec)) {
19700b57cec5SDimitry Andric     error.SetErrorString("no such file");
19710b57cec5SDimitry Andric     return StructuredData::ObjectSP();
19720b57cec5SDimitry Andric   }
19730b57cec5SDimitry Andric 
19740b57cec5SDimitry Andric   StructuredData::ObjectSP module_sp;
19750b57cec5SDimitry Andric 
19760b57cec5SDimitry Andric   if (LoadScriptingModule(file_spec.GetPath().c_str(), true, true, error,
19770b57cec5SDimitry Andric                           &module_sp))
19780b57cec5SDimitry Andric     return module_sp;
19790b57cec5SDimitry Andric 
19800b57cec5SDimitry Andric   return StructuredData::ObjectSP();
19810b57cec5SDimitry Andric }
19820b57cec5SDimitry Andric 
19830b57cec5SDimitry Andric StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
19840b57cec5SDimitry Andric     StructuredData::ObjectSP plugin_module_sp, Target *target,
19850b57cec5SDimitry Andric     const char *setting_name, lldb_private::Status &error) {
19860b57cec5SDimitry Andric   if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
19870b57cec5SDimitry Andric     return StructuredData::DictionarySP();
19880b57cec5SDimitry Andric   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
19890b57cec5SDimitry Andric   if (!generic)
19900b57cec5SDimitry Andric     return StructuredData::DictionarySP();
19910b57cec5SDimitry Andric 
19920b57cec5SDimitry Andric   Locker py_lock(this,
19930b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19940b57cec5SDimitry Andric   TargetSP target_sp(target->shared_from_this());
19950b57cec5SDimitry Andric 
1996*9dba64beSDimitry Andric   auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting(
1997*9dba64beSDimitry Andric       generic->GetValue(), setting_name, target_sp);
1998*9dba64beSDimitry Andric 
1999*9dba64beSDimitry Andric   if (!setting)
2000*9dba64beSDimitry Andric     return StructuredData::DictionarySP();
2001*9dba64beSDimitry Andric 
2002*9dba64beSDimitry Andric   PythonDictionary py_dict =
2003*9dba64beSDimitry Andric       unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
2004*9dba64beSDimitry Andric 
2005*9dba64beSDimitry Andric   if (!py_dict)
2006*9dba64beSDimitry Andric     return StructuredData::DictionarySP();
2007*9dba64beSDimitry Andric 
20080b57cec5SDimitry Andric   return py_dict.CreateStructuredDictionary();
20090b57cec5SDimitry Andric }
20100b57cec5SDimitry Andric 
20110b57cec5SDimitry Andric StructuredData::ObjectSP
20120b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
20130b57cec5SDimitry Andric     const char *class_name, lldb::ValueObjectSP valobj) {
20140b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
20150b57cec5SDimitry Andric     return StructuredData::ObjectSP();
20160b57cec5SDimitry Andric 
20170b57cec5SDimitry Andric   if (!valobj.get())
20180b57cec5SDimitry Andric     return StructuredData::ObjectSP();
20190b57cec5SDimitry Andric 
20200b57cec5SDimitry Andric   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
20210b57cec5SDimitry Andric   Target *target = exe_ctx.GetTargetPtr();
20220b57cec5SDimitry Andric 
20230b57cec5SDimitry Andric   if (!target)
20240b57cec5SDimitry Andric     return StructuredData::ObjectSP();
20250b57cec5SDimitry Andric 
20260b57cec5SDimitry Andric   Debugger &debugger = target->GetDebugger();
20270b57cec5SDimitry Andric   ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
20280b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
20290b57cec5SDimitry Andric       (ScriptInterpreterPythonImpl *)script_interpreter;
20300b57cec5SDimitry Andric 
20310b57cec5SDimitry Andric   if (!script_interpreter)
20320b57cec5SDimitry Andric     return StructuredData::ObjectSP();
20330b57cec5SDimitry Andric 
20340b57cec5SDimitry Andric   void *ret_val = nullptr;
20350b57cec5SDimitry Andric 
20360b57cec5SDimitry Andric   {
20370b57cec5SDimitry Andric     Locker py_lock(this,
20380b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
20390b57cec5SDimitry Andric     ret_val = LLDBSwigPythonCreateSyntheticProvider(
20400b57cec5SDimitry Andric         class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
20410b57cec5SDimitry Andric   }
20420b57cec5SDimitry Andric 
20430b57cec5SDimitry Andric   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
20440b57cec5SDimitry Andric }
20450b57cec5SDimitry Andric 
20460b57cec5SDimitry Andric StructuredData::GenericSP
20470b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
20480b57cec5SDimitry Andric   DebuggerSP debugger_sp(m_debugger.shared_from_this());
20490b57cec5SDimitry Andric 
20500b57cec5SDimitry Andric   if (class_name == nullptr || class_name[0] == '\0')
20510b57cec5SDimitry Andric     return StructuredData::GenericSP();
20520b57cec5SDimitry Andric 
20530b57cec5SDimitry Andric   if (!debugger_sp.get())
20540b57cec5SDimitry Andric     return StructuredData::GenericSP();
20550b57cec5SDimitry Andric 
20560b57cec5SDimitry Andric   void *ret_val;
20570b57cec5SDimitry Andric 
20580b57cec5SDimitry Andric   {
20590b57cec5SDimitry Andric     Locker py_lock(this,
20600b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
20610b57cec5SDimitry Andric     ret_val = LLDBSwigPythonCreateCommandObject(
20620b57cec5SDimitry Andric         class_name, m_dictionary_name.c_str(), debugger_sp);
20630b57cec5SDimitry Andric   }
20640b57cec5SDimitry Andric 
20650b57cec5SDimitry Andric   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
20660b57cec5SDimitry Andric }
20670b57cec5SDimitry Andric 
20680b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
20690b57cec5SDimitry Andric     const char *oneliner, std::string &output, const void *name_token) {
20700b57cec5SDimitry Andric   StringList input;
20710b57cec5SDimitry Andric   input.SplitIntoLines(oneliner, strlen(oneliner));
20720b57cec5SDimitry Andric   return GenerateTypeScriptFunction(input, output, name_token);
20730b57cec5SDimitry Andric }
20740b57cec5SDimitry Andric 
20750b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
20760b57cec5SDimitry Andric     const char *oneliner, std::string &output, const void *name_token) {
20770b57cec5SDimitry Andric   StringList input;
20780b57cec5SDimitry Andric   input.SplitIntoLines(oneliner, strlen(oneliner));
20790b57cec5SDimitry Andric   return GenerateTypeSynthClass(input, output, name_token);
20800b57cec5SDimitry Andric }
20810b57cec5SDimitry Andric 
20820b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
20830b57cec5SDimitry Andric     StringList &user_input, std::string &output) {
20840b57cec5SDimitry Andric   static uint32_t num_created_functions = 0;
20850b57cec5SDimitry Andric   user_input.RemoveBlankLines();
20860b57cec5SDimitry Andric   StreamString sstr;
20870b57cec5SDimitry Andric   Status error;
20880b57cec5SDimitry Andric   if (user_input.GetSize() == 0) {
20890b57cec5SDimitry Andric     error.SetErrorString("No input data.");
20900b57cec5SDimitry Andric     return error;
20910b57cec5SDimitry Andric   }
20920b57cec5SDimitry Andric 
20930b57cec5SDimitry Andric   std::string auto_generated_function_name(GenerateUniqueName(
20940b57cec5SDimitry Andric       "lldb_autogen_python_bp_callback_func_", num_created_functions));
20950b57cec5SDimitry Andric   sstr.Printf("def %s (frame, bp_loc, internal_dict):",
20960b57cec5SDimitry Andric               auto_generated_function_name.c_str());
20970b57cec5SDimitry Andric 
20980b57cec5SDimitry Andric   error = GenerateFunction(sstr.GetData(), user_input);
20990b57cec5SDimitry Andric   if (!error.Success())
21000b57cec5SDimitry Andric     return error;
21010b57cec5SDimitry Andric 
21020b57cec5SDimitry Andric   // Store the name of the auto-generated function to be called.
21030b57cec5SDimitry Andric   output.assign(auto_generated_function_name);
21040b57cec5SDimitry Andric   return error;
21050b57cec5SDimitry Andric }
21060b57cec5SDimitry Andric 
21070b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
21080b57cec5SDimitry Andric     StringList &user_input, std::string &output) {
21090b57cec5SDimitry Andric   static uint32_t num_created_functions = 0;
21100b57cec5SDimitry Andric   user_input.RemoveBlankLines();
21110b57cec5SDimitry Andric   StreamString sstr;
21120b57cec5SDimitry Andric 
21130b57cec5SDimitry Andric   if (user_input.GetSize() == 0)
21140b57cec5SDimitry Andric     return false;
21150b57cec5SDimitry Andric 
21160b57cec5SDimitry Andric   std::string auto_generated_function_name(GenerateUniqueName(
21170b57cec5SDimitry Andric       "lldb_autogen_python_wp_callback_func_", num_created_functions));
21180b57cec5SDimitry Andric   sstr.Printf("def %s (frame, wp, internal_dict):",
21190b57cec5SDimitry Andric               auto_generated_function_name.c_str());
21200b57cec5SDimitry Andric 
21210b57cec5SDimitry Andric   if (!GenerateFunction(sstr.GetData(), user_input).Success())
21220b57cec5SDimitry Andric     return false;
21230b57cec5SDimitry Andric 
21240b57cec5SDimitry Andric   // Store the name of the auto-generated function to be called.
21250b57cec5SDimitry Andric   output.assign(auto_generated_function_name);
21260b57cec5SDimitry Andric   return true;
21270b57cec5SDimitry Andric }
21280b57cec5SDimitry Andric 
21290b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetScriptedSummary(
21300b57cec5SDimitry Andric     const char *python_function_name, lldb::ValueObjectSP valobj,
21310b57cec5SDimitry Andric     StructuredData::ObjectSP &callee_wrapper_sp,
21320b57cec5SDimitry Andric     const TypeSummaryOptions &options, std::string &retval) {
21330b57cec5SDimitry Andric 
21340b57cec5SDimitry Andric   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
21350b57cec5SDimitry Andric   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric   if (!valobj.get()) {
21380b57cec5SDimitry Andric     retval.assign("<no object>");
21390b57cec5SDimitry Andric     return false;
21400b57cec5SDimitry Andric   }
21410b57cec5SDimitry Andric 
21420b57cec5SDimitry Andric   void *old_callee = nullptr;
21430b57cec5SDimitry Andric   StructuredData::Generic *generic = nullptr;
21440b57cec5SDimitry Andric   if (callee_wrapper_sp) {
21450b57cec5SDimitry Andric     generic = callee_wrapper_sp->GetAsGeneric();
21460b57cec5SDimitry Andric     if (generic)
21470b57cec5SDimitry Andric       old_callee = generic->GetValue();
21480b57cec5SDimitry Andric   }
21490b57cec5SDimitry Andric   void *new_callee = old_callee;
21500b57cec5SDimitry Andric 
21510b57cec5SDimitry Andric   bool ret_val;
21520b57cec5SDimitry Andric   if (python_function_name && *python_function_name) {
21530b57cec5SDimitry Andric     {
21540b57cec5SDimitry Andric       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
21550b57cec5SDimitry Andric                                Locker::NoSTDIN);
21560b57cec5SDimitry Andric       {
21570b57cec5SDimitry Andric         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
21580b57cec5SDimitry Andric 
21590b57cec5SDimitry Andric         static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
21600b57cec5SDimitry Andric         Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
21610b57cec5SDimitry Andric         ret_val = LLDBSwigPythonCallTypeScript(
21620b57cec5SDimitry Andric             python_function_name, GetSessionDictionary().get(), valobj,
21630b57cec5SDimitry Andric             &new_callee, options_sp, retval);
21640b57cec5SDimitry Andric       }
21650b57cec5SDimitry Andric     }
21660b57cec5SDimitry Andric   } else {
21670b57cec5SDimitry Andric     retval.assign("<no function name>");
21680b57cec5SDimitry Andric     return false;
21690b57cec5SDimitry Andric   }
21700b57cec5SDimitry Andric 
21710b57cec5SDimitry Andric   if (new_callee && old_callee != new_callee)
21720b57cec5SDimitry Andric     callee_wrapper_sp = std::make_shared<StructuredPythonObject>(new_callee);
21730b57cec5SDimitry Andric 
21740b57cec5SDimitry Andric   return ret_val;
21750b57cec5SDimitry Andric }
21760b57cec5SDimitry Andric 
21770b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
21780b57cec5SDimitry Andric     void *baton, StoppointCallbackContext *context, user_id_t break_id,
21790b57cec5SDimitry Andric     user_id_t break_loc_id) {
21800b57cec5SDimitry Andric   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
21810b57cec5SDimitry Andric   const char *python_function_name = bp_option_data->script_source.c_str();
21820b57cec5SDimitry Andric 
21830b57cec5SDimitry Andric   if (!context)
21840b57cec5SDimitry Andric     return true;
21850b57cec5SDimitry Andric 
21860b57cec5SDimitry Andric   ExecutionContext exe_ctx(context->exe_ctx_ref);
21870b57cec5SDimitry Andric   Target *target = exe_ctx.GetTargetPtr();
21880b57cec5SDimitry Andric 
21890b57cec5SDimitry Andric   if (!target)
21900b57cec5SDimitry Andric     return true;
21910b57cec5SDimitry Andric 
21920b57cec5SDimitry Andric   Debugger &debugger = target->GetDebugger();
21930b57cec5SDimitry Andric   ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
21940b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
21950b57cec5SDimitry Andric       (ScriptInterpreterPythonImpl *)script_interpreter;
21960b57cec5SDimitry Andric 
21970b57cec5SDimitry Andric   if (!script_interpreter)
21980b57cec5SDimitry Andric     return true;
21990b57cec5SDimitry Andric 
22000b57cec5SDimitry Andric   if (python_function_name && python_function_name[0]) {
22010b57cec5SDimitry Andric     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
22020b57cec5SDimitry Andric     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
22030b57cec5SDimitry Andric     if (breakpoint_sp) {
22040b57cec5SDimitry Andric       const BreakpointLocationSP bp_loc_sp(
22050b57cec5SDimitry Andric           breakpoint_sp->FindLocationByID(break_loc_id));
22060b57cec5SDimitry Andric 
22070b57cec5SDimitry Andric       if (stop_frame_sp && bp_loc_sp) {
22080b57cec5SDimitry Andric         bool ret_val = true;
22090b57cec5SDimitry Andric         {
22100b57cec5SDimitry Andric           Locker py_lock(python_interpreter, Locker::AcquireLock |
22110b57cec5SDimitry Andric                                                  Locker::InitSession |
22120b57cec5SDimitry Andric                                                  Locker::NoSTDIN);
22130b57cec5SDimitry Andric           ret_val = LLDBSwigPythonBreakpointCallbackFunction(
22140b57cec5SDimitry Andric               python_function_name,
22150b57cec5SDimitry Andric               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
22160b57cec5SDimitry Andric               bp_loc_sp);
22170b57cec5SDimitry Andric         }
22180b57cec5SDimitry Andric         return ret_val;
22190b57cec5SDimitry Andric       }
22200b57cec5SDimitry Andric     }
22210b57cec5SDimitry Andric   }
22220b57cec5SDimitry Andric   // We currently always true so we stop in case anything goes wrong when
22230b57cec5SDimitry Andric   // trying to call the script function
22240b57cec5SDimitry Andric   return true;
22250b57cec5SDimitry Andric }
22260b57cec5SDimitry Andric 
22270b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
22280b57cec5SDimitry Andric     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
22290b57cec5SDimitry Andric   WatchpointOptions::CommandData *wp_option_data =
22300b57cec5SDimitry Andric       (WatchpointOptions::CommandData *)baton;
22310b57cec5SDimitry Andric   const char *python_function_name = wp_option_data->script_source.c_str();
22320b57cec5SDimitry Andric 
22330b57cec5SDimitry Andric   if (!context)
22340b57cec5SDimitry Andric     return true;
22350b57cec5SDimitry Andric 
22360b57cec5SDimitry Andric   ExecutionContext exe_ctx(context->exe_ctx_ref);
22370b57cec5SDimitry Andric   Target *target = exe_ctx.GetTargetPtr();
22380b57cec5SDimitry Andric 
22390b57cec5SDimitry Andric   if (!target)
22400b57cec5SDimitry Andric     return true;
22410b57cec5SDimitry Andric 
22420b57cec5SDimitry Andric   Debugger &debugger = target->GetDebugger();
22430b57cec5SDimitry Andric   ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
22440b57cec5SDimitry Andric   ScriptInterpreterPythonImpl *python_interpreter =
22450b57cec5SDimitry Andric       (ScriptInterpreterPythonImpl *)script_interpreter;
22460b57cec5SDimitry Andric 
22470b57cec5SDimitry Andric   if (!script_interpreter)
22480b57cec5SDimitry Andric     return true;
22490b57cec5SDimitry Andric 
22500b57cec5SDimitry Andric   if (python_function_name && python_function_name[0]) {
22510b57cec5SDimitry Andric     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
22520b57cec5SDimitry Andric     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
22530b57cec5SDimitry Andric     if (wp_sp) {
22540b57cec5SDimitry Andric       if (stop_frame_sp && wp_sp) {
22550b57cec5SDimitry Andric         bool ret_val = true;
22560b57cec5SDimitry Andric         {
22570b57cec5SDimitry Andric           Locker py_lock(python_interpreter, Locker::AcquireLock |
22580b57cec5SDimitry Andric                                                  Locker::InitSession |
22590b57cec5SDimitry Andric                                                  Locker::NoSTDIN);
22600b57cec5SDimitry Andric           ret_val = LLDBSwigPythonWatchpointCallbackFunction(
22610b57cec5SDimitry Andric               python_function_name,
22620b57cec5SDimitry Andric               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
22630b57cec5SDimitry Andric               wp_sp);
22640b57cec5SDimitry Andric         }
22650b57cec5SDimitry Andric         return ret_val;
22660b57cec5SDimitry Andric       }
22670b57cec5SDimitry Andric     }
22680b57cec5SDimitry Andric   }
22690b57cec5SDimitry Andric   // We currently always true so we stop in case anything goes wrong when
22700b57cec5SDimitry Andric   // trying to call the script function
22710b57cec5SDimitry Andric   return true;
22720b57cec5SDimitry Andric }
22730b57cec5SDimitry Andric 
22740b57cec5SDimitry Andric size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
22750b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
22760b57cec5SDimitry Andric   if (!implementor_sp)
22770b57cec5SDimitry Andric     return 0;
22780b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
22790b57cec5SDimitry Andric   if (!generic)
22800b57cec5SDimitry Andric     return 0;
22810b57cec5SDimitry Andric   void *implementor = generic->GetValue();
22820b57cec5SDimitry Andric   if (!implementor)
22830b57cec5SDimitry Andric     return 0;
22840b57cec5SDimitry Andric 
22850b57cec5SDimitry Andric   size_t ret_val = 0;
22860b57cec5SDimitry Andric 
22870b57cec5SDimitry Andric   {
22880b57cec5SDimitry Andric     Locker py_lock(this,
22890b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
22900b57cec5SDimitry Andric     ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max);
22910b57cec5SDimitry Andric   }
22920b57cec5SDimitry Andric 
22930b57cec5SDimitry Andric   return ret_val;
22940b57cec5SDimitry Andric }
22950b57cec5SDimitry Andric 
22960b57cec5SDimitry Andric lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
22970b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
22980b57cec5SDimitry Andric   if (!implementor_sp)
22990b57cec5SDimitry Andric     return lldb::ValueObjectSP();
23000b57cec5SDimitry Andric 
23010b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
23020b57cec5SDimitry Andric   if (!generic)
23030b57cec5SDimitry Andric     return lldb::ValueObjectSP();
23040b57cec5SDimitry Andric   void *implementor = generic->GetValue();
23050b57cec5SDimitry Andric   if (!implementor)
23060b57cec5SDimitry Andric     return lldb::ValueObjectSP();
23070b57cec5SDimitry Andric 
23080b57cec5SDimitry Andric   lldb::ValueObjectSP ret_val;
23090b57cec5SDimitry Andric   {
23100b57cec5SDimitry Andric     Locker py_lock(this,
23110b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
23120b57cec5SDimitry Andric     void *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx);
23130b57cec5SDimitry Andric     if (child_ptr != nullptr && child_ptr != Py_None) {
23140b57cec5SDimitry Andric       lldb::SBValue *sb_value_ptr =
23150b57cec5SDimitry Andric           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
23160b57cec5SDimitry Andric       if (sb_value_ptr == nullptr)
23170b57cec5SDimitry Andric         Py_XDECREF(child_ptr);
23180b57cec5SDimitry Andric       else
23190b57cec5SDimitry Andric         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
23200b57cec5SDimitry Andric     } else {
23210b57cec5SDimitry Andric       Py_XDECREF(child_ptr);
23220b57cec5SDimitry Andric     }
23230b57cec5SDimitry Andric   }
23240b57cec5SDimitry Andric 
23250b57cec5SDimitry Andric   return ret_val;
23260b57cec5SDimitry Andric }
23270b57cec5SDimitry Andric 
23280b57cec5SDimitry Andric int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
23290b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
23300b57cec5SDimitry Andric   if (!implementor_sp)
23310b57cec5SDimitry Andric     return UINT32_MAX;
23320b57cec5SDimitry Andric 
23330b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
23340b57cec5SDimitry Andric   if (!generic)
23350b57cec5SDimitry Andric     return UINT32_MAX;
23360b57cec5SDimitry Andric   void *implementor = generic->GetValue();
23370b57cec5SDimitry Andric   if (!implementor)
23380b57cec5SDimitry Andric     return UINT32_MAX;
23390b57cec5SDimitry Andric 
23400b57cec5SDimitry Andric   int ret_val = UINT32_MAX;
23410b57cec5SDimitry Andric 
23420b57cec5SDimitry Andric   {
23430b57cec5SDimitry Andric     Locker py_lock(this,
23440b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
23450b57cec5SDimitry Andric     ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
23460b57cec5SDimitry Andric   }
23470b57cec5SDimitry Andric 
23480b57cec5SDimitry Andric   return ret_val;
23490b57cec5SDimitry Andric }
23500b57cec5SDimitry Andric 
23510b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
23520b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp) {
23530b57cec5SDimitry Andric   bool ret_val = false;
23540b57cec5SDimitry Andric 
23550b57cec5SDimitry Andric   if (!implementor_sp)
23560b57cec5SDimitry Andric     return ret_val;
23570b57cec5SDimitry Andric 
23580b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
23590b57cec5SDimitry Andric   if (!generic)
23600b57cec5SDimitry Andric     return ret_val;
23610b57cec5SDimitry Andric   void *implementor = generic->GetValue();
23620b57cec5SDimitry Andric   if (!implementor)
23630b57cec5SDimitry Andric     return ret_val;
23640b57cec5SDimitry Andric 
23650b57cec5SDimitry Andric   {
23660b57cec5SDimitry Andric     Locker py_lock(this,
23670b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
23680b57cec5SDimitry Andric     ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor);
23690b57cec5SDimitry Andric   }
23700b57cec5SDimitry Andric 
23710b57cec5SDimitry Andric   return ret_val;
23720b57cec5SDimitry Andric }
23730b57cec5SDimitry Andric 
23740b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
23750b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp) {
23760b57cec5SDimitry Andric   bool ret_val = false;
23770b57cec5SDimitry Andric 
23780b57cec5SDimitry Andric   if (!implementor_sp)
23790b57cec5SDimitry Andric     return ret_val;
23800b57cec5SDimitry Andric 
23810b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
23820b57cec5SDimitry Andric   if (!generic)
23830b57cec5SDimitry Andric     return ret_val;
23840b57cec5SDimitry Andric   void *implementor = generic->GetValue();
23850b57cec5SDimitry Andric   if (!implementor)
23860b57cec5SDimitry Andric     return ret_val;
23870b57cec5SDimitry Andric 
23880b57cec5SDimitry Andric   {
23890b57cec5SDimitry Andric     Locker py_lock(this,
23900b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
23910b57cec5SDimitry Andric     ret_val =
23920b57cec5SDimitry Andric         LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor);
23930b57cec5SDimitry Andric   }
23940b57cec5SDimitry Andric 
23950b57cec5SDimitry Andric   return ret_val;
23960b57cec5SDimitry Andric }
23970b57cec5SDimitry Andric 
23980b57cec5SDimitry Andric lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
23990b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp) {
24000b57cec5SDimitry Andric   lldb::ValueObjectSP ret_val(nullptr);
24010b57cec5SDimitry Andric 
24020b57cec5SDimitry Andric   if (!implementor_sp)
24030b57cec5SDimitry Andric     return ret_val;
24040b57cec5SDimitry Andric 
24050b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24060b57cec5SDimitry Andric   if (!generic)
24070b57cec5SDimitry Andric     return ret_val;
24080b57cec5SDimitry Andric   void *implementor = generic->GetValue();
24090b57cec5SDimitry Andric   if (!implementor)
24100b57cec5SDimitry Andric     return ret_val;
24110b57cec5SDimitry Andric 
24120b57cec5SDimitry Andric   {
24130b57cec5SDimitry Andric     Locker py_lock(this,
24140b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
24150b57cec5SDimitry Andric     void *child_ptr = LLDBSwigPython_GetValueSynthProviderInstance(implementor);
24160b57cec5SDimitry Andric     if (child_ptr != nullptr && child_ptr != Py_None) {
24170b57cec5SDimitry Andric       lldb::SBValue *sb_value_ptr =
24180b57cec5SDimitry Andric           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
24190b57cec5SDimitry Andric       if (sb_value_ptr == nullptr)
24200b57cec5SDimitry Andric         Py_XDECREF(child_ptr);
24210b57cec5SDimitry Andric       else
24220b57cec5SDimitry Andric         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
24230b57cec5SDimitry Andric     } else {
24240b57cec5SDimitry Andric       Py_XDECREF(child_ptr);
24250b57cec5SDimitry Andric     }
24260b57cec5SDimitry Andric   }
24270b57cec5SDimitry Andric 
24280b57cec5SDimitry Andric   return ret_val;
24290b57cec5SDimitry Andric }
24300b57cec5SDimitry Andric 
24310b57cec5SDimitry Andric ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
24320b57cec5SDimitry Andric     const StructuredData::ObjectSP &implementor_sp) {
24330b57cec5SDimitry Andric   Locker py_lock(this,
24340b57cec5SDimitry Andric                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
24350b57cec5SDimitry Andric 
24360b57cec5SDimitry Andric   static char callee_name[] = "get_type_name";
24370b57cec5SDimitry Andric 
24380b57cec5SDimitry Andric   ConstString ret_val;
24390b57cec5SDimitry Andric   bool got_string = false;
24400b57cec5SDimitry Andric   std::string buffer;
24410b57cec5SDimitry Andric 
24420b57cec5SDimitry Andric   if (!implementor_sp)
24430b57cec5SDimitry Andric     return ret_val;
24440b57cec5SDimitry Andric 
24450b57cec5SDimitry Andric   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24460b57cec5SDimitry Andric   if (!generic)
24470b57cec5SDimitry Andric     return ret_val;
24480b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
24490b57cec5SDimitry Andric                            (PyObject *)generic->GetValue());
24500b57cec5SDimitry Andric   if (!implementor.IsAllocated())
24510b57cec5SDimitry Andric     return ret_val;
24520b57cec5SDimitry Andric 
24530b57cec5SDimitry Andric   PythonObject pmeth(PyRefType::Owned,
24540b57cec5SDimitry Andric                      PyObject_GetAttrString(implementor.get(), callee_name));
24550b57cec5SDimitry Andric 
24560b57cec5SDimitry Andric   if (PyErr_Occurred())
24570b57cec5SDimitry Andric     PyErr_Clear();
24580b57cec5SDimitry Andric 
24590b57cec5SDimitry Andric   if (!pmeth.IsAllocated())
24600b57cec5SDimitry Andric     return ret_val;
24610b57cec5SDimitry Andric 
24620b57cec5SDimitry Andric   if (PyCallable_Check(pmeth.get()) == 0) {
24630b57cec5SDimitry Andric     if (PyErr_Occurred())
24640b57cec5SDimitry Andric       PyErr_Clear();
24650b57cec5SDimitry Andric     return ret_val;
24660b57cec5SDimitry Andric   }
24670b57cec5SDimitry Andric 
24680b57cec5SDimitry Andric   if (PyErr_Occurred())
24690b57cec5SDimitry Andric     PyErr_Clear();
24700b57cec5SDimitry Andric 
24710b57cec5SDimitry Andric   // right now we know this function exists and is callable..
24720b57cec5SDimitry Andric   PythonObject py_return(
24730b57cec5SDimitry Andric       PyRefType::Owned,
24740b57cec5SDimitry Andric       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
24750b57cec5SDimitry Andric 
24760b57cec5SDimitry Andric   // if it fails, print the error but otherwise go on
24770b57cec5SDimitry Andric   if (PyErr_Occurred()) {
24780b57cec5SDimitry Andric     PyErr_Print();
24790b57cec5SDimitry Andric     PyErr_Clear();
24800b57cec5SDimitry Andric   }
24810b57cec5SDimitry Andric 
24820b57cec5SDimitry Andric   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
24830b57cec5SDimitry Andric     PythonString py_string(PyRefType::Borrowed, py_return.get());
24840b57cec5SDimitry Andric     llvm::StringRef return_data(py_string.GetString());
24850b57cec5SDimitry Andric     if (!return_data.empty()) {
24860b57cec5SDimitry Andric       buffer.assign(return_data.data(), return_data.size());
24870b57cec5SDimitry Andric       got_string = true;
24880b57cec5SDimitry Andric     }
24890b57cec5SDimitry Andric   }
24900b57cec5SDimitry Andric 
24910b57cec5SDimitry Andric   if (got_string)
24920b57cec5SDimitry Andric     ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
24930b57cec5SDimitry Andric 
24940b57cec5SDimitry Andric   return ret_val;
24950b57cec5SDimitry Andric }
24960b57cec5SDimitry Andric 
24970b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
24980b57cec5SDimitry Andric     const char *impl_function, Process *process, std::string &output,
24990b57cec5SDimitry Andric     Status &error) {
25000b57cec5SDimitry Andric   bool ret_val;
25010b57cec5SDimitry Andric   if (!process) {
25020b57cec5SDimitry Andric     error.SetErrorString("no process");
25030b57cec5SDimitry Andric     return false;
25040b57cec5SDimitry Andric   }
25050b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
25060b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
25070b57cec5SDimitry Andric     return false;
25080b57cec5SDimitry Andric   }
25090b57cec5SDimitry Andric 
25100b57cec5SDimitry Andric   {
25110b57cec5SDimitry Andric     ProcessSP process_sp(process->shared_from_this());
25120b57cec5SDimitry Andric     Locker py_lock(this,
25130b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
25140b57cec5SDimitry Andric     ret_val = LLDBSWIGPythonRunScriptKeywordProcess(
25150b57cec5SDimitry Andric         impl_function, m_dictionary_name.c_str(), process_sp, output);
25160b57cec5SDimitry Andric     if (!ret_val)
25170b57cec5SDimitry Andric       error.SetErrorString("python script evaluation failed");
25180b57cec5SDimitry Andric   }
25190b57cec5SDimitry Andric   return ret_val;
25200b57cec5SDimitry Andric }
25210b57cec5SDimitry Andric 
25220b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
25230b57cec5SDimitry Andric     const char *impl_function, Thread *thread, std::string &output,
25240b57cec5SDimitry Andric     Status &error) {
25250b57cec5SDimitry Andric   bool ret_val;
25260b57cec5SDimitry Andric   if (!thread) {
25270b57cec5SDimitry Andric     error.SetErrorString("no thread");
25280b57cec5SDimitry Andric     return false;
25290b57cec5SDimitry Andric   }
25300b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
25310b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
25320b57cec5SDimitry Andric     return false;
25330b57cec5SDimitry Andric   }
25340b57cec5SDimitry Andric 
25350b57cec5SDimitry Andric   {
25360b57cec5SDimitry Andric     ThreadSP thread_sp(thread->shared_from_this());
25370b57cec5SDimitry Andric     Locker py_lock(this,
25380b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
25390b57cec5SDimitry Andric     ret_val = LLDBSWIGPythonRunScriptKeywordThread(
25400b57cec5SDimitry Andric         impl_function, m_dictionary_name.c_str(), thread_sp, output);
25410b57cec5SDimitry Andric     if (!ret_val)
25420b57cec5SDimitry Andric       error.SetErrorString("python script evaluation failed");
25430b57cec5SDimitry Andric   }
25440b57cec5SDimitry Andric   return ret_val;
25450b57cec5SDimitry Andric }
25460b57cec5SDimitry Andric 
25470b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
25480b57cec5SDimitry Andric     const char *impl_function, Target *target, std::string &output,
25490b57cec5SDimitry Andric     Status &error) {
25500b57cec5SDimitry Andric   bool ret_val;
25510b57cec5SDimitry Andric   if (!target) {
25520b57cec5SDimitry Andric     error.SetErrorString("no thread");
25530b57cec5SDimitry Andric     return false;
25540b57cec5SDimitry Andric   }
25550b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
25560b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
25570b57cec5SDimitry Andric     return false;
25580b57cec5SDimitry Andric   }
25590b57cec5SDimitry Andric 
25600b57cec5SDimitry Andric   {
25610b57cec5SDimitry Andric     TargetSP target_sp(target->shared_from_this());
25620b57cec5SDimitry Andric     Locker py_lock(this,
25630b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
25640b57cec5SDimitry Andric     ret_val = LLDBSWIGPythonRunScriptKeywordTarget(
25650b57cec5SDimitry Andric         impl_function, m_dictionary_name.c_str(), target_sp, output);
25660b57cec5SDimitry Andric     if (!ret_val)
25670b57cec5SDimitry Andric       error.SetErrorString("python script evaluation failed");
25680b57cec5SDimitry Andric   }
25690b57cec5SDimitry Andric   return ret_val;
25700b57cec5SDimitry Andric }
25710b57cec5SDimitry Andric 
25720b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
25730b57cec5SDimitry Andric     const char *impl_function, StackFrame *frame, std::string &output,
25740b57cec5SDimitry Andric     Status &error) {
25750b57cec5SDimitry Andric   bool ret_val;
25760b57cec5SDimitry Andric   if (!frame) {
25770b57cec5SDimitry Andric     error.SetErrorString("no frame");
25780b57cec5SDimitry Andric     return false;
25790b57cec5SDimitry Andric   }
25800b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
25810b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
25820b57cec5SDimitry Andric     return false;
25830b57cec5SDimitry Andric   }
25840b57cec5SDimitry Andric 
25850b57cec5SDimitry Andric   {
25860b57cec5SDimitry Andric     StackFrameSP frame_sp(frame->shared_from_this());
25870b57cec5SDimitry Andric     Locker py_lock(this,
25880b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
25890b57cec5SDimitry Andric     ret_val = LLDBSWIGPythonRunScriptKeywordFrame(
25900b57cec5SDimitry Andric         impl_function, m_dictionary_name.c_str(), frame_sp, output);
25910b57cec5SDimitry Andric     if (!ret_val)
25920b57cec5SDimitry Andric       error.SetErrorString("python script evaluation failed");
25930b57cec5SDimitry Andric   }
25940b57cec5SDimitry Andric   return ret_val;
25950b57cec5SDimitry Andric }
25960b57cec5SDimitry Andric 
25970b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
25980b57cec5SDimitry Andric     const char *impl_function, ValueObject *value, std::string &output,
25990b57cec5SDimitry Andric     Status &error) {
26000b57cec5SDimitry Andric   bool ret_val;
26010b57cec5SDimitry Andric   if (!value) {
26020b57cec5SDimitry Andric     error.SetErrorString("no value");
26030b57cec5SDimitry Andric     return false;
26040b57cec5SDimitry Andric   }
26050b57cec5SDimitry Andric   if (!impl_function || !impl_function[0]) {
26060b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
26070b57cec5SDimitry Andric     return false;
26080b57cec5SDimitry Andric   }
26090b57cec5SDimitry Andric 
26100b57cec5SDimitry Andric   {
26110b57cec5SDimitry Andric     ValueObjectSP value_sp(value->GetSP());
26120b57cec5SDimitry Andric     Locker py_lock(this,
26130b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
26140b57cec5SDimitry Andric     ret_val = LLDBSWIGPythonRunScriptKeywordValue(
26150b57cec5SDimitry Andric         impl_function, m_dictionary_name.c_str(), value_sp, output);
26160b57cec5SDimitry Andric     if (!ret_val)
26170b57cec5SDimitry Andric       error.SetErrorString("python script evaluation failed");
26180b57cec5SDimitry Andric   }
26190b57cec5SDimitry Andric   return ret_val;
26200b57cec5SDimitry Andric }
26210b57cec5SDimitry Andric 
26220b57cec5SDimitry Andric uint64_t replace_all(std::string &str, const std::string &oldStr,
26230b57cec5SDimitry Andric                      const std::string &newStr) {
26240b57cec5SDimitry Andric   size_t pos = 0;
26250b57cec5SDimitry Andric   uint64_t matches = 0;
26260b57cec5SDimitry Andric   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
26270b57cec5SDimitry Andric     matches++;
26280b57cec5SDimitry Andric     str.replace(pos, oldStr.length(), newStr);
26290b57cec5SDimitry Andric     pos += newStr.length();
26300b57cec5SDimitry Andric   }
26310b57cec5SDimitry Andric   return matches;
26320b57cec5SDimitry Andric }
26330b57cec5SDimitry Andric 
26340b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::LoadScriptingModule(
26350b57cec5SDimitry Andric     const char *pathname, bool can_reload, bool init_session,
26360b57cec5SDimitry Andric     lldb_private::Status &error, StructuredData::ObjectSP *module_sp) {
26370b57cec5SDimitry Andric   if (!pathname || !pathname[0]) {
26380b57cec5SDimitry Andric     error.SetErrorString("invalid pathname");
26390b57cec5SDimitry Andric     return false;
26400b57cec5SDimitry Andric   }
26410b57cec5SDimitry Andric 
26420b57cec5SDimitry Andric   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
26430b57cec5SDimitry Andric 
26440b57cec5SDimitry Andric   {
26450b57cec5SDimitry Andric     FileSpec target_file(pathname);
26460b57cec5SDimitry Andric     FileSystem::Instance().Resolve(target_file);
26470b57cec5SDimitry Andric     std::string basename(target_file.GetFilename().GetCString());
26480b57cec5SDimitry Andric 
26490b57cec5SDimitry Andric     StreamString command_stream;
26500b57cec5SDimitry Andric 
26510b57cec5SDimitry Andric     // Before executing Python code, lock the GIL.
26520b57cec5SDimitry Andric     Locker py_lock(this,
26530b57cec5SDimitry Andric                    Locker::AcquireLock |
26540b57cec5SDimitry Andric                        (init_session ? Locker::InitSession : 0) |
26550b57cec5SDimitry Andric                        Locker::NoSTDIN,
26560b57cec5SDimitry Andric                    Locker::FreeAcquiredLock |
26570b57cec5SDimitry Andric                        (init_session ? Locker::TearDownSession : 0));
26580b57cec5SDimitry Andric     namespace fs = llvm::sys::fs;
26590b57cec5SDimitry Andric     fs::file_status st;
26600b57cec5SDimitry Andric     std::error_code ec = status(target_file.GetPath(), st);
26610b57cec5SDimitry Andric 
26620b57cec5SDimitry Andric     if (ec || st.type() == fs::file_type::status_error ||
26630b57cec5SDimitry Andric         st.type() == fs::file_type::type_unknown ||
26640b57cec5SDimitry Andric         st.type() == fs::file_type::file_not_found) {
26650b57cec5SDimitry Andric       // if not a valid file of any sort, check if it might be a filename still
26660b57cec5SDimitry Andric       // dot can't be used but / and \ can, and if either is found, reject
26670b57cec5SDimitry Andric       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
26680b57cec5SDimitry Andric         error.SetErrorString("invalid pathname");
26690b57cec5SDimitry Andric         return false;
26700b57cec5SDimitry Andric       }
26710b57cec5SDimitry Andric       basename = pathname; // not a filename, probably a package of some sort,
26720b57cec5SDimitry Andric                            // let it go through
26730b57cec5SDimitry Andric     } else if (is_directory(st) || is_regular_file(st)) {
26740b57cec5SDimitry Andric       if (target_file.GetDirectory().IsEmpty()) {
26750b57cec5SDimitry Andric         error.SetErrorString("invalid directory name");
26760b57cec5SDimitry Andric         return false;
26770b57cec5SDimitry Andric       }
26780b57cec5SDimitry Andric 
26790b57cec5SDimitry Andric       std::string directory = target_file.GetDirectory().GetCString();
26800b57cec5SDimitry Andric       replace_all(directory, "\\", "\\\\");
26810b57cec5SDimitry Andric       replace_all(directory, "'", "\\'");
26820b57cec5SDimitry Andric 
26830b57cec5SDimitry Andric       // now make sure that Python has "directory" in the search path
26840b57cec5SDimitry Andric       StreamString command_stream;
26850b57cec5SDimitry Andric       command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
26860b57cec5SDimitry Andric                             "sys.path.insert(1,'%s');\n\n",
26870b57cec5SDimitry Andric                             directory.c_str(), directory.c_str());
26880b57cec5SDimitry Andric       bool syspath_retval =
26890b57cec5SDimitry Andric           ExecuteMultipleLines(command_stream.GetData(),
26900b57cec5SDimitry Andric                                ScriptInterpreter::ExecuteScriptOptions()
26910b57cec5SDimitry Andric                                    .SetEnableIO(false)
26920b57cec5SDimitry Andric                                    .SetSetLLDBGlobals(false))
26930b57cec5SDimitry Andric               .Success();
26940b57cec5SDimitry Andric       if (!syspath_retval) {
26950b57cec5SDimitry Andric         error.SetErrorString("Python sys.path handling failed");
26960b57cec5SDimitry Andric         return false;
26970b57cec5SDimitry Andric       }
26980b57cec5SDimitry Andric 
26990b57cec5SDimitry Andric       // strip .py or .pyc extension
27000b57cec5SDimitry Andric       ConstString extension = target_file.GetFileNameExtension();
27010b57cec5SDimitry Andric       if (extension) {
27020b57cec5SDimitry Andric         if (llvm::StringRef(extension.GetCString()) == ".py")
27030b57cec5SDimitry Andric           basename.resize(basename.length() - 3);
27040b57cec5SDimitry Andric         else if (llvm::StringRef(extension.GetCString()) == ".pyc")
27050b57cec5SDimitry Andric           basename.resize(basename.length() - 4);
27060b57cec5SDimitry Andric       }
27070b57cec5SDimitry Andric     } else {
27080b57cec5SDimitry Andric       error.SetErrorString("no known way to import this module specification");
27090b57cec5SDimitry Andric       return false;
27100b57cec5SDimitry Andric     }
27110b57cec5SDimitry Andric 
27120b57cec5SDimitry Andric     // check if the module is already import-ed
27130b57cec5SDimitry Andric     command_stream.Clear();
27140b57cec5SDimitry Andric     command_stream.Printf("sys.modules.__contains__('%s')", basename.c_str());
27150b57cec5SDimitry Andric     bool does_contain = false;
27160b57cec5SDimitry Andric     // this call will succeed if the module was ever imported in any Debugger
27170b57cec5SDimitry Andric     // in the lifetime of the process in which this LLDB framework is living
27180b57cec5SDimitry Andric     bool was_imported_globally =
27190b57cec5SDimitry Andric         (ExecuteOneLineWithReturn(
27200b57cec5SDimitry Andric              command_stream.GetData(),
27210b57cec5SDimitry Andric              ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain,
27220b57cec5SDimitry Andric              ScriptInterpreter::ExecuteScriptOptions()
27230b57cec5SDimitry Andric                  .SetEnableIO(false)
27240b57cec5SDimitry Andric                  .SetSetLLDBGlobals(false)) &&
27250b57cec5SDimitry Andric          does_contain);
27260b57cec5SDimitry Andric     // this call will fail if the module was not imported in this Debugger
27270b57cec5SDimitry Andric     // before
27280b57cec5SDimitry Andric     command_stream.Clear();
27290b57cec5SDimitry Andric     command_stream.Printf("sys.getrefcount(%s)", basename.c_str());
27300b57cec5SDimitry Andric     bool was_imported_locally = GetSessionDictionary()
27310b57cec5SDimitry Andric                                     .GetItemForKey(PythonString(basename))
27320b57cec5SDimitry Andric                                     .IsAllocated();
27330b57cec5SDimitry Andric 
27340b57cec5SDimitry Andric     bool was_imported = (was_imported_globally || was_imported_locally);
27350b57cec5SDimitry Andric 
27360b57cec5SDimitry Andric     if (was_imported && !can_reload) {
27370b57cec5SDimitry Andric       error.SetErrorString("module already imported");
27380b57cec5SDimitry Andric       return false;
27390b57cec5SDimitry Andric     }
27400b57cec5SDimitry Andric 
27410b57cec5SDimitry Andric     // now actually do the import
27420b57cec5SDimitry Andric     command_stream.Clear();
27430b57cec5SDimitry Andric 
27440b57cec5SDimitry Andric     if (was_imported) {
27450b57cec5SDimitry Andric       if (!was_imported_locally)
27460b57cec5SDimitry Andric         command_stream.Printf("import %s ; reload_module(%s)", basename.c_str(),
27470b57cec5SDimitry Andric                               basename.c_str());
27480b57cec5SDimitry Andric       else
27490b57cec5SDimitry Andric         command_stream.Printf("reload_module(%s)", basename.c_str());
27500b57cec5SDimitry Andric     } else
27510b57cec5SDimitry Andric       command_stream.Printf("import %s", basename.c_str());
27520b57cec5SDimitry Andric 
27530b57cec5SDimitry Andric     error = ExecuteMultipleLines(command_stream.GetData(),
27540b57cec5SDimitry Andric                                  ScriptInterpreter::ExecuteScriptOptions()
27550b57cec5SDimitry Andric                                      .SetEnableIO(false)
27560b57cec5SDimitry Andric                                      .SetSetLLDBGlobals(false));
27570b57cec5SDimitry Andric     if (error.Fail())
27580b57cec5SDimitry Andric       return false;
27590b57cec5SDimitry Andric 
27600b57cec5SDimitry Andric     // if we are here, everything worked
27610b57cec5SDimitry Andric     // call __lldb_init_module(debugger,dict)
27620b57cec5SDimitry Andric     if (!LLDBSwigPythonCallModuleInit(basename.c_str(),
27630b57cec5SDimitry Andric                                       m_dictionary_name.c_str(), debugger_sp)) {
27640b57cec5SDimitry Andric       error.SetErrorString("calling __lldb_init_module failed");
27650b57cec5SDimitry Andric       return false;
27660b57cec5SDimitry Andric     }
27670b57cec5SDimitry Andric 
27680b57cec5SDimitry Andric     if (module_sp) {
27690b57cec5SDimitry Andric       // everything went just great, now set the module object
27700b57cec5SDimitry Andric       command_stream.Clear();
27710b57cec5SDimitry Andric       command_stream.Printf("%s", basename.c_str());
27720b57cec5SDimitry Andric       void *module_pyobj = nullptr;
27730b57cec5SDimitry Andric       if (ExecuteOneLineWithReturn(
27740b57cec5SDimitry Andric               command_stream.GetData(),
27750b57cec5SDimitry Andric               ScriptInterpreter::eScriptReturnTypeOpaqueObject,
27760b57cec5SDimitry Andric               &module_pyobj) &&
27770b57cec5SDimitry Andric           module_pyobj)
27780b57cec5SDimitry Andric         *module_sp = std::make_shared<StructuredPythonObject>(module_pyobj);
27790b57cec5SDimitry Andric     }
27800b57cec5SDimitry Andric 
27810b57cec5SDimitry Andric     return true;
27820b57cec5SDimitry Andric   }
27830b57cec5SDimitry Andric }
27840b57cec5SDimitry Andric 
27850b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
27860b57cec5SDimitry Andric   if (!word || !word[0])
27870b57cec5SDimitry Andric     return false;
27880b57cec5SDimitry Andric 
27890b57cec5SDimitry Andric   llvm::StringRef word_sr(word);
27900b57cec5SDimitry Andric 
27910b57cec5SDimitry Andric   // filter out a few characters that would just confuse us and that are
27920b57cec5SDimitry Andric   // clearly not keyword material anyway
27930b57cec5SDimitry Andric   if (word_sr.find('"') != llvm::StringRef::npos ||
27940b57cec5SDimitry Andric       word_sr.find('\'') != llvm::StringRef::npos)
27950b57cec5SDimitry Andric     return false;
27960b57cec5SDimitry Andric 
27970b57cec5SDimitry Andric   StreamString command_stream;
27980b57cec5SDimitry Andric   command_stream.Printf("keyword.iskeyword('%s')", word);
27990b57cec5SDimitry Andric   bool result;
28000b57cec5SDimitry Andric   ExecuteScriptOptions options;
28010b57cec5SDimitry Andric   options.SetEnableIO(false);
28020b57cec5SDimitry Andric   options.SetMaskoutErrors(true);
28030b57cec5SDimitry Andric   options.SetSetLLDBGlobals(false);
28040b57cec5SDimitry Andric   if (ExecuteOneLineWithReturn(command_stream.GetData(),
28050b57cec5SDimitry Andric                                ScriptInterpreter::eScriptReturnTypeBool,
28060b57cec5SDimitry Andric                                &result, options))
28070b57cec5SDimitry Andric     return result;
28080b57cec5SDimitry Andric   return false;
28090b57cec5SDimitry Andric }
28100b57cec5SDimitry Andric 
28110b57cec5SDimitry Andric ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
28120b57cec5SDimitry Andric     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
28130b57cec5SDimitry Andric     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
28140b57cec5SDimitry Andric       m_old_asynch(debugger_sp->GetAsyncExecution()) {
28150b57cec5SDimitry Andric   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
28160b57cec5SDimitry Andric     m_debugger_sp->SetAsyncExecution(false);
28170b57cec5SDimitry Andric   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
28180b57cec5SDimitry Andric     m_debugger_sp->SetAsyncExecution(true);
28190b57cec5SDimitry Andric }
28200b57cec5SDimitry Andric 
28210b57cec5SDimitry Andric ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
28220b57cec5SDimitry Andric   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
28230b57cec5SDimitry Andric     m_debugger_sp->SetAsyncExecution(m_old_asynch);
28240b57cec5SDimitry Andric }
28250b57cec5SDimitry Andric 
28260b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
28270b57cec5SDimitry Andric     const char *impl_function, llvm::StringRef args,
28280b57cec5SDimitry Andric     ScriptedCommandSynchronicity synchronicity,
28290b57cec5SDimitry Andric     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
28300b57cec5SDimitry Andric     const lldb_private::ExecutionContext &exe_ctx) {
28310b57cec5SDimitry Andric   if (!impl_function) {
28320b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
28330b57cec5SDimitry Andric     return false;
28340b57cec5SDimitry Andric   }
28350b57cec5SDimitry Andric 
28360b57cec5SDimitry Andric   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
28370b57cec5SDimitry Andric   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
28380b57cec5SDimitry Andric 
28390b57cec5SDimitry Andric   if (!debugger_sp.get()) {
28400b57cec5SDimitry Andric     error.SetErrorString("invalid Debugger pointer");
28410b57cec5SDimitry Andric     return false;
28420b57cec5SDimitry Andric   }
28430b57cec5SDimitry Andric 
28440b57cec5SDimitry Andric   bool ret_val = false;
28450b57cec5SDimitry Andric 
28460b57cec5SDimitry Andric   std::string err_msg;
28470b57cec5SDimitry Andric 
28480b57cec5SDimitry Andric   {
28490b57cec5SDimitry Andric     Locker py_lock(this,
28500b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession |
28510b57cec5SDimitry Andric                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
28520b57cec5SDimitry Andric                    Locker::FreeLock | Locker::TearDownSession);
28530b57cec5SDimitry Andric 
28540b57cec5SDimitry Andric     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
28550b57cec5SDimitry Andric 
28560b57cec5SDimitry Andric     std::string args_str = args.str();
28570b57cec5SDimitry Andric     ret_val = LLDBSwigPythonCallCommand(
28580b57cec5SDimitry Andric         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
28590b57cec5SDimitry Andric         cmd_retobj, exe_ctx_ref_sp);
28600b57cec5SDimitry Andric   }
28610b57cec5SDimitry Andric 
28620b57cec5SDimitry Andric   if (!ret_val)
28630b57cec5SDimitry Andric     error.SetErrorString("unable to execute script function");
28640b57cec5SDimitry Andric   else
28650b57cec5SDimitry Andric     error.Clear();
28660b57cec5SDimitry Andric 
28670b57cec5SDimitry Andric   return ret_val;
28680b57cec5SDimitry Andric }
28690b57cec5SDimitry Andric 
28700b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
28710b57cec5SDimitry Andric     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
28720b57cec5SDimitry Andric     ScriptedCommandSynchronicity synchronicity,
28730b57cec5SDimitry Andric     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
28740b57cec5SDimitry Andric     const lldb_private::ExecutionContext &exe_ctx) {
28750b57cec5SDimitry Andric   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
28760b57cec5SDimitry Andric     error.SetErrorString("no function to execute");
28770b57cec5SDimitry Andric     return false;
28780b57cec5SDimitry Andric   }
28790b57cec5SDimitry Andric 
28800b57cec5SDimitry Andric   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
28810b57cec5SDimitry Andric   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
28820b57cec5SDimitry Andric 
28830b57cec5SDimitry Andric   if (!debugger_sp.get()) {
28840b57cec5SDimitry Andric     error.SetErrorString("invalid Debugger pointer");
28850b57cec5SDimitry Andric     return false;
28860b57cec5SDimitry Andric   }
28870b57cec5SDimitry Andric 
28880b57cec5SDimitry Andric   bool ret_val = false;
28890b57cec5SDimitry Andric 
28900b57cec5SDimitry Andric   std::string err_msg;
28910b57cec5SDimitry Andric 
28920b57cec5SDimitry Andric   {
28930b57cec5SDimitry Andric     Locker py_lock(this,
28940b57cec5SDimitry Andric                    Locker::AcquireLock | Locker::InitSession |
28950b57cec5SDimitry Andric                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
28960b57cec5SDimitry Andric                    Locker::FreeLock | Locker::TearDownSession);
28970b57cec5SDimitry Andric 
28980b57cec5SDimitry Andric     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
28990b57cec5SDimitry Andric 
29000b57cec5SDimitry Andric     std::string args_str = args.str();
29010b57cec5SDimitry Andric     ret_val = LLDBSwigPythonCallCommandObject(impl_obj_sp->GetValue(),
29020b57cec5SDimitry Andric                                               debugger_sp, args_str.c_str(),
29030b57cec5SDimitry Andric                                               cmd_retobj, exe_ctx_ref_sp);
29040b57cec5SDimitry Andric   }
29050b57cec5SDimitry Andric 
29060b57cec5SDimitry Andric   if (!ret_val)
29070b57cec5SDimitry Andric     error.SetErrorString("unable to execute script function");
29080b57cec5SDimitry Andric   else
29090b57cec5SDimitry Andric     error.Clear();
29100b57cec5SDimitry Andric 
29110b57cec5SDimitry Andric   return ret_val;
29120b57cec5SDimitry Andric }
29130b57cec5SDimitry Andric 
29140b57cec5SDimitry Andric // in Python, a special attribute __doc__ contains the docstring for an object
29150b57cec5SDimitry Andric // (function, method, class, ...) if any is defined Otherwise, the attribute's
29160b57cec5SDimitry Andric // value is None
29170b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
29180b57cec5SDimitry Andric                                                           std::string &dest) {
29190b57cec5SDimitry Andric   dest.clear();
29200b57cec5SDimitry Andric   if (!item || !*item)
29210b57cec5SDimitry Andric     return false;
29220b57cec5SDimitry Andric   std::string command(item);
29230b57cec5SDimitry Andric   command += ".__doc__";
29240b57cec5SDimitry Andric 
29250b57cec5SDimitry Andric   char *result_ptr = nullptr; // Python is going to point this to valid data if
29260b57cec5SDimitry Andric                               // ExecuteOneLineWithReturn returns successfully
29270b57cec5SDimitry Andric 
29280b57cec5SDimitry Andric   if (ExecuteOneLineWithReturn(
29290b57cec5SDimitry Andric           command.c_str(), ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
29300b57cec5SDimitry Andric           &result_ptr,
29310b57cec5SDimitry Andric           ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false))) {
29320b57cec5SDimitry Andric     if (result_ptr)
29330b57cec5SDimitry Andric       dest.assign(result_ptr);
29340b57cec5SDimitry Andric     return true;
29350b57cec5SDimitry Andric   } else {
29360b57cec5SDimitry Andric     StreamString str_stream;
29370b57cec5SDimitry Andric     str_stream.Printf(
29380b57cec5SDimitry Andric         "Function %s was not found. Containing module might be missing.", item);
29390b57cec5SDimitry Andric     dest = str_stream.GetString();
29400b57cec5SDimitry Andric     return false;
29410b57cec5SDimitry Andric   }
29420b57cec5SDimitry Andric }
29430b57cec5SDimitry Andric 
29440b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
29450b57cec5SDimitry Andric     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
29460b57cec5SDimitry Andric   bool got_string = false;
29470b57cec5SDimitry Andric   dest.clear();
29480b57cec5SDimitry Andric 
29490b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
29500b57cec5SDimitry Andric 
29510b57cec5SDimitry Andric   static char callee_name[] = "get_short_help";
29520b57cec5SDimitry Andric 
29530b57cec5SDimitry Andric   if (!cmd_obj_sp)
29540b57cec5SDimitry Andric     return false;
29550b57cec5SDimitry Andric 
29560b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
29570b57cec5SDimitry Andric                            (PyObject *)cmd_obj_sp->GetValue());
29580b57cec5SDimitry Andric 
29590b57cec5SDimitry Andric   if (!implementor.IsAllocated())
29600b57cec5SDimitry Andric     return false;
29610b57cec5SDimitry Andric 
29620b57cec5SDimitry Andric   PythonObject pmeth(PyRefType::Owned,
29630b57cec5SDimitry Andric                      PyObject_GetAttrString(implementor.get(), callee_name));
29640b57cec5SDimitry Andric 
29650b57cec5SDimitry Andric   if (PyErr_Occurred())
29660b57cec5SDimitry Andric     PyErr_Clear();
29670b57cec5SDimitry Andric 
29680b57cec5SDimitry Andric   if (!pmeth.IsAllocated())
29690b57cec5SDimitry Andric     return false;
29700b57cec5SDimitry Andric 
29710b57cec5SDimitry Andric   if (PyCallable_Check(pmeth.get()) == 0) {
29720b57cec5SDimitry Andric     if (PyErr_Occurred())
29730b57cec5SDimitry Andric       PyErr_Clear();
29740b57cec5SDimitry Andric     return false;
29750b57cec5SDimitry Andric   }
29760b57cec5SDimitry Andric 
29770b57cec5SDimitry Andric   if (PyErr_Occurred())
29780b57cec5SDimitry Andric     PyErr_Clear();
29790b57cec5SDimitry Andric 
29800b57cec5SDimitry Andric   // right now we know this function exists and is callable..
29810b57cec5SDimitry Andric   PythonObject py_return(
29820b57cec5SDimitry Andric       PyRefType::Owned,
29830b57cec5SDimitry Andric       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
29840b57cec5SDimitry Andric 
29850b57cec5SDimitry Andric   // if it fails, print the error but otherwise go on
29860b57cec5SDimitry Andric   if (PyErr_Occurred()) {
29870b57cec5SDimitry Andric     PyErr_Print();
29880b57cec5SDimitry Andric     PyErr_Clear();
29890b57cec5SDimitry Andric   }
29900b57cec5SDimitry Andric 
29910b57cec5SDimitry Andric   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
29920b57cec5SDimitry Andric     PythonString py_string(PyRefType::Borrowed, py_return.get());
29930b57cec5SDimitry Andric     llvm::StringRef return_data(py_string.GetString());
29940b57cec5SDimitry Andric     dest.assign(return_data.data(), return_data.size());
29950b57cec5SDimitry Andric     got_string = true;
29960b57cec5SDimitry Andric   }
29970b57cec5SDimitry Andric   return got_string;
29980b57cec5SDimitry Andric }
29990b57cec5SDimitry Andric 
30000b57cec5SDimitry Andric uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
30010b57cec5SDimitry Andric     StructuredData::GenericSP cmd_obj_sp) {
30020b57cec5SDimitry Andric   uint32_t result = 0;
30030b57cec5SDimitry Andric 
30040b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
30050b57cec5SDimitry Andric 
30060b57cec5SDimitry Andric   static char callee_name[] = "get_flags";
30070b57cec5SDimitry Andric 
30080b57cec5SDimitry Andric   if (!cmd_obj_sp)
30090b57cec5SDimitry Andric     return result;
30100b57cec5SDimitry Andric 
30110b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
30120b57cec5SDimitry Andric                            (PyObject *)cmd_obj_sp->GetValue());
30130b57cec5SDimitry Andric 
30140b57cec5SDimitry Andric   if (!implementor.IsAllocated())
30150b57cec5SDimitry Andric     return result;
30160b57cec5SDimitry Andric 
30170b57cec5SDimitry Andric   PythonObject pmeth(PyRefType::Owned,
30180b57cec5SDimitry Andric                      PyObject_GetAttrString(implementor.get(), callee_name));
30190b57cec5SDimitry Andric 
30200b57cec5SDimitry Andric   if (PyErr_Occurred())
30210b57cec5SDimitry Andric     PyErr_Clear();
30220b57cec5SDimitry Andric 
30230b57cec5SDimitry Andric   if (!pmeth.IsAllocated())
30240b57cec5SDimitry Andric     return result;
30250b57cec5SDimitry Andric 
30260b57cec5SDimitry Andric   if (PyCallable_Check(pmeth.get()) == 0) {
30270b57cec5SDimitry Andric     if (PyErr_Occurred())
30280b57cec5SDimitry Andric       PyErr_Clear();
30290b57cec5SDimitry Andric     return result;
30300b57cec5SDimitry Andric   }
30310b57cec5SDimitry Andric 
30320b57cec5SDimitry Andric   if (PyErr_Occurred())
30330b57cec5SDimitry Andric     PyErr_Clear();
30340b57cec5SDimitry Andric 
30350b57cec5SDimitry Andric   // right now we know this function exists and is callable..
30360b57cec5SDimitry Andric   PythonObject py_return(
30370b57cec5SDimitry Andric       PyRefType::Owned,
30380b57cec5SDimitry Andric       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
30390b57cec5SDimitry Andric 
30400b57cec5SDimitry Andric   // if it fails, print the error but otherwise go on
30410b57cec5SDimitry Andric   if (PyErr_Occurred()) {
30420b57cec5SDimitry Andric     PyErr_Print();
30430b57cec5SDimitry Andric     PyErr_Clear();
30440b57cec5SDimitry Andric   }
30450b57cec5SDimitry Andric 
30460b57cec5SDimitry Andric   if (py_return.IsAllocated() && PythonInteger::Check(py_return.get())) {
30470b57cec5SDimitry Andric     PythonInteger int_value(PyRefType::Borrowed, py_return.get());
30480b57cec5SDimitry Andric     result = int_value.GetInteger();
30490b57cec5SDimitry Andric   }
30500b57cec5SDimitry Andric 
30510b57cec5SDimitry Andric   return result;
30520b57cec5SDimitry Andric }
30530b57cec5SDimitry Andric 
30540b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
30550b57cec5SDimitry Andric     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
30560b57cec5SDimitry Andric   bool got_string = false;
30570b57cec5SDimitry Andric   dest.clear();
30580b57cec5SDimitry Andric 
30590b57cec5SDimitry Andric   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
30600b57cec5SDimitry Andric 
30610b57cec5SDimitry Andric   static char callee_name[] = "get_long_help";
30620b57cec5SDimitry Andric 
30630b57cec5SDimitry Andric   if (!cmd_obj_sp)
30640b57cec5SDimitry Andric     return false;
30650b57cec5SDimitry Andric 
30660b57cec5SDimitry Andric   PythonObject implementor(PyRefType::Borrowed,
30670b57cec5SDimitry Andric                            (PyObject *)cmd_obj_sp->GetValue());
30680b57cec5SDimitry Andric 
30690b57cec5SDimitry Andric   if (!implementor.IsAllocated())
30700b57cec5SDimitry Andric     return false;
30710b57cec5SDimitry Andric 
30720b57cec5SDimitry Andric   PythonObject pmeth(PyRefType::Owned,
30730b57cec5SDimitry Andric                      PyObject_GetAttrString(implementor.get(), callee_name));
30740b57cec5SDimitry Andric 
30750b57cec5SDimitry Andric   if (PyErr_Occurred())
30760b57cec5SDimitry Andric     PyErr_Clear();
30770b57cec5SDimitry Andric 
30780b57cec5SDimitry Andric   if (!pmeth.IsAllocated())
30790b57cec5SDimitry Andric     return false;
30800b57cec5SDimitry Andric 
30810b57cec5SDimitry Andric   if (PyCallable_Check(pmeth.get()) == 0) {
30820b57cec5SDimitry Andric     if (PyErr_Occurred())
30830b57cec5SDimitry Andric       PyErr_Clear();
30840b57cec5SDimitry Andric 
30850b57cec5SDimitry Andric     return false;
30860b57cec5SDimitry Andric   }
30870b57cec5SDimitry Andric 
30880b57cec5SDimitry Andric   if (PyErr_Occurred())
30890b57cec5SDimitry Andric     PyErr_Clear();
30900b57cec5SDimitry Andric 
30910b57cec5SDimitry Andric   // right now we know this function exists and is callable..
30920b57cec5SDimitry Andric   PythonObject py_return(
30930b57cec5SDimitry Andric       PyRefType::Owned,
30940b57cec5SDimitry Andric       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
30950b57cec5SDimitry Andric 
30960b57cec5SDimitry Andric   // if it fails, print the error but otherwise go on
30970b57cec5SDimitry Andric   if (PyErr_Occurred()) {
30980b57cec5SDimitry Andric     PyErr_Print();
30990b57cec5SDimitry Andric     PyErr_Clear();
31000b57cec5SDimitry Andric   }
31010b57cec5SDimitry Andric 
31020b57cec5SDimitry Andric   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
31030b57cec5SDimitry Andric     PythonString str(PyRefType::Borrowed, py_return.get());
31040b57cec5SDimitry Andric     llvm::StringRef str_data(str.GetString());
31050b57cec5SDimitry Andric     dest.assign(str_data.data(), str_data.size());
31060b57cec5SDimitry Andric     got_string = true;
31070b57cec5SDimitry Andric   }
31080b57cec5SDimitry Andric 
31090b57cec5SDimitry Andric   return got_string;
31100b57cec5SDimitry Andric }
31110b57cec5SDimitry Andric 
31120b57cec5SDimitry Andric std::unique_ptr<ScriptInterpreterLocker>
31130b57cec5SDimitry Andric ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
31140b57cec5SDimitry Andric   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
31150b57cec5SDimitry Andric       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
31160b57cec5SDimitry Andric       Locker::FreeLock | Locker::TearDownSession));
31170b57cec5SDimitry Andric   return py_lock;
31180b57cec5SDimitry Andric }
31190b57cec5SDimitry Andric 
31200b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::InitializePrivate() {
31210b57cec5SDimitry Andric   if (g_initialized)
31220b57cec5SDimitry Andric     return;
31230b57cec5SDimitry Andric 
31240b57cec5SDimitry Andric   g_initialized = true;
31250b57cec5SDimitry Andric 
31260b57cec5SDimitry Andric   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
31270b57cec5SDimitry Andric   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
31280b57cec5SDimitry Andric 
31290b57cec5SDimitry Andric   // RAII-based initialization which correctly handles multiple-initialization,
31300b57cec5SDimitry Andric   // version- specific differences among Python 2 and Python 3, and saving and
31310b57cec5SDimitry Andric   // restoring various other pieces of state that can get mucked with during
31320b57cec5SDimitry Andric   // initialization.
31330b57cec5SDimitry Andric   InitializePythonRAII initialize_guard;
31340b57cec5SDimitry Andric 
31350b57cec5SDimitry Andric   LLDBSwigPyInit();
31360b57cec5SDimitry Andric 
31370b57cec5SDimitry Andric   // Update the path python uses to search for modules to include the current
31380b57cec5SDimitry Andric   // directory.
31390b57cec5SDimitry Andric 
31400b57cec5SDimitry Andric   PyRun_SimpleString("import sys");
31410b57cec5SDimitry Andric   AddToSysPath(AddLocation::End, ".");
31420b57cec5SDimitry Andric 
31430b57cec5SDimitry Andric   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
31440b57cec5SDimitry Andric   // that use a backslash as the path separator, this will result in executing
31450b57cec5SDimitry Andric   // python code containing paths with unescaped backslashes.  But Python also
31460b57cec5SDimitry Andric   // accepts forward slashes, so to make life easier we just use that.
31470b57cec5SDimitry Andric   if (FileSpec file_spec = GetPythonDir())
31480b57cec5SDimitry Andric     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
31490b57cec5SDimitry Andric   if (FileSpec file_spec = HostInfo::GetShlibDir())
31500b57cec5SDimitry Andric     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
31510b57cec5SDimitry Andric 
31520b57cec5SDimitry Andric   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
31530b57cec5SDimitry Andric                      "lldb.embedded_interpreter; from "
31540b57cec5SDimitry Andric                      "lldb.embedded_interpreter import run_python_interpreter; "
31550b57cec5SDimitry Andric                      "from lldb.embedded_interpreter import run_one_line");
31560b57cec5SDimitry Andric }
31570b57cec5SDimitry Andric 
31580b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
31590b57cec5SDimitry Andric                                                std::string path) {
31600b57cec5SDimitry Andric   std::string path_copy;
31610b57cec5SDimitry Andric 
31620b57cec5SDimitry Andric   std::string statement;
31630b57cec5SDimitry Andric   if (location == AddLocation::Beginning) {
31640b57cec5SDimitry Andric     statement.assign("sys.path.insert(0,\"");
31650b57cec5SDimitry Andric     statement.append(path);
31660b57cec5SDimitry Andric     statement.append("\")");
31670b57cec5SDimitry Andric   } else {
31680b57cec5SDimitry Andric     statement.assign("sys.path.append(\"");
31690b57cec5SDimitry Andric     statement.append(path);
31700b57cec5SDimitry Andric     statement.append("\")");
31710b57cec5SDimitry Andric   }
31720b57cec5SDimitry Andric   PyRun_SimpleString(statement.c_str());
31730b57cec5SDimitry Andric }
31740b57cec5SDimitry Andric 
31750b57cec5SDimitry Andric // We are intentionally NOT calling Py_Finalize here (this would be the logical
31760b57cec5SDimitry Andric // place to call it).  Calling Py_Finalize here causes test suite runs to seg
31770b57cec5SDimitry Andric // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
31780b57cec5SDimitry Andric // be called 'at_exit'.  When the test suite Python harness finishes up, it
31790b57cec5SDimitry Andric // calls Py_Finalize, which calls all the 'at_exit' registered functions.
31800b57cec5SDimitry Andric // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
31810b57cec5SDimitry Andric // which calls ScriptInterpreter::Terminate, which calls
31820b57cec5SDimitry Andric // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
31830b57cec5SDimitry Andric // end up with Py_Finalize being called from within Py_Finalize, which results
31840b57cec5SDimitry Andric // in a seg fault. Since this function only gets called when lldb is shutting
31850b57cec5SDimitry Andric // down and going away anyway, the fact that we don't actually call Py_Finalize
31860b57cec5SDimitry Andric // should not cause any problems (everything should shut down/go away anyway
31870b57cec5SDimitry Andric // when the process exits).
31880b57cec5SDimitry Andric //
31890b57cec5SDimitry Andric // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
31900b57cec5SDimitry Andric 
31910b57cec5SDimitry Andric #endif // LLDB_DISABLE_PYTHON
3192