180814287SRaphael Isemann //===-- ScriptInterpreterPython.cpp ---------------------------------------===//
22c1f46dcSZachary Turner //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
62c1f46dcSZachary Turner //
72c1f46dcSZachary Turner //===----------------------------------------------------------------------===//
82c1f46dcSZachary Turner 
959998b7bSJonas Devlieghere #include "lldb/Host/Config.h"
10d68983e3SPavel Labath 
114e26cf2cSJonas Devlieghere #if LLDB_ENABLE_PYTHON
12d68983e3SPavel Labath 
1341de9a97SKate Stone // LLDB Python header must be included first
142c1f46dcSZachary Turner #include "lldb-python.h"
1541de9a97SKate Stone 
162c1f46dcSZachary Turner #include "PythonDataObjects.h"
179357b5d0Sserge-sans-paille #include "PythonReadline.h"
1863dd5d25SJonas Devlieghere #include "ScriptInterpreterPythonImpl.h"
1941ae8e74SKuba Mracek #include "lldb/API/SBFrame.h"
2063dd5d25SJonas Devlieghere #include "lldb/API/SBValue.h"
212c1f46dcSZachary Turner #include "lldb/Breakpoint/StoppointCallbackContext.h"
222c1f46dcSZachary Turner #include "lldb/Breakpoint/WatchpointOptions.h"
232c1f46dcSZachary Turner #include "lldb/Core/Communication.h"
242c1f46dcSZachary Turner #include "lldb/Core/Debugger.h"
252c1f46dcSZachary Turner #include "lldb/Core/PluginManager.h"
262c1f46dcSZachary Turner #include "lldb/Core/ValueObject.h"
272c1f46dcSZachary Turner #include "lldb/DataFormatters/TypeSummary.h"
284eff2d31SZachary Turner #include "lldb/Host/FileSystem.h"
292c1f46dcSZachary Turner #include "lldb/Host/HostInfo.h"
302c1f46dcSZachary Turner #include "lldb/Host/Pipe.h"
312c1f46dcSZachary Turner #include "lldb/Interpreter/CommandInterpreter.h"
322c1f46dcSZachary Turner #include "lldb/Interpreter/CommandReturnObject.h"
332c1f46dcSZachary Turner #include "lldb/Target/Thread.h"
342c1f46dcSZachary Turner #include "lldb/Target/ThreadPlan.h"
3538d0632eSPavel Labath #include "lldb/Utility/Timer.h"
3622c8efcdSZachary Turner #include "llvm/ADT/STLExtras.h"
37b9c1b51eSKate Stone #include "llvm/ADT/StringRef.h"
38d79273c9SJonas Devlieghere #include "llvm/Support/Error.h"
397d86ee5aSZachary Turner #include "llvm/Support/FileSystem.h"
402fce1137SLawrence D'Anna #include "llvm/Support/FormatAdapters.h"
412c1f46dcSZachary Turner 
429a6c7572SJonas Devlieghere #include <memory>
439a6c7572SJonas Devlieghere #include <mutex>
449a6c7572SJonas Devlieghere #include <stdio.h>
459a6c7572SJonas Devlieghere #include <stdlib.h>
469a6c7572SJonas Devlieghere #include <string>
479a6c7572SJonas Devlieghere 
482c1f46dcSZachary Turner using namespace lldb;
492c1f46dcSZachary Turner using namespace lldb_private;
50722b6189SLawrence D'Anna using namespace lldb_private::python;
5104edd189SLawrence D'Anna using llvm::Expected;
522c1f46dcSZachary Turner 
53bba9ba8dSJonas Devlieghere LLDB_PLUGIN_DEFINE(ScriptInterpreterPython)
54fbb4d1e4SJonas Devlieghere 
55b01b1087SJonas Devlieghere // Defined in the SWIG source file
56b01b1087SJonas Devlieghere #if PY_MAJOR_VERSION >= 3
57b01b1087SJonas Devlieghere extern "C" PyObject *PyInit__lldb(void);
58b01b1087SJonas Devlieghere 
59b01b1087SJonas Devlieghere #define LLDBSwigPyInit PyInit__lldb
60b01b1087SJonas Devlieghere 
61b01b1087SJonas Devlieghere #else
62b01b1087SJonas Devlieghere extern "C" void init_lldb(void);
63b01b1087SJonas Devlieghere 
64b01b1087SJonas Devlieghere #define LLDBSwigPyInit init_lldb
65b01b1087SJonas Devlieghere #endif
66b01b1087SJonas Devlieghere 
6705495c5dSJonas Devlieghere // These prototypes are the Pythonic implementations of the required callbacks.
6805495c5dSJonas Devlieghere // Although these are scripting-language specific, their definition depends on
6905495c5dSJonas Devlieghere // the public API.
70a69bbe02SLawrence D'Anna 
71a69bbe02SLawrence D'Anna #pragma clang diagnostic push
72a69bbe02SLawrence D'Anna #pragma clang diagnostic ignored "-Wreturn-type-c-linkage"
73a69bbe02SLawrence D'Anna 
741cc0ba4cSAlexandre Ganea // Disable warning C4190: 'LLDBSwigPythonBreakpointCallbackFunction' has
751cc0ba4cSAlexandre Ganea // C-linkage specified, but returns UDT 'llvm::Expected<bool>' which is
761cc0ba4cSAlexandre Ganea // incompatible with C
771cc0ba4cSAlexandre Ganea #if _MSC_VER
781cc0ba4cSAlexandre Ganea #pragma warning (push)
791cc0ba4cSAlexandre Ganea #pragma warning (disable : 4190)
801cc0ba4cSAlexandre Ganea #endif
811cc0ba4cSAlexandre Ganea 
82a69bbe02SLawrence D'Anna extern "C" llvm::Expected<bool> LLDBSwigPythonBreakpointCallbackFunction(
83b01b1087SJonas Devlieghere     const char *python_function_name, const char *session_dictionary_name,
84b01b1087SJonas Devlieghere     const lldb::StackFrameSP &sb_frame,
85a69bbe02SLawrence D'Anna     const lldb::BreakpointLocationSP &sb_bp_loc, StructuredDataImpl *args_impl);
86a69bbe02SLawrence D'Anna 
871cc0ba4cSAlexandre Ganea #if _MSC_VER
881cc0ba4cSAlexandre Ganea #pragma warning (pop)
891cc0ba4cSAlexandre Ganea #endif
901cc0ba4cSAlexandre Ganea 
91a69bbe02SLawrence D'Anna #pragma clang diagnostic pop
92b01b1087SJonas Devlieghere 
93b01b1087SJonas Devlieghere extern "C" bool LLDBSwigPythonWatchpointCallbackFunction(
94b01b1087SJonas Devlieghere     const char *python_function_name, const char *session_dictionary_name,
95b01b1087SJonas Devlieghere     const lldb::StackFrameSP &sb_frame, const lldb::WatchpointSP &sb_wp);
96b01b1087SJonas Devlieghere 
97b01b1087SJonas Devlieghere extern "C" bool LLDBSwigPythonCallTypeScript(
98b01b1087SJonas Devlieghere     const char *python_function_name, void *session_dictionary,
99b01b1087SJonas Devlieghere     const lldb::ValueObjectSP &valobj_sp, void **pyfunct_wrapper,
100b01b1087SJonas Devlieghere     const lldb::TypeSummaryOptionsSP &options_sp, std::string &retval);
101b01b1087SJonas Devlieghere 
102b01b1087SJonas Devlieghere extern "C" void *
103b01b1087SJonas Devlieghere LLDBSwigPythonCreateSyntheticProvider(const char *python_class_name,
104b01b1087SJonas Devlieghere                                       const char *session_dictionary_name,
105b01b1087SJonas Devlieghere                                       const lldb::ValueObjectSP &valobj_sp);
106b01b1087SJonas Devlieghere 
107b01b1087SJonas Devlieghere extern "C" void *
108b01b1087SJonas Devlieghere LLDBSwigPythonCreateCommandObject(const char *python_class_name,
109b01b1087SJonas Devlieghere                                   const char *session_dictionary_name,
110b01b1087SJonas Devlieghere                                   const lldb::DebuggerSP debugger_sp);
111b01b1087SJonas Devlieghere 
112b01b1087SJonas Devlieghere extern "C" void *LLDBSwigPythonCreateScriptedThreadPlan(
113b01b1087SJonas Devlieghere     const char *python_class_name, const char *session_dictionary_name,
11427a14f19SJim Ingham     StructuredDataImpl *args_data,
11593c98346SJim Ingham     std::string &error_string,
116b01b1087SJonas Devlieghere     const lldb::ThreadPlanSP &thread_plan_sp);
117b01b1087SJonas Devlieghere 
118b01b1087SJonas Devlieghere extern "C" bool LLDBSWIGPythonCallThreadPlan(void *implementor,
119b01b1087SJonas Devlieghere                                              const char *method_name,
120b01b1087SJonas Devlieghere                                              Event *event_sp, bool &got_error);
121b01b1087SJonas Devlieghere 
122b01b1087SJonas Devlieghere extern "C" void *LLDBSwigPythonCreateScriptedBreakpointResolver(
123b01b1087SJonas Devlieghere     const char *python_class_name, const char *session_dictionary_name,
124b01b1087SJonas Devlieghere     lldb_private::StructuredDataImpl *args, lldb::BreakpointSP &bkpt_sp);
125b01b1087SJonas Devlieghere 
126b01b1087SJonas Devlieghere extern "C" unsigned int
127b01b1087SJonas Devlieghere LLDBSwigPythonCallBreakpointResolver(void *implementor, const char *method_name,
128b01b1087SJonas Devlieghere                                      lldb_private::SymbolContext *sym_ctx);
129b01b1087SJonas Devlieghere 
1301b1d9815SJim Ingham extern "C" void *LLDBSwigPythonCreateScriptedStopHook(
1311b1d9815SJim Ingham     TargetSP target_sp, const char *python_class_name,
1321b1d9815SJim Ingham     const char *session_dictionary_name, lldb_private::StructuredDataImpl *args,
1331b1d9815SJim Ingham     lldb_private::Status &error);
1341b1d9815SJim Ingham 
1351b1d9815SJim Ingham extern "C" bool
1361b1d9815SJim Ingham LLDBSwigPythonStopHookCallHandleStop(void *implementor,
1371b1d9815SJim Ingham                                      lldb::ExecutionContextRefSP exc_ctx,
1381b1d9815SJim Ingham                                      lldb::StreamSP stream);
1391b1d9815SJim Ingham 
140b01b1087SJonas Devlieghere extern "C" size_t LLDBSwigPython_CalculateNumChildren(void *implementor,
141b01b1087SJonas Devlieghere                                                       uint32_t max);
142b01b1087SJonas Devlieghere 
143b01b1087SJonas Devlieghere extern "C" void *LLDBSwigPython_GetChildAtIndex(void *implementor,
144b01b1087SJonas Devlieghere                                                 uint32_t idx);
145b01b1087SJonas Devlieghere 
146b01b1087SJonas Devlieghere extern "C" int LLDBSwigPython_GetIndexOfChildWithName(void *implementor,
147b01b1087SJonas Devlieghere                                                       const char *child_name);
148b01b1087SJonas Devlieghere 
149b01b1087SJonas Devlieghere extern "C" void *LLDBSWIGPython_CastPyObjectToSBValue(void *data);
150b01b1087SJonas Devlieghere 
151b01b1087SJonas Devlieghere extern lldb::ValueObjectSP
152b01b1087SJonas Devlieghere LLDBSWIGPython_GetValueObjectSPFromSBValue(void *data);
153b01b1087SJonas Devlieghere 
154b01b1087SJonas Devlieghere extern "C" bool LLDBSwigPython_UpdateSynthProviderInstance(void *implementor);
155b01b1087SJonas Devlieghere 
156b01b1087SJonas Devlieghere extern "C" bool
157b01b1087SJonas Devlieghere LLDBSwigPython_MightHaveChildrenSynthProviderInstance(void *implementor);
158b01b1087SJonas Devlieghere 
159b01b1087SJonas Devlieghere extern "C" void *
160b01b1087SJonas Devlieghere LLDBSwigPython_GetValueSynthProviderInstance(void *implementor);
161b01b1087SJonas Devlieghere 
162b01b1087SJonas Devlieghere extern "C" bool
163b01b1087SJonas Devlieghere LLDBSwigPythonCallCommand(const char *python_function_name,
164b01b1087SJonas Devlieghere                           const char *session_dictionary_name,
165b01b1087SJonas Devlieghere                           lldb::DebuggerSP &debugger, const char *args,
166b01b1087SJonas Devlieghere                           lldb_private::CommandReturnObject &cmd_retobj,
167b01b1087SJonas Devlieghere                           lldb::ExecutionContextRefSP exe_ctx_ref_sp);
168b01b1087SJonas Devlieghere 
169b01b1087SJonas Devlieghere extern "C" bool
170b01b1087SJonas Devlieghere LLDBSwigPythonCallCommandObject(void *implementor, lldb::DebuggerSP &debugger,
171b01b1087SJonas Devlieghere                                 const char *args,
172b01b1087SJonas Devlieghere                                 lldb_private::CommandReturnObject &cmd_retobj,
173b01b1087SJonas Devlieghere                                 lldb::ExecutionContextRefSP exe_ctx_ref_sp);
174b01b1087SJonas Devlieghere 
175b01b1087SJonas Devlieghere extern "C" bool
176b01b1087SJonas Devlieghere LLDBSwigPythonCallModuleInit(const char *python_module_name,
177b01b1087SJonas Devlieghere                              const char *session_dictionary_name,
178b01b1087SJonas Devlieghere                              lldb::DebuggerSP &debugger);
179b01b1087SJonas Devlieghere 
180b01b1087SJonas Devlieghere extern "C" void *
181b01b1087SJonas Devlieghere LLDBSWIGPythonCreateOSPlugin(const char *python_class_name,
182b01b1087SJonas Devlieghere                              const char *session_dictionary_name,
183b01b1087SJonas Devlieghere                              const lldb::ProcessSP &process_sp);
184b01b1087SJonas Devlieghere 
185b01b1087SJonas Devlieghere extern "C" void *
186b01b1087SJonas Devlieghere LLDBSWIGPython_CreateFrameRecognizer(const char *python_class_name,
187b01b1087SJonas Devlieghere                                      const char *session_dictionary_name);
188b01b1087SJonas Devlieghere 
189b01b1087SJonas Devlieghere extern "C" void *
190b01b1087SJonas Devlieghere LLDBSwigPython_GetRecognizedArguments(void *implementor,
191b01b1087SJonas Devlieghere                                       const lldb::StackFrameSP &frame_sp);
192b01b1087SJonas Devlieghere 
193b01b1087SJonas Devlieghere extern "C" bool LLDBSWIGPythonRunScriptKeywordProcess(
194b01b1087SJonas Devlieghere     const char *python_function_name, const char *session_dictionary_name,
195b01b1087SJonas Devlieghere     lldb::ProcessSP &process, std::string &output);
196b01b1087SJonas Devlieghere 
197b01b1087SJonas Devlieghere extern "C" bool LLDBSWIGPythonRunScriptKeywordThread(
198b01b1087SJonas Devlieghere     const char *python_function_name, const char *session_dictionary_name,
199b01b1087SJonas Devlieghere     lldb::ThreadSP &thread, std::string &output);
200b01b1087SJonas Devlieghere 
201b01b1087SJonas Devlieghere extern "C" bool LLDBSWIGPythonRunScriptKeywordTarget(
202b01b1087SJonas Devlieghere     const char *python_function_name, const char *session_dictionary_name,
203b01b1087SJonas Devlieghere     lldb::TargetSP &target, std::string &output);
204b01b1087SJonas Devlieghere 
205b01b1087SJonas Devlieghere extern "C" bool LLDBSWIGPythonRunScriptKeywordFrame(
206b01b1087SJonas Devlieghere     const char *python_function_name, const char *session_dictionary_name,
207b01b1087SJonas Devlieghere     lldb::StackFrameSP &frame, std::string &output);
208b01b1087SJonas Devlieghere 
209b01b1087SJonas Devlieghere extern "C" bool LLDBSWIGPythonRunScriptKeywordValue(
210b01b1087SJonas Devlieghere     const char *python_function_name, const char *session_dictionary_name,
211b01b1087SJonas Devlieghere     lldb::ValueObjectSP &value, std::string &output);
212b01b1087SJonas Devlieghere 
213b01b1087SJonas Devlieghere extern "C" void *
214b01b1087SJonas Devlieghere LLDBSWIGPython_GetDynamicSetting(void *module, const char *setting,
215b01b1087SJonas Devlieghere                                  const lldb::TargetSP &target_sp);
216b01b1087SJonas Devlieghere 
2172c1f46dcSZachary Turner static bool g_initialized = false;
2182c1f46dcSZachary Turner 
219b9c1b51eSKate Stone namespace {
22022c8efcdSZachary Turner 
22105097246SAdrian Prantl // Initializing Python is not a straightforward process.  We cannot control
22205097246SAdrian Prantl // what external code may have done before getting to this point in LLDB,
22305097246SAdrian Prantl // including potentially having already initialized Python, so we need to do a
22405097246SAdrian Prantl // lot of work to ensure that the existing state of the system is maintained
22505097246SAdrian Prantl // across our initialization.  We do this by using an RAII pattern where we
22605097246SAdrian Prantl // save off initial state at the beginning, and restore it at the end
227b9c1b51eSKate Stone struct InitializePythonRAII {
228079fe48aSZachary Turner public:
229b9c1b51eSKate Stone   InitializePythonRAII()
230b9c1b51eSKate Stone       : m_gil_state(PyGILState_UNLOCKED), m_was_already_initialized(false) {
231079fe48aSZachary Turner     InitializePythonHome();
232079fe48aSZachary Turner 
2339357b5d0Sserge-sans-paille #ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
2349357b5d0Sserge-sans-paille     // Python's readline is incompatible with libedit being linked into lldb.
2359357b5d0Sserge-sans-paille     // Provide a patched version local to the embedded interpreter.
2369357b5d0Sserge-sans-paille     bool ReadlinePatched = false;
2379357b5d0Sserge-sans-paille     for (auto *p = PyImport_Inittab; p->name != NULL; p++) {
2389357b5d0Sserge-sans-paille       if (strcmp(p->name, "readline") == 0) {
2399357b5d0Sserge-sans-paille         p->initfunc = initlldb_readline;
2409357b5d0Sserge-sans-paille         break;
2419357b5d0Sserge-sans-paille       }
2429357b5d0Sserge-sans-paille     }
2439357b5d0Sserge-sans-paille     if (!ReadlinePatched) {
2449357b5d0Sserge-sans-paille       PyImport_AppendInittab("readline", initlldb_readline);
2459357b5d0Sserge-sans-paille       ReadlinePatched = true;
2469357b5d0Sserge-sans-paille     }
2479357b5d0Sserge-sans-paille #endif
2489357b5d0Sserge-sans-paille 
24974587a0eSVadim Chugunov     // Register _lldb as a built-in module.
25005495c5dSJonas Devlieghere     PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
25174587a0eSVadim Chugunov 
252079fe48aSZachary Turner // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
253079fe48aSZachary Turner // calling `Py_Initialize` and `PyEval_InitThreads`.  < 3.2 requires that you
254079fe48aSZachary Turner // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
255079fe48aSZachary Turner #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
256079fe48aSZachary Turner     Py_InitializeEx(0);
257079fe48aSZachary Turner     InitializeThreadsPrivate();
258079fe48aSZachary Turner #else
259079fe48aSZachary Turner     InitializeThreadsPrivate();
260079fe48aSZachary Turner     Py_InitializeEx(0);
261079fe48aSZachary Turner #endif
262079fe48aSZachary Turner   }
263079fe48aSZachary Turner 
264b9c1b51eSKate Stone   ~InitializePythonRAII() {
265b9c1b51eSKate Stone     if (m_was_already_initialized) {
2663b7e1981SPavel Labath       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
2673b7e1981SPavel Labath       LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
2681b6700efSTatyana Krasnukha                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
269079fe48aSZachary Turner       PyGILState_Release(m_gil_state);
270b9c1b51eSKate Stone     } else {
271079fe48aSZachary Turner       // We initialized the threads in this function, just unlock the GIL.
272079fe48aSZachary Turner       PyEval_SaveThread();
273079fe48aSZachary Turner     }
274079fe48aSZachary Turner   }
275079fe48aSZachary Turner 
276079fe48aSZachary Turner private:
277b9c1b51eSKate Stone   void InitializePythonHome() {
2783ec3f62fSHaibo Huang #if LLDB_EMBED_PYTHON_HOME
2793ec3f62fSHaibo Huang #if PY_MAJOR_VERSION >= 3
2803ec3f62fSHaibo Huang     typedef wchar_t* str_type;
2813ec3f62fSHaibo Huang #else
2823ec3f62fSHaibo Huang     typedef char* str_type;
2833ec3f62fSHaibo Huang #endif
2843ec3f62fSHaibo Huang     static str_type g_python_home = []() -> str_type {
2853ec3f62fSHaibo Huang       const char *lldb_python_home = LLDB_PYTHON_HOME;
2863ec3f62fSHaibo Huang       const char *absolute_python_home = nullptr;
2873ec3f62fSHaibo Huang       llvm::SmallString<64> path;
2883ec3f62fSHaibo Huang       if (llvm::sys::path::is_absolute(lldb_python_home)) {
2893ec3f62fSHaibo Huang         absolute_python_home = lldb_python_home;
2903ec3f62fSHaibo Huang       } else {
2913ec3f62fSHaibo Huang         FileSpec spec = HostInfo::GetShlibDir();
2923ec3f62fSHaibo Huang         if (!spec)
2933ec3f62fSHaibo Huang           return nullptr;
2943ec3f62fSHaibo Huang         spec.GetPath(path);
2953ec3f62fSHaibo Huang         llvm::sys::path::append(path, lldb_python_home);
2963ec3f62fSHaibo Huang         absolute_python_home = path.c_str();
2973ec3f62fSHaibo Huang       }
29822c8efcdSZachary Turner #if PY_MAJOR_VERSION >= 3
29922c8efcdSZachary Turner       size_t size = 0;
3003ec3f62fSHaibo Huang       return Py_DecodeLocale(absolute_python_home, &size);
30122c8efcdSZachary Turner #else
3023ec3f62fSHaibo Huang       return strdup(absolute_python_home);
30322c8efcdSZachary Turner #endif
3043ec3f62fSHaibo Huang     }();
3053ec3f62fSHaibo Huang     if (g_python_home != nullptr) {
306079fe48aSZachary Turner       Py_SetPythonHome(g_python_home);
3073ec3f62fSHaibo Huang     }
308386f00dbSDavide Italiano #else
309386f00dbSDavide Italiano #if defined(__APPLE__) && PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION == 7
31063dd5d25SJonas Devlieghere     // For Darwin, the only Python version supported is the one shipped in the
31163dd5d25SJonas Devlieghere     // OS OS and linked with lldb. Other installation of Python may have higher
3124f9cb260SDavide Italiano     // priorities in the path, overriding PYTHONHOME and causing
3134f9cb260SDavide Italiano     // problems/incompatibilities. In order to avoid confusion, always hardcode
3144f9cb260SDavide Italiano     // the PythonHome to be right, as it's not going to change.
31563dd5d25SJonas Devlieghere     static char path[] =
31663dd5d25SJonas Devlieghere         "/System/Library/Frameworks/Python.framework/Versions/2.7";
3174f9cb260SDavide Italiano     Py_SetPythonHome(path);
318386f00dbSDavide Italiano #endif
319386f00dbSDavide Italiano #endif
32022c8efcdSZachary Turner   }
32122c8efcdSZachary Turner 
322b9c1b51eSKate Stone   void InitializeThreadsPrivate() {
3231b6700efSTatyana Krasnukha // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself,
3241b6700efSTatyana Krasnukha // so there is no way to determine whether the embedded interpreter
3251b6700efSTatyana Krasnukha // was already initialized by some external code. `PyEval_ThreadsInitialized`
3261b6700efSTatyana Krasnukha // would always return `true` and `PyGILState_Ensure/Release` flow would be
3271b6700efSTatyana Krasnukha // executed instead of unlocking GIL with `PyEval_SaveThread`. When
3281b6700efSTatyana Krasnukha // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock.
3291b6700efSTatyana Krasnukha #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3)
3301b6700efSTatyana Krasnukha     // The only case we should go further and acquire the GIL: it is unlocked.
3311b6700efSTatyana Krasnukha     if (PyGILState_Check())
3321b6700efSTatyana Krasnukha       return;
3331b6700efSTatyana Krasnukha #endif
3341b6700efSTatyana Krasnukha 
335b9c1b51eSKate Stone     if (PyEval_ThreadsInitialized()) {
3363b7e1981SPavel Labath       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
337079fe48aSZachary Turner 
338079fe48aSZachary Turner       m_was_already_initialized = true;
339079fe48aSZachary Turner       m_gil_state = PyGILState_Ensure();
3403b7e1981SPavel Labath       LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n",
341079fe48aSZachary Turner                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
342079fe48aSZachary Turner       return;
343079fe48aSZachary Turner     }
344079fe48aSZachary Turner 
345079fe48aSZachary Turner     // InitThreads acquires the GIL if it hasn't been called before.
346079fe48aSZachary Turner     PyEval_InitThreads();
347079fe48aSZachary Turner   }
348079fe48aSZachary Turner 
349079fe48aSZachary Turner   TerminalState m_stdin_tty_state;
350079fe48aSZachary Turner   PyGILState_STATE m_gil_state;
351079fe48aSZachary Turner   bool m_was_already_initialized;
352079fe48aSZachary Turner };
35363dd5d25SJonas Devlieghere } // namespace
3542c1f46dcSZachary Turner 
3552df331b0SPavel Labath void ScriptInterpreterPython::ComputePythonDirForApple(
3562df331b0SPavel Labath     llvm::SmallVectorImpl<char> &path) {
3572df331b0SPavel Labath   auto style = llvm::sys::path::Style::posix;
3582df331b0SPavel Labath 
3592df331b0SPavel Labath   llvm::StringRef path_ref(path.begin(), path.size());
3602df331b0SPavel Labath   auto rbegin = llvm::sys::path::rbegin(path_ref, style);
3612df331b0SPavel Labath   auto rend = llvm::sys::path::rend(path_ref);
3622df331b0SPavel Labath   auto framework = std::find(rbegin, rend, "LLDB.framework");
3632df331b0SPavel Labath   if (framework == rend) {
36461f471a7SHaibo Huang     ComputePythonDir(path);
3652df331b0SPavel Labath     return;
3662df331b0SPavel Labath   }
3672df331b0SPavel Labath   path.resize(framework - rend);
3682df331b0SPavel Labath   llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
3692df331b0SPavel Labath }
3702df331b0SPavel Labath 
37161f471a7SHaibo Huang void ScriptInterpreterPython::ComputePythonDir(
3722df331b0SPavel Labath     llvm::SmallVectorImpl<char> &path) {
3732df331b0SPavel Labath   // Build the path by backing out of the lib dir, then building with whatever
3742df331b0SPavel Labath   // the real python interpreter uses.  (e.g. lib for most, lib64 on RHEL
37561f471a7SHaibo Huang   // x86_64, or bin on Windows).
37661f471a7SHaibo Huang   llvm::sys::path::remove_filename(path);
37761f471a7SHaibo Huang   llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
3780016b450SHaibo Huang 
3790016b450SHaibo Huang #if defined(_WIN32)
3800016b450SHaibo Huang   // This will be injected directly through FileSpec.GetDirectory().SetString(),
3810016b450SHaibo Huang   // so we need to normalize manually.
3820016b450SHaibo Huang   std::replace(path.begin(), path.end(), '\\', '/');
3830016b450SHaibo Huang #endif
3842df331b0SPavel Labath }
3852df331b0SPavel Labath 
3862df331b0SPavel Labath FileSpec ScriptInterpreterPython::GetPythonDir() {
3872df331b0SPavel Labath   static FileSpec g_spec = []() {
3882df331b0SPavel Labath     FileSpec spec = HostInfo::GetShlibDir();
3892df331b0SPavel Labath     if (!spec)
3902df331b0SPavel Labath       return FileSpec();
3912df331b0SPavel Labath     llvm::SmallString<64> path;
3922df331b0SPavel Labath     spec.GetPath(path);
3932df331b0SPavel Labath 
3942df331b0SPavel Labath #if defined(__APPLE__)
3952df331b0SPavel Labath     ComputePythonDirForApple(path);
3962df331b0SPavel Labath #else
39761f471a7SHaibo Huang     ComputePythonDir(path);
3982df331b0SPavel Labath #endif
3992df331b0SPavel Labath     spec.GetDirectory().SetString(path);
4002df331b0SPavel Labath     return spec;
4012df331b0SPavel Labath   }();
4022df331b0SPavel Labath   return g_spec;
4032df331b0SPavel Labath }
4042df331b0SPavel Labath 
40563dd5d25SJonas Devlieghere lldb_private::ConstString ScriptInterpreterPython::GetPluginNameStatic() {
40663dd5d25SJonas Devlieghere   static ConstString g_name("script-python");
40763dd5d25SJonas Devlieghere   return g_name;
40863dd5d25SJonas Devlieghere }
40963dd5d25SJonas Devlieghere 
41063dd5d25SJonas Devlieghere const char *ScriptInterpreterPython::GetPluginDescriptionStatic() {
41163dd5d25SJonas Devlieghere   return "Embedded Python interpreter";
41263dd5d25SJonas Devlieghere }
41363dd5d25SJonas Devlieghere 
41463dd5d25SJonas Devlieghere void ScriptInterpreterPython::Initialize() {
41563dd5d25SJonas Devlieghere   static llvm::once_flag g_once_flag;
41663dd5d25SJonas Devlieghere 
41763dd5d25SJonas Devlieghere   llvm::call_once(g_once_flag, []() {
41863dd5d25SJonas Devlieghere     PluginManager::RegisterPlugin(GetPluginNameStatic(),
41963dd5d25SJonas Devlieghere                                   GetPluginDescriptionStatic(),
42063dd5d25SJonas Devlieghere                                   lldb::eScriptLanguagePython,
42163dd5d25SJonas Devlieghere                                   ScriptInterpreterPythonImpl::CreateInstance);
42263dd5d25SJonas Devlieghere   });
42363dd5d25SJonas Devlieghere }
42463dd5d25SJonas Devlieghere 
42563dd5d25SJonas Devlieghere void ScriptInterpreterPython::Terminate() {}
42663dd5d25SJonas Devlieghere 
42763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::Locker(
42863dd5d25SJonas Devlieghere     ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
429b07823f3SLawrence D'Anna     uint16_t on_leave, FileSP in, FileSP out, FileSP err)
43063dd5d25SJonas Devlieghere     : ScriptInterpreterLocker(),
43163dd5d25SJonas Devlieghere       m_teardown_session((on_leave & TearDownSession) == TearDownSession),
43263dd5d25SJonas Devlieghere       m_python_interpreter(py_interpreter) {
43363dd5d25SJonas Devlieghere   DoAcquireLock();
43463dd5d25SJonas Devlieghere   if ((on_entry & InitSession) == InitSession) {
43563dd5d25SJonas Devlieghere     if (!DoInitSession(on_entry, in, out, err)) {
43663dd5d25SJonas Devlieghere       // Don't teardown the session if we didn't init it.
43763dd5d25SJonas Devlieghere       m_teardown_session = false;
43863dd5d25SJonas Devlieghere     }
43963dd5d25SJonas Devlieghere   }
44063dd5d25SJonas Devlieghere }
44163dd5d25SJonas Devlieghere 
44263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
44363dd5d25SJonas Devlieghere   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
44463dd5d25SJonas Devlieghere   m_GILState = PyGILState_Ensure();
44563dd5d25SJonas Devlieghere   LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked",
44663dd5d25SJonas Devlieghere             m_GILState == PyGILState_UNLOCKED ? "un" : "");
44763dd5d25SJonas Devlieghere 
44863dd5d25SJonas Devlieghere   // we need to save the thread state when we first start the command because
44963dd5d25SJonas Devlieghere   // we might decide to interrupt it while some action is taking place outside
45063dd5d25SJonas Devlieghere   // of Python (e.g. printing to screen, waiting for the network, ...) in that
45163dd5d25SJonas Devlieghere   // case, _PyThreadState_Current will be NULL - and we would be unable to set
45263dd5d25SJonas Devlieghere   // the asynchronous exception - not a desirable situation
45363dd5d25SJonas Devlieghere   m_python_interpreter->SetThreadState(PyThreadState_Get());
45463dd5d25SJonas Devlieghere   m_python_interpreter->IncrementLockCount();
45563dd5d25SJonas Devlieghere   return true;
45663dd5d25SJonas Devlieghere }
45763dd5d25SJonas Devlieghere 
45863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
459b07823f3SLawrence D'Anna                                                         FileSP in, FileSP out,
460b07823f3SLawrence D'Anna                                                         FileSP err) {
46163dd5d25SJonas Devlieghere   if (!m_python_interpreter)
46263dd5d25SJonas Devlieghere     return false;
46363dd5d25SJonas Devlieghere   return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
46463dd5d25SJonas Devlieghere }
46563dd5d25SJonas Devlieghere 
46663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
46763dd5d25SJonas Devlieghere   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
46863dd5d25SJonas Devlieghere   LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
46963dd5d25SJonas Devlieghere             m_GILState == PyGILState_UNLOCKED ? "un" : "");
47063dd5d25SJonas Devlieghere   PyGILState_Release(m_GILState);
47163dd5d25SJonas Devlieghere   m_python_interpreter->DecrementLockCount();
47263dd5d25SJonas Devlieghere   return true;
47363dd5d25SJonas Devlieghere }
47463dd5d25SJonas Devlieghere 
47563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
47663dd5d25SJonas Devlieghere   if (!m_python_interpreter)
47763dd5d25SJonas Devlieghere     return false;
47863dd5d25SJonas Devlieghere   m_python_interpreter->LeaveSession();
47963dd5d25SJonas Devlieghere   return true;
48063dd5d25SJonas Devlieghere }
48163dd5d25SJonas Devlieghere 
48263dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::~Locker() {
48363dd5d25SJonas Devlieghere   if (m_teardown_session)
48463dd5d25SJonas Devlieghere     DoTearDownSession();
48563dd5d25SJonas Devlieghere   DoFreeLock();
48663dd5d25SJonas Devlieghere }
48763dd5d25SJonas Devlieghere 
4888d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger)
4898d1fb843SJonas Devlieghere     : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
49063dd5d25SJonas Devlieghere       m_saved_stderr(), m_main_module(),
49163dd5d25SJonas Devlieghere       m_session_dict(PyInitialValue::Invalid),
49263dd5d25SJonas Devlieghere       m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(),
49363dd5d25SJonas Devlieghere       m_run_one_line_str_global(),
4948d1fb843SJonas Devlieghere       m_dictionary_name(m_debugger.GetInstanceName().AsCString()),
495ea1752a7SJonas Devlieghere       m_active_io_handler(eIOHandlerNone), m_session_is_active(false),
49664ec505dSJonas Devlieghere       m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
497ea1752a7SJonas Devlieghere       m_command_thread_state(nullptr) {
49863dd5d25SJonas Devlieghere   InitializePrivate();
49963dd5d25SJonas Devlieghere 
50063dd5d25SJonas Devlieghere   m_dictionary_name.append("_dict");
50163dd5d25SJonas Devlieghere   StreamString run_string;
50263dd5d25SJonas Devlieghere   run_string.Printf("%s = dict()", m_dictionary_name.c_str());
50363dd5d25SJonas Devlieghere 
50463dd5d25SJonas Devlieghere   Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock);
50563dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
50663dd5d25SJonas Devlieghere 
50763dd5d25SJonas Devlieghere   run_string.Clear();
50863dd5d25SJonas Devlieghere   run_string.Printf(
50963dd5d25SJonas Devlieghere       "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
51063dd5d25SJonas Devlieghere       m_dictionary_name.c_str());
51163dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
51263dd5d25SJonas Devlieghere 
51363dd5d25SJonas Devlieghere   // Reloading modules requires a different syntax in Python 2 and Python 3.
51463dd5d25SJonas Devlieghere   // This provides a consistent syntax no matter what version of Python.
51563dd5d25SJonas Devlieghere   run_string.Clear();
51663dd5d25SJonas Devlieghere   run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')",
51763dd5d25SJonas Devlieghere                     m_dictionary_name.c_str());
51863dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
51963dd5d25SJonas Devlieghere 
52063dd5d25SJonas Devlieghere   // WARNING: temporary code that loads Cocoa formatters - this should be done
52163dd5d25SJonas Devlieghere   // on a per-platform basis rather than loading the whole set and letting the
52263dd5d25SJonas Devlieghere   // individual formatter classes exploit APIs to check whether they can/cannot
52363dd5d25SJonas Devlieghere   // do their task
52463dd5d25SJonas Devlieghere   run_string.Clear();
52563dd5d25SJonas Devlieghere   run_string.Printf(
52663dd5d25SJonas Devlieghere       "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')",
52763dd5d25SJonas Devlieghere       m_dictionary_name.c_str());
52863dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
52963dd5d25SJonas Devlieghere   run_string.Clear();
53063dd5d25SJonas Devlieghere 
53163dd5d25SJonas Devlieghere   run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
53263dd5d25SJonas Devlieghere                     "lldb.embedded_interpreter import run_python_interpreter; "
53363dd5d25SJonas Devlieghere                     "from lldb.embedded_interpreter import run_one_line')",
53463dd5d25SJonas Devlieghere                     m_dictionary_name.c_str());
53563dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
53663dd5d25SJonas Devlieghere   run_string.Clear();
53763dd5d25SJonas Devlieghere 
53863dd5d25SJonas Devlieghere   run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
53963dd5d25SJonas Devlieghere                     "; pydoc.pager = pydoc.plainpager')",
5408d1fb843SJonas Devlieghere                     m_dictionary_name.c_str(), m_debugger.GetID());
54163dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
54263dd5d25SJonas Devlieghere }
54363dd5d25SJonas Devlieghere 
54463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
54563dd5d25SJonas Devlieghere   // the session dictionary may hold objects with complex state which means
54663dd5d25SJonas Devlieghere   // that they may need to be torn down with some level of smarts and that, in
54763dd5d25SJonas Devlieghere   // turn, requires a valid thread state force Python to procure itself such a
54863dd5d25SJonas Devlieghere   // thread state, nuke the session dictionary and then release it for others
54963dd5d25SJonas Devlieghere   // to use and proceed with the rest of the shutdown
55063dd5d25SJonas Devlieghere   auto gil_state = PyGILState_Ensure();
55163dd5d25SJonas Devlieghere   m_session_dict.Reset();
55263dd5d25SJonas Devlieghere   PyGILState_Release(gil_state);
55363dd5d25SJonas Devlieghere }
55463dd5d25SJonas Devlieghere 
55563dd5d25SJonas Devlieghere lldb_private::ConstString ScriptInterpreterPythonImpl::GetPluginName() {
5562c1f46dcSZachary Turner   return GetPluginNameStatic();
5572c1f46dcSZachary Turner }
5582c1f46dcSZachary Turner 
55963dd5d25SJonas Devlieghere uint32_t ScriptInterpreterPythonImpl::GetPluginVersion() { return 1; }
5602c1f46dcSZachary Turner 
56163dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler,
56263dd5d25SJonas Devlieghere                                                      bool interactive) {
5632c1f46dcSZachary Turner   const char *instructions = nullptr;
5642c1f46dcSZachary Turner 
565b9c1b51eSKate Stone   switch (m_active_io_handler) {
5662c1f46dcSZachary Turner   case eIOHandlerNone:
5672c1f46dcSZachary Turner     break;
5682c1f46dcSZachary Turner   case eIOHandlerBreakpoint:
5692c1f46dcSZachary Turner     instructions = R"(Enter your Python command(s). Type 'DONE' to end.
5702c1f46dcSZachary Turner def function (frame, bp_loc, internal_dict):
5712c1f46dcSZachary Turner     """frame: the lldb.SBFrame for the location at which you stopped
5722c1f46dcSZachary Turner        bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
5732c1f46dcSZachary Turner        internal_dict: an LLDB support object not to be used"""
5742c1f46dcSZachary Turner )";
5752c1f46dcSZachary Turner     break;
5762c1f46dcSZachary Turner   case eIOHandlerWatchpoint:
5772c1f46dcSZachary Turner     instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
5782c1f46dcSZachary Turner     break;
5792c1f46dcSZachary Turner   }
5802c1f46dcSZachary Turner 
581b9c1b51eSKate Stone   if (instructions) {
5827ca15ba7SLawrence D'Anna     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
5830affb582SDave Lee     if (output_sp && interactive) {
5842c1f46dcSZachary Turner       output_sp->PutCString(instructions);
5852c1f46dcSZachary Turner       output_sp->Flush();
5862c1f46dcSZachary Turner     }
5872c1f46dcSZachary Turner   }
5882c1f46dcSZachary Turner }
5892c1f46dcSZachary Turner 
59063dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler,
591b9c1b51eSKate Stone                                                          std::string &data) {
5922c1f46dcSZachary Turner   io_handler.SetIsDone(true);
5938d1fb843SJonas Devlieghere   bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
5942c1f46dcSZachary Turner 
595b9c1b51eSKate Stone   switch (m_active_io_handler) {
5962c1f46dcSZachary Turner   case eIOHandlerNone:
5972c1f46dcSZachary Turner     break;
598b9c1b51eSKate Stone   case eIOHandlerBreakpoint: {
599b9c1b51eSKate Stone     std::vector<BreakpointOptions *> *bp_options_vec =
600b9c1b51eSKate Stone         (std::vector<BreakpointOptions *> *)io_handler.GetUserData();
601b9c1b51eSKate Stone     for (auto bp_options : *bp_options_vec) {
6022c1f46dcSZachary Turner       if (!bp_options)
6032c1f46dcSZachary Turner         continue;
6042c1f46dcSZachary Turner 
605a8f3ae7cSJonas Devlieghere       auto data_up = std::make_unique<CommandDataPython>();
606d5b44036SJonas Devlieghere       if (!data_up)
6074e4fbe82SZachary Turner         break;
608d5b44036SJonas Devlieghere       data_up->user_source.SplitIntoLines(data);
6092c1f46dcSZachary Turner 
610738af7a6SJim Ingham       StructuredData::ObjectSP empty_args_sp;
611d5b44036SJonas Devlieghere       if (GenerateBreakpointCommandCallbackData(data_up->user_source,
612738af7a6SJim Ingham                                                 data_up->script_source,
613738af7a6SJim Ingham                                                 false)
614b9c1b51eSKate Stone               .Success()) {
6154e4fbe82SZachary Turner         auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
616d5b44036SJonas Devlieghere             std::move(data_up));
617b9c1b51eSKate Stone         bp_options->SetCallback(
61863dd5d25SJonas Devlieghere             ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
619b9c1b51eSKate Stone       } else if (!batch_mode) {
6207ca15ba7SLawrence D'Anna         StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
621b9c1b51eSKate Stone         if (error_sp) {
6222c1f46dcSZachary Turner           error_sp->Printf("Warning: No command attached to breakpoint.\n");
6232c1f46dcSZachary Turner           error_sp->Flush();
6242c1f46dcSZachary Turner         }
6252c1f46dcSZachary Turner       }
6262c1f46dcSZachary Turner     }
6272c1f46dcSZachary Turner     m_active_io_handler = eIOHandlerNone;
628b9c1b51eSKate Stone   } break;
629b9c1b51eSKate Stone   case eIOHandlerWatchpoint: {
630b9c1b51eSKate Stone     WatchpointOptions *wp_options =
631b9c1b51eSKate Stone         (WatchpointOptions *)io_handler.GetUserData();
632a8f3ae7cSJonas Devlieghere     auto data_up = std::make_unique<WatchpointOptions::CommandData>();
633d5b44036SJonas Devlieghere     data_up->user_source.SplitIntoLines(data);
6342c1f46dcSZachary Turner 
635d5b44036SJonas Devlieghere     if (GenerateWatchpointCommandCallbackData(data_up->user_source,
636d5b44036SJonas Devlieghere                                               data_up->script_source)) {
6374e4fbe82SZachary Turner       auto baton_sp =
638d5b44036SJonas Devlieghere           std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
639b9c1b51eSKate Stone       wp_options->SetCallback(
64063dd5d25SJonas Devlieghere           ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
641b9c1b51eSKate Stone     } else if (!batch_mode) {
6427ca15ba7SLawrence D'Anna       StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
643b9c1b51eSKate Stone       if (error_sp) {
6442c1f46dcSZachary Turner         error_sp->Printf("Warning: No command attached to breakpoint.\n");
6452c1f46dcSZachary Turner         error_sp->Flush();
6462c1f46dcSZachary Turner       }
6472c1f46dcSZachary Turner     }
6482c1f46dcSZachary Turner     m_active_io_handler = eIOHandlerNone;
649b9c1b51eSKate Stone   } break;
6502c1f46dcSZachary Turner   }
6512c1f46dcSZachary Turner }
6522c1f46dcSZachary Turner 
65363dd5d25SJonas Devlieghere lldb::ScriptInterpreterSP
6548d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) {
6558d1fb843SJonas Devlieghere   return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
65663dd5d25SJonas Devlieghere }
6572c1f46dcSZachary Turner 
65863dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::LeaveSession() {
6592c1f46dcSZachary Turner   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
6602c1f46dcSZachary Turner   if (log)
66163dd5d25SJonas Devlieghere     log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
6622c1f46dcSZachary Turner 
66320b52c33SJonas Devlieghere   // Unset the LLDB global variables.
66420b52c33SJonas Devlieghere   PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
66520b52c33SJonas Devlieghere                      "= None; lldb.thread = None; lldb.frame = None");
66620b52c33SJonas Devlieghere 
66705097246SAdrian Prantl   // checking that we have a valid thread state - since we use our own
66805097246SAdrian Prantl   // threading and locking in some (rare) cases during cleanup Python may end
66905097246SAdrian Prantl   // up believing we have no thread state and PyImport_AddModule will crash if
67005097246SAdrian Prantl   // that is the case - since that seems to only happen when destroying the
67105097246SAdrian Prantl   // SBDebugger, we can make do without clearing up stdout and stderr
6722c1f46dcSZachary Turner 
6732c1f46dcSZachary Turner   // rdar://problem/11292882
674b9c1b51eSKate Stone   // When the current thread state is NULL, PyThreadState_Get() issues a fatal
675b9c1b51eSKate Stone   // error.
676b9c1b51eSKate Stone   if (PyThreadState_GetDict()) {
6772c1f46dcSZachary Turner     PythonDictionary &sys_module_dict = GetSysModuleDictionary();
678b9c1b51eSKate Stone     if (sys_module_dict.IsValid()) {
679b9c1b51eSKate Stone       if (m_saved_stdin.IsValid()) {
680f8b22f8fSZachary Turner         sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
6812c1f46dcSZachary Turner         m_saved_stdin.Reset();
6822c1f46dcSZachary Turner       }
683b9c1b51eSKate Stone       if (m_saved_stdout.IsValid()) {
684f8b22f8fSZachary Turner         sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
6852c1f46dcSZachary Turner         m_saved_stdout.Reset();
6862c1f46dcSZachary Turner       }
687b9c1b51eSKate Stone       if (m_saved_stderr.IsValid()) {
688f8b22f8fSZachary Turner         sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
6892c1f46dcSZachary Turner         m_saved_stderr.Reset();
6902c1f46dcSZachary Turner       }
6912c1f46dcSZachary Turner     }
6922c1f46dcSZachary Turner   }
6932c1f46dcSZachary Turner 
6942c1f46dcSZachary Turner   m_session_is_active = false;
6952c1f46dcSZachary Turner }
6962c1f46dcSZachary Turner 
697b07823f3SLawrence D'Anna bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp,
698b07823f3SLawrence D'Anna                                                const char *py_name,
699b07823f3SLawrence D'Anna                                                PythonObject &save_file,
700b9c1b51eSKate Stone                                                const char *mode) {
701b07823f3SLawrence D'Anna   if (!file_sp || !*file_sp) {
702b07823f3SLawrence D'Anna     save_file.Reset();
703b07823f3SLawrence D'Anna     return false;
704b07823f3SLawrence D'Anna   }
705b07823f3SLawrence D'Anna   File &file = *file_sp;
706b07823f3SLawrence D'Anna 
707a31baf08SGreg Clayton   // Flush the file before giving it to python to avoid interleaved output.
708a31baf08SGreg Clayton   file.Flush();
709a31baf08SGreg Clayton 
710a31baf08SGreg Clayton   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
711a31baf08SGreg Clayton 
7120f783599SLawrence D'Anna   auto new_file = PythonFile::FromFile(file, mode);
7130f783599SLawrence D'Anna   if (!new_file) {
7140f783599SLawrence D'Anna     llvm::consumeError(new_file.takeError());
7150f783599SLawrence D'Anna     return false;
7160f783599SLawrence D'Anna   }
7170f783599SLawrence D'Anna 
718b07823f3SLawrence D'Anna   save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
719a31baf08SGreg Clayton 
7200f783599SLawrence D'Anna   sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
721a31baf08SGreg Clayton   return true;
722a31baf08SGreg Clayton }
723a31baf08SGreg Clayton 
72463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
725b07823f3SLawrence D'Anna                                                FileSP in_sp, FileSP out_sp,
726b07823f3SLawrence D'Anna                                                FileSP err_sp) {
727b9c1b51eSKate Stone   // If we have already entered the session, without having officially 'left'
72805097246SAdrian Prantl   // it, then there is no need to 'enter' it again.
7292c1f46dcSZachary Turner   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
730b9c1b51eSKate Stone   if (m_session_is_active) {
73163e5fb76SJonas Devlieghere     LLDB_LOGF(
73263e5fb76SJonas Devlieghere         log,
73363dd5d25SJonas Devlieghere         "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
734b9c1b51eSKate Stone         ") session is already active, returning without doing anything",
735b9c1b51eSKate Stone         on_entry_flags);
7362c1f46dcSZachary Turner     return false;
7372c1f46dcSZachary Turner   }
7382c1f46dcSZachary Turner 
73963e5fb76SJonas Devlieghere   LLDB_LOGF(
74063e5fb76SJonas Devlieghere       log,
74163e5fb76SJonas Devlieghere       "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
742b9c1b51eSKate Stone       on_entry_flags);
7432c1f46dcSZachary Turner 
7442c1f46dcSZachary Turner   m_session_is_active = true;
7452c1f46dcSZachary Turner 
7462c1f46dcSZachary Turner   StreamString run_string;
7472c1f46dcSZachary Turner 
748b9c1b51eSKate Stone   if (on_entry_flags & Locker::InitGlobals) {
749b9c1b51eSKate Stone     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
7508d1fb843SJonas Devlieghere                       m_dictionary_name.c_str(), m_debugger.GetID());
751b9c1b51eSKate Stone     run_string.Printf(
752b9c1b51eSKate Stone         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
7538d1fb843SJonas Devlieghere         m_debugger.GetID());
7542c1f46dcSZachary Turner     run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
7552c1f46dcSZachary Turner     run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
7562c1f46dcSZachary Turner     run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
7572c1f46dcSZachary Turner     run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
7582c1f46dcSZachary Turner     run_string.PutCString("')");
759b9c1b51eSKate Stone   } else {
76005097246SAdrian Prantl     // If we aren't initing the globals, we should still always set the
76105097246SAdrian Prantl     // debugger (since that is always unique.)
762b9c1b51eSKate Stone     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
7638d1fb843SJonas Devlieghere                       m_dictionary_name.c_str(), m_debugger.GetID());
764b9c1b51eSKate Stone     run_string.Printf(
765b9c1b51eSKate Stone         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
7668d1fb843SJonas Devlieghere         m_debugger.GetID());
7672c1f46dcSZachary Turner     run_string.PutCString("')");
7682c1f46dcSZachary Turner   }
7692c1f46dcSZachary Turner 
7702c1f46dcSZachary Turner   PyRun_SimpleString(run_string.GetData());
7712c1f46dcSZachary Turner   run_string.Clear();
7722c1f46dcSZachary Turner 
7732c1f46dcSZachary Turner   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
774b9c1b51eSKate Stone   if (sys_module_dict.IsValid()) {
775b07823f3SLawrence D'Anna     lldb::FileSP top_in_sp;
776b07823f3SLawrence D'Anna     lldb::StreamFileSP top_out_sp, top_err_sp;
777b07823f3SLawrence D'Anna     if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
778b07823f3SLawrence D'Anna       m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
779b07823f3SLawrence D'Anna                                                  top_err_sp);
7802c1f46dcSZachary Turner 
781b9c1b51eSKate Stone     if (on_entry_flags & Locker::NoSTDIN) {
7822c1f46dcSZachary Turner       m_saved_stdin.Reset();
783b9c1b51eSKate Stone     } else {
784b07823f3SLawrence D'Anna       if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
785b07823f3SLawrence D'Anna         if (top_in_sp)
786b07823f3SLawrence D'Anna           SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
7872c1f46dcSZachary Turner       }
788a31baf08SGreg Clayton     }
789a31baf08SGreg Clayton 
790b07823f3SLawrence D'Anna     if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
791b07823f3SLawrence D'Anna       if (top_out_sp)
792b07823f3SLawrence D'Anna         SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w");
793a31baf08SGreg Clayton     }
794a31baf08SGreg Clayton 
795b07823f3SLawrence D'Anna     if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
796b07823f3SLawrence D'Anna       if (top_err_sp)
797b07823f3SLawrence D'Anna         SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w");
798a31baf08SGreg Clayton     }
7992c1f46dcSZachary Turner   }
8002c1f46dcSZachary Turner 
8012c1f46dcSZachary Turner   if (PyErr_Occurred())
8022c1f46dcSZachary Turner     PyErr_Clear();
8032c1f46dcSZachary Turner 
8042c1f46dcSZachary Turner   return true;
8052c1f46dcSZachary Turner }
8062c1f46dcSZachary Turner 
80704edd189SLawrence D'Anna PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
808f8b22f8fSZachary Turner   if (!m_main_module.IsValid())
80904edd189SLawrence D'Anna     m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__"));
8102c1f46dcSZachary Turner   return m_main_module;
8112c1f46dcSZachary Turner }
8122c1f46dcSZachary Turner 
81363dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
814f8b22f8fSZachary Turner   if (m_session_dict.IsValid())
815f8b22f8fSZachary Turner     return m_session_dict;
816f8b22f8fSZachary Turner 
8172c1f46dcSZachary Turner   PythonObject &main_module = GetMainModule();
818f8b22f8fSZachary Turner   if (!main_module.IsValid())
819f8b22f8fSZachary Turner     return m_session_dict;
820f8b22f8fSZachary Turner 
821b9c1b51eSKate Stone   PythonDictionary main_dict(PyRefType::Borrowed,
822b9c1b51eSKate Stone                              PyModule_GetDict(main_module.get()));
823f8b22f8fSZachary Turner   if (!main_dict.IsValid())
824f8b22f8fSZachary Turner     return m_session_dict;
825f8b22f8fSZachary Turner 
826722b6189SLawrence D'Anna   m_session_dict = unwrapIgnoringErrors(
827722b6189SLawrence D'Anna       As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
8282c1f46dcSZachary Turner   return m_session_dict;
8292c1f46dcSZachary Turner }
8302c1f46dcSZachary Turner 
83163dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
832f8b22f8fSZachary Turner   if (m_sys_module_dict.IsValid())
833f8b22f8fSZachary Turner     return m_sys_module_dict;
834722b6189SLawrence D'Anna   PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys"));
835722b6189SLawrence D'Anna   m_sys_module_dict = sys_module.GetDictionary();
8362c1f46dcSZachary Turner   return m_sys_module_dict;
8372c1f46dcSZachary Turner }
8382c1f46dcSZachary Turner 
839a69bbe02SLawrence D'Anna llvm::Expected<unsigned>
840a69bbe02SLawrence D'Anna ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
841a69bbe02SLawrence D'Anna     const llvm::StringRef &callable_name) {
842738af7a6SJim Ingham   if (callable_name.empty()) {
843738af7a6SJim Ingham     return llvm::createStringError(
844738af7a6SJim Ingham         llvm::inconvertibleErrorCode(),
845738af7a6SJim Ingham         "called with empty callable name.");
846738af7a6SJim Ingham   }
847738af7a6SJim Ingham   Locker py_lock(this, Locker::AcquireLock |
848738af7a6SJim Ingham                  Locker::InitSession |
849738af7a6SJim Ingham                  Locker::NoSTDIN);
850738af7a6SJim Ingham   auto dict = PythonModule::MainModule()
851738af7a6SJim Ingham       .ResolveName<PythonDictionary>(m_dictionary_name);
852a69bbe02SLawrence D'Anna   auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
853a69bbe02SLawrence D'Anna       callable_name, dict);
854738af7a6SJim Ingham   if (!pfunc.IsAllocated()) {
855738af7a6SJim Ingham     return llvm::createStringError(
856738af7a6SJim Ingham         llvm::inconvertibleErrorCode(),
857738af7a6SJim Ingham         "can't find callable: %s", callable_name.str().c_str());
858738af7a6SJim Ingham   }
859adbf64ccSLawrence D'Anna   llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
860adbf64ccSLawrence D'Anna   if (!arg_info)
861adbf64ccSLawrence D'Anna     return arg_info.takeError();
862adbf64ccSLawrence D'Anna   return arg_info.get().max_positional_args;
863738af7a6SJim Ingham }
864738af7a6SJim Ingham 
865b9c1b51eSKate Stone static std::string GenerateUniqueName(const char *base_name_wanted,
8662c1f46dcSZachary Turner                                       uint32_t &functions_counter,
867b9c1b51eSKate Stone                                       const void *name_token = nullptr) {
8682c1f46dcSZachary Turner   StreamString sstr;
8692c1f46dcSZachary Turner 
8702c1f46dcSZachary Turner   if (!base_name_wanted)
8712c1f46dcSZachary Turner     return std::string();
8722c1f46dcSZachary Turner 
8732c1f46dcSZachary Turner   if (!name_token)
8742c1f46dcSZachary Turner     sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
8752c1f46dcSZachary Turner   else
8762c1f46dcSZachary Turner     sstr.Printf("%s_%p", base_name_wanted, name_token);
8772c1f46dcSZachary Turner 
878adcd0268SBenjamin Kramer   return std::string(sstr.GetString());
8792c1f46dcSZachary Turner }
8802c1f46dcSZachary Turner 
88163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
882f8b22f8fSZachary Turner   if (m_run_one_line_function.IsValid())
883f8b22f8fSZachary Turner     return true;
884f8b22f8fSZachary Turner 
885b9c1b51eSKate Stone   PythonObject module(PyRefType::Borrowed,
886b9c1b51eSKate Stone                       PyImport_AddModule("lldb.embedded_interpreter"));
887f8b22f8fSZachary Turner   if (!module.IsValid())
888f8b22f8fSZachary Turner     return false;
889f8b22f8fSZachary Turner 
890b9c1b51eSKate Stone   PythonDictionary module_dict(PyRefType::Borrowed,
891b9c1b51eSKate Stone                                PyModule_GetDict(module.get()));
892f8b22f8fSZachary Turner   if (!module_dict.IsValid())
893f8b22f8fSZachary Turner     return false;
894f8b22f8fSZachary Turner 
895b9c1b51eSKate Stone   m_run_one_line_function =
896b9c1b51eSKate Stone       module_dict.GetItemForKey(PythonString("run_one_line"));
897b9c1b51eSKate Stone   m_run_one_line_str_global =
898b9c1b51eSKate Stone       module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
899f8b22f8fSZachary Turner   return m_run_one_line_function.IsValid();
9002c1f46dcSZachary Turner }
9012c1f46dcSZachary Turner 
90263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLine(
9034d51a902SRaphael Isemann     llvm::StringRef command, CommandReturnObject *result,
904b9c1b51eSKate Stone     const ExecuteScriptOptions &options) {
905d6c062bcSRaphael Isemann   std::string command_str = command.str();
906d6c062bcSRaphael Isemann 
9072c1f46dcSZachary Turner   if (!m_valid_session)
9082c1f46dcSZachary Turner     return false;
9092c1f46dcSZachary Turner 
9104d51a902SRaphael Isemann   if (!command.empty()) {
911b9c1b51eSKate Stone     // We want to call run_one_line, passing in the dictionary and the command
91205097246SAdrian Prantl     // string.  We cannot do this through PyRun_SimpleString here because the
91305097246SAdrian Prantl     // command string may contain escaped characters, and putting it inside
914b9c1b51eSKate Stone     // another string to pass to PyRun_SimpleString messes up the escaping.  So
91505097246SAdrian Prantl     // we use the following more complicated method to pass the command string
91605097246SAdrian Prantl     // directly down to Python.
917d79273c9SJonas Devlieghere     llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
91884228365SJonas Devlieghere         io_redirect_or_error = ScriptInterpreterIORedirect::Create(
91984228365SJonas Devlieghere             options.GetEnableIO(), m_debugger, result);
920d79273c9SJonas Devlieghere     if (!io_redirect_or_error) {
921d79273c9SJonas Devlieghere       if (result)
922d79273c9SJonas Devlieghere         result->AppendErrorWithFormatv(
923d79273c9SJonas Devlieghere             "failed to redirect I/O: {0}\n",
924d79273c9SJonas Devlieghere             llvm::fmt_consume(io_redirect_or_error.takeError()));
925d79273c9SJonas Devlieghere       else
926d79273c9SJonas Devlieghere         llvm::consumeError(io_redirect_or_error.takeError());
9272fce1137SLawrence D'Anna       return false;
9282fce1137SLawrence D'Anna     }
929d79273c9SJonas Devlieghere 
930d79273c9SJonas Devlieghere     ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
9312c1f46dcSZachary Turner 
93232064024SZachary Turner     bool success = false;
93332064024SZachary Turner     {
93405097246SAdrian Prantl       // WARNING!  It's imperative that this RAII scope be as tight as
93505097246SAdrian Prantl       // possible. In particular, the scope must end *before* we try to join
93605097246SAdrian Prantl       // the read thread.  The reason for this is that a pre-requisite for
93705097246SAdrian Prantl       // joining the read thread is that we close the write handle (to break
93805097246SAdrian Prantl       // the pipe and cause it to wake up and exit).  But acquiring the GIL as
93905097246SAdrian Prantl       // below will redirect Python's stdio to use this same handle.  If we
94005097246SAdrian Prantl       // close the handle while Python is still using it, bad things will
94105097246SAdrian Prantl       // happen.
942b9c1b51eSKate Stone       Locker locker(
943b9c1b51eSKate Stone           this,
94463dd5d25SJonas Devlieghere           Locker::AcquireLock | Locker::InitSession |
94563dd5d25SJonas Devlieghere               (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
9462c1f46dcSZachary Turner               ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
947d79273c9SJonas Devlieghere           Locker::FreeAcquiredLock | Locker::TearDownSession,
948d79273c9SJonas Devlieghere           io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
949d79273c9SJonas Devlieghere           io_redirect.GetErrorFile());
9502c1f46dcSZachary Turner 
9512c1f46dcSZachary Turner       // Find the correct script interpreter dictionary in the main module.
9522c1f46dcSZachary Turner       PythonDictionary &session_dict = GetSessionDictionary();
953b9c1b51eSKate Stone       if (session_dict.IsValid()) {
954b9c1b51eSKate Stone         if (GetEmbeddedInterpreterModuleObjects()) {
955b9c1b51eSKate Stone           if (PyCallable_Check(m_run_one_line_function.get())) {
956b9c1b51eSKate Stone             PythonObject pargs(
957b9c1b51eSKate Stone                 PyRefType::Owned,
958d6c062bcSRaphael Isemann                 Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
959b9c1b51eSKate Stone             if (pargs.IsValid()) {
960b9c1b51eSKate Stone               PythonObject return_value(
961b9c1b51eSKate Stone                   PyRefType::Owned,
962b9c1b51eSKate Stone                   PyObject_CallObject(m_run_one_line_function.get(),
963b9c1b51eSKate Stone                                       pargs.get()));
964f8b22f8fSZachary Turner               if (return_value.IsValid())
9652c1f46dcSZachary Turner                 success = true;
966b9c1b51eSKate Stone               else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
9672c1f46dcSZachary Turner                 PyErr_Print();
9682c1f46dcSZachary Turner                 PyErr_Clear();
9692c1f46dcSZachary Turner               }
9702c1f46dcSZachary Turner             }
9712c1f46dcSZachary Turner           }
9722c1f46dcSZachary Turner         }
9732c1f46dcSZachary Turner       }
9742c1f46dcSZachary Turner 
975d79273c9SJonas Devlieghere       io_redirect.Flush();
9762c1f46dcSZachary Turner     }
9772c1f46dcSZachary Turner 
9782c1f46dcSZachary Turner     if (success)
9792c1f46dcSZachary Turner       return true;
9802c1f46dcSZachary Turner 
9812c1f46dcSZachary Turner     // The one-liner failed.  Append the error message.
9824d51a902SRaphael Isemann     if (result) {
983b9c1b51eSKate Stone       result->AppendErrorWithFormat(
9844d51a902SRaphael Isemann           "python failed attempting to evaluate '%s'\n", command_str.c_str());
9854d51a902SRaphael Isemann     }
9862c1f46dcSZachary Turner     return false;
9872c1f46dcSZachary Turner   }
9882c1f46dcSZachary Turner 
9892c1f46dcSZachary Turner   if (result)
9902c1f46dcSZachary Turner     result->AppendError("empty command passed to python\n");
9912c1f46dcSZachary Turner   return false;
9922c1f46dcSZachary Turner }
9932c1f46dcSZachary Turner 
99463dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
995f9d16476SPavel Labath   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
996f9d16476SPavel Labath   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
9972c1f46dcSZachary Turner 
9988d1fb843SJonas Devlieghere   Debugger &debugger = m_debugger;
9992c1f46dcSZachary Turner 
1000b9c1b51eSKate Stone   // At the moment, the only time the debugger does not have an input file
100105097246SAdrian Prantl   // handle is when this is called directly from Python, in which case it is
100205097246SAdrian Prantl   // both dangerous and unnecessary (not to mention confusing) to try to embed
100305097246SAdrian Prantl   // a running interpreter loop inside the already running Python interpreter
100405097246SAdrian Prantl   // loop, so we won't do it.
10052c1f46dcSZachary Turner 
10067ca15ba7SLawrence D'Anna   if (!debugger.GetInputFile().IsValid())
10072c1f46dcSZachary Turner     return;
10082c1f46dcSZachary Turner 
10092c1f46dcSZachary Turner   IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
1010b9c1b51eSKate Stone   if (io_handler_sp) {
10117ce2de2cSJonas Devlieghere     debugger.RunIOHandlerAsync(io_handler_sp);
10122c1f46dcSZachary Turner   }
10132c1f46dcSZachary Turner }
10142c1f46dcSZachary Turner 
101563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Interrupt() {
10162c1f46dcSZachary Turner   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
10172c1f46dcSZachary Turner 
1018b9c1b51eSKate Stone   if (IsExecutingPython()) {
1019b1cf558dSEnrico Granata     PyThreadState *state = PyThreadState_GET();
10202c1f46dcSZachary Turner     if (!state)
10212c1f46dcSZachary Turner       state = GetThreadState();
1022b9c1b51eSKate Stone     if (state) {
10232c1f46dcSZachary Turner       long tid = state->thread_id;
102422c8efcdSZachary Turner       PyThreadState_Swap(state);
10252c1f46dcSZachary Turner       int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
102663e5fb76SJonas Devlieghere       LLDB_LOGF(log,
102763e5fb76SJonas Devlieghere                 "ScriptInterpreterPythonImpl::Interrupt() sending "
1028b9c1b51eSKate Stone                 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
1029b9c1b51eSKate Stone                 tid, num_threads);
10302c1f46dcSZachary Turner       return true;
10312c1f46dcSZachary Turner     }
10322c1f46dcSZachary Turner   }
103363e5fb76SJonas Devlieghere   LLDB_LOGF(log,
103463dd5d25SJonas Devlieghere             "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
1035b9c1b51eSKate Stone             "can't interrupt");
10362c1f46dcSZachary Turner   return false;
10372c1f46dcSZachary Turner }
103804edd189SLawrence D'Anna 
103963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
10404d51a902SRaphael Isemann     llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
1041b9c1b51eSKate Stone     void *ret_value, const ExecuteScriptOptions &options) {
10422c1f46dcSZachary Turner 
104363dd5d25SJonas Devlieghere   Locker locker(this,
104463dd5d25SJonas Devlieghere                 Locker::AcquireLock | Locker::InitSession |
104563dd5d25SJonas Devlieghere                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1046b9c1b51eSKate Stone                     Locker::NoSTDIN,
104763dd5d25SJonas Devlieghere                 Locker::FreeAcquiredLock | Locker::TearDownSession);
10482c1f46dcSZachary Turner 
104904edd189SLawrence D'Anna   PythonModule &main_module = GetMainModule();
105004edd189SLawrence D'Anna   PythonDictionary globals = main_module.GetDictionary();
10512c1f46dcSZachary Turner 
10522c1f46dcSZachary Turner   PythonDictionary locals = GetSessionDictionary();
105304edd189SLawrence D'Anna   if (!locals.IsValid())
1054722b6189SLawrence D'Anna     locals = unwrapIgnoringErrors(
1055722b6189SLawrence D'Anna         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1056f8b22f8fSZachary Turner   if (!locals.IsValid())
10572c1f46dcSZachary Turner     locals = globals;
10582c1f46dcSZachary Turner 
105904edd189SLawrence D'Anna   Expected<PythonObject> maybe_py_return =
106004edd189SLawrence D'Anna       runStringOneLine(in_string, globals, locals);
10612c1f46dcSZachary Turner 
106204edd189SLawrence D'Anna   if (!maybe_py_return) {
106304edd189SLawrence D'Anna     llvm::handleAllErrors(
106404edd189SLawrence D'Anna         maybe_py_return.takeError(),
106504edd189SLawrence D'Anna         [&](PythonException &E) {
106604edd189SLawrence D'Anna           E.Restore();
106704edd189SLawrence D'Anna           if (options.GetMaskoutErrors()) {
106804edd189SLawrence D'Anna             if (E.Matches(PyExc_SyntaxError)) {
106904edd189SLawrence D'Anna               PyErr_Print();
10702c1f46dcSZachary Turner             }
107104edd189SLawrence D'Anna             PyErr_Clear();
107204edd189SLawrence D'Anna           }
107304edd189SLawrence D'Anna         },
107404edd189SLawrence D'Anna         [](const llvm::ErrorInfoBase &E) {});
107504edd189SLawrence D'Anna     return false;
10762c1f46dcSZachary Turner   }
10772c1f46dcSZachary Turner 
107804edd189SLawrence D'Anna   PythonObject py_return = std::move(maybe_py_return.get());
107904edd189SLawrence D'Anna   assert(py_return.IsValid());
108004edd189SLawrence D'Anna 
1081b9c1b51eSKate Stone   switch (return_type) {
10822c1f46dcSZachary Turner   case eScriptReturnTypeCharPtr: // "char *"
10832c1f46dcSZachary Turner   {
10842c1f46dcSZachary Turner     const char format[3] = "s#";
108504edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
10862c1f46dcSZachary Turner   }
1087b9c1b51eSKate Stone   case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
1088b9c1b51eSKate Stone                                        // Py_None
10892c1f46dcSZachary Turner   {
10902c1f46dcSZachary Turner     const char format[3] = "z";
109104edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
10922c1f46dcSZachary Turner   }
1093b9c1b51eSKate Stone   case eScriptReturnTypeBool: {
10942c1f46dcSZachary Turner     const char format[2] = "b";
109504edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
10962c1f46dcSZachary Turner   }
1097b9c1b51eSKate Stone   case eScriptReturnTypeShortInt: {
10982c1f46dcSZachary Turner     const char format[2] = "h";
109904edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (short *)ret_value);
11002c1f46dcSZachary Turner   }
1101b9c1b51eSKate Stone   case eScriptReturnTypeShortIntUnsigned: {
11022c1f46dcSZachary Turner     const char format[2] = "H";
110304edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
11042c1f46dcSZachary Turner   }
1105b9c1b51eSKate Stone   case eScriptReturnTypeInt: {
11062c1f46dcSZachary Turner     const char format[2] = "i";
110704edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (int *)ret_value);
11082c1f46dcSZachary Turner   }
1109b9c1b51eSKate Stone   case eScriptReturnTypeIntUnsigned: {
11102c1f46dcSZachary Turner     const char format[2] = "I";
111104edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
11122c1f46dcSZachary Turner   }
1113b9c1b51eSKate Stone   case eScriptReturnTypeLongInt: {
11142c1f46dcSZachary Turner     const char format[2] = "l";
111504edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (long *)ret_value);
11162c1f46dcSZachary Turner   }
1117b9c1b51eSKate Stone   case eScriptReturnTypeLongIntUnsigned: {
11182c1f46dcSZachary Turner     const char format[2] = "k";
111904edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
11202c1f46dcSZachary Turner   }
1121b9c1b51eSKate Stone   case eScriptReturnTypeLongLong: {
11222c1f46dcSZachary Turner     const char format[2] = "L";
112304edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
11242c1f46dcSZachary Turner   }
1125b9c1b51eSKate Stone   case eScriptReturnTypeLongLongUnsigned: {
11262c1f46dcSZachary Turner     const char format[2] = "K";
112704edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format,
112804edd189SLawrence D'Anna                        (unsigned long long *)ret_value);
11292c1f46dcSZachary Turner   }
1130b9c1b51eSKate Stone   case eScriptReturnTypeFloat: {
11312c1f46dcSZachary Turner     const char format[2] = "f";
113204edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (float *)ret_value);
11332c1f46dcSZachary Turner   }
1134b9c1b51eSKate Stone   case eScriptReturnTypeDouble: {
11352c1f46dcSZachary Turner     const char format[2] = "d";
113604edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (double *)ret_value);
11372c1f46dcSZachary Turner   }
1138b9c1b51eSKate Stone   case eScriptReturnTypeChar: {
11392c1f46dcSZachary Turner     const char format[2] = "c";
114004edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (char *)ret_value);
11412c1f46dcSZachary Turner   }
1142b9c1b51eSKate Stone   case eScriptReturnTypeOpaqueObject: {
114304edd189SLawrence D'Anna     *((PyObject **)ret_value) = py_return.release();
114404edd189SLawrence D'Anna     return true;
11452c1f46dcSZachary Turner   }
11462c1f46dcSZachary Turner   }
11471dfb1a85SPavel Labath   llvm_unreachable("Fully covered switch!");
11482c1f46dcSZachary Turner }
11492c1f46dcSZachary Turner 
115063dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1151b9c1b51eSKate Stone     const char *in_string, const ExecuteScriptOptions &options) {
115204edd189SLawrence D'Anna 
115304edd189SLawrence D'Anna   if (in_string == nullptr)
115404edd189SLawrence D'Anna     return Status();
11552c1f46dcSZachary Turner 
115663dd5d25SJonas Devlieghere   Locker locker(this,
115763dd5d25SJonas Devlieghere                 Locker::AcquireLock | Locker::InitSession |
115863dd5d25SJonas Devlieghere                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1159b9c1b51eSKate Stone                     Locker::NoSTDIN,
116063dd5d25SJonas Devlieghere                 Locker::FreeAcquiredLock | Locker::TearDownSession);
11612c1f46dcSZachary Turner 
116204edd189SLawrence D'Anna   PythonModule &main_module = GetMainModule();
116304edd189SLawrence D'Anna   PythonDictionary globals = main_module.GetDictionary();
11642c1f46dcSZachary Turner 
11652c1f46dcSZachary Turner   PythonDictionary locals = GetSessionDictionary();
1166f8b22f8fSZachary Turner   if (!locals.IsValid())
1167722b6189SLawrence D'Anna     locals = unwrapIgnoringErrors(
1168722b6189SLawrence D'Anna         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1169f8b22f8fSZachary Turner   if (!locals.IsValid())
11702c1f46dcSZachary Turner     locals = globals;
11712c1f46dcSZachary Turner 
117204edd189SLawrence D'Anna   Expected<PythonObject> return_value =
117304edd189SLawrence D'Anna       runStringMultiLine(in_string, globals, locals);
11742c1f46dcSZachary Turner 
117504edd189SLawrence D'Anna   if (!return_value) {
117604edd189SLawrence D'Anna     llvm::Error error =
117704edd189SLawrence D'Anna         llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
117804edd189SLawrence D'Anna           llvm::Error error = llvm::createStringError(
117904edd189SLawrence D'Anna               llvm::inconvertibleErrorCode(), E.ReadBacktrace());
118004edd189SLawrence D'Anna           if (!options.GetMaskoutErrors())
118104edd189SLawrence D'Anna             E.Restore();
11822c1f46dcSZachary Turner           return error;
118304edd189SLawrence D'Anna         });
118404edd189SLawrence D'Anna     return Status(std::move(error));
118504edd189SLawrence D'Anna   }
118604edd189SLawrence D'Anna 
118704edd189SLawrence D'Anna   return Status();
11882c1f46dcSZachary Turner }
11892c1f46dcSZachary Turner 
119063dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1191b9c1b51eSKate Stone     std::vector<BreakpointOptions *> &bp_options_vec,
1192b9c1b51eSKate Stone     CommandReturnObject &result) {
11932c1f46dcSZachary Turner   m_active_io_handler = eIOHandlerBreakpoint;
11948d1fb843SJonas Devlieghere   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1195a6faf851SJonas Devlieghere       "    ", *this, &bp_options_vec);
11962c1f46dcSZachary Turner }
11972c1f46dcSZachary Turner 
119863dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1199b9c1b51eSKate Stone     WatchpointOptions *wp_options, CommandReturnObject &result) {
12002c1f46dcSZachary Turner   m_active_io_handler = eIOHandlerWatchpoint;
12018d1fb843SJonas Devlieghere   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1202a6faf851SJonas Devlieghere       "    ", *this, wp_options);
12032c1f46dcSZachary Turner }
12042c1f46dcSZachary Turner 
1205738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1206738af7a6SJim Ingham     BreakpointOptions *bp_options, const char *function_name,
1207738af7a6SJim Ingham     StructuredData::ObjectSP extra_args_sp) {
1208738af7a6SJim Ingham   Status error;
12092c1f46dcSZachary Turner   // For now just cons up a oneliner that calls the provided function.
12102c1f46dcSZachary Turner   std::string oneliner("return ");
12112c1f46dcSZachary Turner   oneliner += function_name;
1212738af7a6SJim Ingham 
1213a69bbe02SLawrence D'Anna   llvm::Expected<unsigned> maybe_args =
1214a69bbe02SLawrence D'Anna       GetMaxPositionalArgumentsForCallable(function_name);
1215738af7a6SJim Ingham   if (!maybe_args) {
1216a69bbe02SLawrence D'Anna     error.SetErrorStringWithFormat(
1217a69bbe02SLawrence D'Anna         "could not get num args: %s",
1218738af7a6SJim Ingham         llvm::toString(maybe_args.takeError()).c_str());
1219738af7a6SJim Ingham     return error;
1220738af7a6SJim Ingham   }
1221a69bbe02SLawrence D'Anna   size_t max_args = *maybe_args;
1222738af7a6SJim Ingham 
1223738af7a6SJim Ingham   bool uses_extra_args = false;
1224a69bbe02SLawrence D'Anna   if (max_args >= 4) {
1225738af7a6SJim Ingham     uses_extra_args = true;
1226738af7a6SJim Ingham     oneliner += "(frame, bp_loc, extra_args, internal_dict)";
1227a69bbe02SLawrence D'Anna   } else if (max_args >= 3) {
1228738af7a6SJim Ingham     if (extra_args_sp) {
1229738af7a6SJim Ingham       error.SetErrorString("cannot pass extra_args to a three argument callback"
1230738af7a6SJim Ingham                           );
1231738af7a6SJim Ingham       return error;
1232738af7a6SJim Ingham     }
1233738af7a6SJim Ingham     uses_extra_args = false;
12342c1f46dcSZachary Turner     oneliner += "(frame, bp_loc, internal_dict)";
1235738af7a6SJim Ingham   } else {
1236738af7a6SJim Ingham     error.SetErrorStringWithFormat("expected 3 or 4 argument "
1237a69bbe02SLawrence D'Anna                                    "function, %s can only take %zu",
1238a69bbe02SLawrence D'Anna                                    function_name, max_args);
1239738af7a6SJim Ingham     return error;
1240738af7a6SJim Ingham   }
1241738af7a6SJim Ingham 
1242738af7a6SJim Ingham   SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp,
1243738af7a6SJim Ingham                                uses_extra_args);
1244738af7a6SJim Ingham   return error;
12452c1f46dcSZachary Turner }
12462c1f46dcSZachary Turner 
124763dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1248f7e07256SJim Ingham     BreakpointOptions *bp_options,
1249f7e07256SJim Ingham     std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
125097206d57SZachary Turner   Status error;
1251f7e07256SJim Ingham   error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1252738af7a6SJim Ingham                                                 cmd_data_up->script_source,
1253738af7a6SJim Ingham                                                 false);
1254f7e07256SJim Ingham   if (error.Fail()) {
1255f7e07256SJim Ingham     return error;
1256f7e07256SJim Ingham   }
1257f7e07256SJim Ingham   auto baton_sp =
1258f7e07256SJim Ingham       std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
125963dd5d25SJonas Devlieghere   bp_options->SetCallback(
126063dd5d25SJonas Devlieghere       ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1261f7e07256SJim Ingham   return error;
1262f7e07256SJim Ingham }
1263f7e07256SJim Ingham 
126463dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1265b9c1b51eSKate Stone     BreakpointOptions *bp_options, const char *command_body_text) {
1266738af7a6SJim Ingham   return SetBreakpointCommandCallback(bp_options, command_body_text, {},false);
1267738af7a6SJim Ingham }
12682c1f46dcSZachary Turner 
1269738af7a6SJim Ingham // Set a Python one-liner as the callback for the breakpoint.
1270738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1271738af7a6SJim Ingham     BreakpointOptions *bp_options, const char *command_body_text,
1272738af7a6SJim Ingham     StructuredData::ObjectSP extra_args_sp,
1273738af7a6SJim Ingham     bool uses_extra_args) {
1274738af7a6SJim Ingham   auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1275b9c1b51eSKate Stone   // Split the command_body_text into lines, and pass that to
127605097246SAdrian Prantl   // GenerateBreakpointCommandCallbackData.  That will wrap the body in an
127705097246SAdrian Prantl   // auto-generated function, and return the function name in script_source.
127805097246SAdrian Prantl   // That is what the callback will actually invoke.
12792c1f46dcSZachary Turner 
1280d5b44036SJonas Devlieghere   data_up->user_source.SplitIntoLines(command_body_text);
1281d5b44036SJonas Devlieghere   Status error = GenerateBreakpointCommandCallbackData(data_up->user_source,
1282738af7a6SJim Ingham                                                        data_up->script_source,
1283738af7a6SJim Ingham                                                        uses_extra_args);
1284b9c1b51eSKate Stone   if (error.Success()) {
12854e4fbe82SZachary Turner     auto baton_sp =
1286d5b44036SJonas Devlieghere         std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
128763dd5d25SJonas Devlieghere     bp_options->SetCallback(
128863dd5d25SJonas Devlieghere         ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
12892c1f46dcSZachary Turner     return error;
129093571c3cSJonas Devlieghere   }
12912c1f46dcSZachary Turner   return error;
12922c1f46dcSZachary Turner }
12932c1f46dcSZachary Turner 
12942c1f46dcSZachary Turner // Set a Python one-liner as the callback for the watchpoint.
129563dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1296b9c1b51eSKate Stone     WatchpointOptions *wp_options, const char *oneliner) {
1297a8f3ae7cSJonas Devlieghere   auto data_up = std::make_unique<WatchpointOptions::CommandData>();
12982c1f46dcSZachary Turner 
12992c1f46dcSZachary Turner   // It's necessary to set both user_source and script_source to the oneliner.
1300b9c1b51eSKate Stone   // The former is used to generate callback description (as in watchpoint
130105097246SAdrian Prantl   // command list) while the latter is used for Python to interpret during the
130205097246SAdrian Prantl   // actual callback.
13032c1f46dcSZachary Turner 
1304d5b44036SJonas Devlieghere   data_up->user_source.AppendString(oneliner);
1305d5b44036SJonas Devlieghere   data_up->script_source.assign(oneliner);
13062c1f46dcSZachary Turner 
1307d5b44036SJonas Devlieghere   if (GenerateWatchpointCommandCallbackData(data_up->user_source,
1308d5b44036SJonas Devlieghere                                             data_up->script_source)) {
13094e4fbe82SZachary Turner     auto baton_sp =
1310d5b44036SJonas Devlieghere         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
131163dd5d25SJonas Devlieghere     wp_options->SetCallback(
131263dd5d25SJonas Devlieghere         ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
13132c1f46dcSZachary Turner   }
13142c1f46dcSZachary Turner 
13152c1f46dcSZachary Turner   return;
13162c1f46dcSZachary Turner }
13172c1f46dcSZachary Turner 
131863dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1319b9c1b51eSKate Stone     StringList &function_def) {
13202c1f46dcSZachary Turner   // Convert StringList to one long, newline delimited, const char *.
13212c1f46dcSZachary Turner   std::string function_def_string(function_def.CopyList());
13222c1f46dcSZachary Turner 
132397206d57SZachary Turner   Status error = ExecuteMultipleLines(
1324b9c1b51eSKate Stone       function_def_string.c_str(),
1325b9c1b51eSKate Stone       ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false));
13262c1f46dcSZachary Turner   return error;
13272c1f46dcSZachary Turner }
13282c1f46dcSZachary Turner 
132963dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature,
1330b9c1b51eSKate Stone                                                      const StringList &input) {
133197206d57SZachary Turner   Status error;
13322c1f46dcSZachary Turner   int num_lines = input.GetSize();
1333b9c1b51eSKate Stone   if (num_lines == 0) {
13342c1f46dcSZachary Turner     error.SetErrorString("No input data.");
13352c1f46dcSZachary Turner     return error;
13362c1f46dcSZachary Turner   }
13372c1f46dcSZachary Turner 
1338b9c1b51eSKate Stone   if (!signature || *signature == 0) {
13392c1f46dcSZachary Turner     error.SetErrorString("No output function name.");
13402c1f46dcSZachary Turner     return error;
13412c1f46dcSZachary Turner   }
13422c1f46dcSZachary Turner 
13432c1f46dcSZachary Turner   StreamString sstr;
13442c1f46dcSZachary Turner   StringList auto_generated_function;
13452c1f46dcSZachary Turner   auto_generated_function.AppendString(signature);
1346b9c1b51eSKate Stone   auto_generated_function.AppendString(
1347b9c1b51eSKate Stone       "     global_dict = globals()"); // Grab the global dictionary
1348b9c1b51eSKate Stone   auto_generated_function.AppendString(
1349b9c1b51eSKate Stone       "     new_keys = internal_dict.keys()"); // Make a list of keys in the
1350b9c1b51eSKate Stone                                                // session dict
1351b9c1b51eSKate Stone   auto_generated_function.AppendString(
1352b9c1b51eSKate Stone       "     old_keys = global_dict.keys()"); // Save list of keys in global dict
1353b9c1b51eSKate Stone   auto_generated_function.AppendString(
1354b9c1b51eSKate Stone       "     global_dict.update (internal_dict)"); // Add the session dictionary
1355b9c1b51eSKate Stone                                                   // to the
13562c1f46dcSZachary Turner   // global dictionary.
13572c1f46dcSZachary Turner 
13582c1f46dcSZachary Turner   // Wrap everything up inside the function, increasing the indentation.
13592c1f46dcSZachary Turner 
13602c1f46dcSZachary Turner   auto_generated_function.AppendString("     if True:");
1361b9c1b51eSKate Stone   for (int i = 0; i < num_lines; ++i) {
13622c1f46dcSZachary Turner     sstr.Clear();
13632c1f46dcSZachary Turner     sstr.Printf("       %s", input.GetStringAtIndex(i));
13642c1f46dcSZachary Turner     auto_generated_function.AppendString(sstr.GetData());
13652c1f46dcSZachary Turner   }
1366b9c1b51eSKate Stone   auto_generated_function.AppendString(
1367b9c1b51eSKate Stone       "     for key in new_keys:"); // Iterate over all the keys from session
1368b9c1b51eSKate Stone                                     // dict
1369b9c1b51eSKate Stone   auto_generated_function.AppendString(
1370b9c1b51eSKate Stone       "         internal_dict[key] = global_dict[key]"); // Update session dict
1371b9c1b51eSKate Stone                                                          // values
1372b9c1b51eSKate Stone   auto_generated_function.AppendString(
1373b9c1b51eSKate Stone       "         if key not in old_keys:"); // If key was not originally in
1374b9c1b51eSKate Stone                                            // global dict
1375b9c1b51eSKate Stone   auto_generated_function.AppendString(
1376b9c1b51eSKate Stone       "             del global_dict[key]"); //  ...then remove key/value from
1377b9c1b51eSKate Stone                                             //  global dict
13782c1f46dcSZachary Turner 
13792c1f46dcSZachary Turner   // Verify that the results are valid Python.
13802c1f46dcSZachary Turner 
13812c1f46dcSZachary Turner   error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
13822c1f46dcSZachary Turner 
13832c1f46dcSZachary Turner   return error;
13842c1f46dcSZachary Turner }
13852c1f46dcSZachary Turner 
138663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1387b9c1b51eSKate Stone     StringList &user_input, std::string &output, const void *name_token) {
13882c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
13892c1f46dcSZachary Turner   user_input.RemoveBlankLines();
13902c1f46dcSZachary Turner   StreamString sstr;
13912c1f46dcSZachary Turner 
13922c1f46dcSZachary Turner   // Check to see if we have any data; if not, just return.
13932c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
13942c1f46dcSZachary Turner     return false;
13952c1f46dcSZachary Turner 
1396b9c1b51eSKate Stone   // Take what the user wrote, wrap it all up inside one big auto-generated
139705097246SAdrian Prantl   // Python function, passing in the ValueObject as parameter to the function.
13982c1f46dcSZachary Turner 
1399b9c1b51eSKate Stone   std::string auto_generated_function_name(
1400b9c1b51eSKate Stone       GenerateUniqueName("lldb_autogen_python_type_print_func",
1401b9c1b51eSKate Stone                          num_created_functions, name_token));
1402b9c1b51eSKate Stone   sstr.Printf("def %s (valobj, internal_dict):",
1403b9c1b51eSKate Stone               auto_generated_function_name.c_str());
14042c1f46dcSZachary Turner 
14052c1f46dcSZachary Turner   if (!GenerateFunction(sstr.GetData(), user_input).Success())
14062c1f46dcSZachary Turner     return false;
14072c1f46dcSZachary Turner 
14082c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
14092c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
14102c1f46dcSZachary Turner   return true;
14112c1f46dcSZachary Turner }
14122c1f46dcSZachary Turner 
141363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1414b9c1b51eSKate Stone     StringList &user_input, std::string &output) {
14152c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
14162c1f46dcSZachary Turner   user_input.RemoveBlankLines();
14172c1f46dcSZachary Turner   StreamString sstr;
14182c1f46dcSZachary Turner 
14192c1f46dcSZachary Turner   // Check to see if we have any data; if not, just return.
14202c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
14212c1f46dcSZachary Turner     return false;
14222c1f46dcSZachary Turner 
1423b9c1b51eSKate Stone   std::string auto_generated_function_name(GenerateUniqueName(
1424b9c1b51eSKate Stone       "lldb_autogen_python_cmd_alias_func", num_created_functions));
14252c1f46dcSZachary Turner 
1426b9c1b51eSKate Stone   sstr.Printf("def %s (debugger, args, result, internal_dict):",
1427b9c1b51eSKate Stone               auto_generated_function_name.c_str());
14282c1f46dcSZachary Turner 
14292c1f46dcSZachary Turner   if (!GenerateFunction(sstr.GetData(), user_input).Success())
14302c1f46dcSZachary Turner     return false;
14312c1f46dcSZachary Turner 
14322c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
14332c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
14342c1f46dcSZachary Turner   return true;
14352c1f46dcSZachary Turner }
14362c1f46dcSZachary Turner 
143763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
143863dd5d25SJonas Devlieghere     StringList &user_input, std::string &output, const void *name_token) {
14392c1f46dcSZachary Turner   static uint32_t num_created_classes = 0;
14402c1f46dcSZachary Turner   user_input.RemoveBlankLines();
14412c1f46dcSZachary Turner   int num_lines = user_input.GetSize();
14422c1f46dcSZachary Turner   StreamString sstr;
14432c1f46dcSZachary Turner 
14442c1f46dcSZachary Turner   // Check to see if we have any data; if not, just return.
14452c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
14462c1f46dcSZachary Turner     return false;
14472c1f46dcSZachary Turner 
14482c1f46dcSZachary Turner   // Wrap all user input into a Python class
14492c1f46dcSZachary Turner 
1450b9c1b51eSKate Stone   std::string auto_generated_class_name(GenerateUniqueName(
1451b9c1b51eSKate Stone       "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
14522c1f46dcSZachary Turner 
14532c1f46dcSZachary Turner   StringList auto_generated_class;
14542c1f46dcSZachary Turner 
14552c1f46dcSZachary Turner   // Create the function name & definition string.
14562c1f46dcSZachary Turner 
14572c1f46dcSZachary Turner   sstr.Printf("class %s:", auto_generated_class_name.c_str());
1458c156427dSZachary Turner   auto_generated_class.AppendString(sstr.GetString());
14592c1f46dcSZachary Turner 
146005097246SAdrian Prantl   // Wrap everything up inside the class, increasing the indentation. we don't
146105097246SAdrian Prantl   // need to play any fancy indentation tricks here because there is no
14622c1f46dcSZachary Turner   // surrounding code whose indentation we need to honor
1463b9c1b51eSKate Stone   for (int i = 0; i < num_lines; ++i) {
14642c1f46dcSZachary Turner     sstr.Clear();
14652c1f46dcSZachary Turner     sstr.Printf("     %s", user_input.GetStringAtIndex(i));
1466c156427dSZachary Turner     auto_generated_class.AppendString(sstr.GetString());
14672c1f46dcSZachary Turner   }
14682c1f46dcSZachary Turner 
146905097246SAdrian Prantl   // Verify that the results are valid Python. (even though the method is
147005097246SAdrian Prantl   // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
14712c1f46dcSZachary Turner   // (TODO: rename that method to ExportDefinitionToInterpreter)
14722c1f46dcSZachary Turner   if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
14732c1f46dcSZachary Turner     return false;
14742c1f46dcSZachary Turner 
14752c1f46dcSZachary Turner   // Store the name of the auto-generated class
14762c1f46dcSZachary Turner 
14772c1f46dcSZachary Turner   output.assign(auto_generated_class_name);
14782c1f46dcSZachary Turner   return true;
14792c1f46dcSZachary Turner }
14802c1f46dcSZachary Turner 
148163dd5d25SJonas Devlieghere StructuredData::GenericSP
148263dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
148341ae8e74SKuba Mracek   if (class_name == nullptr || class_name[0] == '\0')
148441ae8e74SKuba Mracek     return StructuredData::GenericSP();
148541ae8e74SKuba Mracek 
148641ae8e74SKuba Mracek   void *ret_val;
148741ae8e74SKuba Mracek 
148841ae8e74SKuba Mracek   {
148941ae8e74SKuba Mracek     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
149041ae8e74SKuba Mracek                    Locker::FreeLock);
149105495c5dSJonas Devlieghere     ret_val = LLDBSWIGPython_CreateFrameRecognizer(class_name,
149205495c5dSJonas Devlieghere                                                    m_dictionary_name.c_str());
149341ae8e74SKuba Mracek   }
149441ae8e74SKuba Mracek 
149541ae8e74SKuba Mracek   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
149641ae8e74SKuba Mracek }
149741ae8e74SKuba Mracek 
149863dd5d25SJonas Devlieghere lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
149941ae8e74SKuba Mracek     const StructuredData::ObjectSP &os_plugin_object_sp,
150041ae8e74SKuba Mracek     lldb::StackFrameSP frame_sp) {
150141ae8e74SKuba Mracek   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
150241ae8e74SKuba Mracek 
150363dd5d25SJonas Devlieghere   if (!os_plugin_object_sp)
150463dd5d25SJonas Devlieghere     return ValueObjectListSP();
150541ae8e74SKuba Mracek 
150641ae8e74SKuba Mracek   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
150763dd5d25SJonas Devlieghere   if (!generic)
150863dd5d25SJonas Devlieghere     return nullptr;
150941ae8e74SKuba Mracek 
151041ae8e74SKuba Mracek   PythonObject implementor(PyRefType::Borrowed,
151141ae8e74SKuba Mracek                            (PyObject *)generic->GetValue());
151241ae8e74SKuba Mracek 
151363dd5d25SJonas Devlieghere   if (!implementor.IsAllocated())
151463dd5d25SJonas Devlieghere     return ValueObjectListSP();
151541ae8e74SKuba Mracek 
151605495c5dSJonas Devlieghere   PythonObject py_return(PyRefType::Owned,
151705495c5dSJonas Devlieghere                          (PyObject *)LLDBSwigPython_GetRecognizedArguments(
151805495c5dSJonas Devlieghere                              implementor.get(), frame_sp));
151941ae8e74SKuba Mracek 
152041ae8e74SKuba Mracek   // if it fails, print the error but otherwise go on
152141ae8e74SKuba Mracek   if (PyErr_Occurred()) {
152241ae8e74SKuba Mracek     PyErr_Print();
152341ae8e74SKuba Mracek     PyErr_Clear();
152441ae8e74SKuba Mracek   }
152541ae8e74SKuba Mracek   if (py_return.get()) {
152641ae8e74SKuba Mracek     PythonList result_list(PyRefType::Borrowed, py_return.get());
152741ae8e74SKuba Mracek     ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
15288f81aed1SDavid Bolvansky     for (size_t i = 0; i < result_list.GetSize(); i++) {
152941ae8e74SKuba Mracek       PyObject *item = result_list.GetItemAtIndex(i).get();
153041ae8e74SKuba Mracek       lldb::SBValue *sb_value_ptr =
153105495c5dSJonas Devlieghere           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
153205495c5dSJonas Devlieghere       auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
153363dd5d25SJonas Devlieghere       if (valobj_sp)
153463dd5d25SJonas Devlieghere         result->Append(valobj_sp);
153541ae8e74SKuba Mracek     }
153641ae8e74SKuba Mracek     return result;
153741ae8e74SKuba Mracek   }
153841ae8e74SKuba Mracek   return ValueObjectListSP();
153941ae8e74SKuba Mracek }
154041ae8e74SKuba Mracek 
154163dd5d25SJonas Devlieghere StructuredData::GenericSP
154263dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject(
1543b9c1b51eSKate Stone     const char *class_name, lldb::ProcessSP process_sp) {
15442c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
15452c1f46dcSZachary Turner     return StructuredData::GenericSP();
15462c1f46dcSZachary Turner 
15472c1f46dcSZachary Turner   if (!process_sp)
15482c1f46dcSZachary Turner     return StructuredData::GenericSP();
15492c1f46dcSZachary Turner 
15502c1f46dcSZachary Turner   void *ret_val;
15512c1f46dcSZachary Turner 
15522c1f46dcSZachary Turner   {
1553b9c1b51eSKate Stone     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
15542c1f46dcSZachary Turner                    Locker::FreeLock);
155505495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonCreateOSPlugin(
155605495c5dSJonas Devlieghere         class_name, m_dictionary_name.c_str(), process_sp);
15572c1f46dcSZachary Turner   }
15582c1f46dcSZachary Turner 
15592c1f46dcSZachary Turner   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
15602c1f46dcSZachary Turner }
15612c1f46dcSZachary Turner 
156263dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo(
1563b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp) {
1564b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
15652c1f46dcSZachary Turner 
15662c1f46dcSZachary Turner   static char callee_name[] = "get_register_info";
15672c1f46dcSZachary Turner 
15682c1f46dcSZachary Turner   if (!os_plugin_object_sp)
15692c1f46dcSZachary Turner     return StructuredData::DictionarySP();
15702c1f46dcSZachary Turner 
15712c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
15722c1f46dcSZachary Turner   if (!generic)
15732c1f46dcSZachary Turner     return nullptr;
15742c1f46dcSZachary Turner 
1575b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1576b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
15772c1f46dcSZachary Turner 
1578f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
15792c1f46dcSZachary Turner     return StructuredData::DictionarySP();
15802c1f46dcSZachary Turner 
1581b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1582b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
15832c1f46dcSZachary Turner 
15842c1f46dcSZachary Turner   if (PyErr_Occurred())
15852c1f46dcSZachary Turner     PyErr_Clear();
15862c1f46dcSZachary Turner 
1587f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
15882c1f46dcSZachary Turner     return StructuredData::DictionarySP();
15892c1f46dcSZachary Turner 
1590b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
15912c1f46dcSZachary Turner     if (PyErr_Occurred())
15922c1f46dcSZachary Turner       PyErr_Clear();
15932c1f46dcSZachary Turner 
15942c1f46dcSZachary Turner     return StructuredData::DictionarySP();
15952c1f46dcSZachary Turner   }
15962c1f46dcSZachary Turner 
15972c1f46dcSZachary Turner   if (PyErr_Occurred())
15982c1f46dcSZachary Turner     PyErr_Clear();
15992c1f46dcSZachary Turner 
16002c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1601b9c1b51eSKate Stone   PythonObject py_return(
1602b9c1b51eSKate Stone       PyRefType::Owned,
1603b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
16042c1f46dcSZachary Turner 
16052c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1606b9c1b51eSKate Stone   if (PyErr_Occurred()) {
16072c1f46dcSZachary Turner     PyErr_Print();
16082c1f46dcSZachary Turner     PyErr_Clear();
16092c1f46dcSZachary Turner   }
1610b9c1b51eSKate Stone   if (py_return.get()) {
1611f8b22f8fSZachary Turner     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
16122c1f46dcSZachary Turner     return result_dict.CreateStructuredDictionary();
16132c1f46dcSZachary Turner   }
161458b794aeSGreg Clayton   return StructuredData::DictionarySP();
161558b794aeSGreg Clayton }
16162c1f46dcSZachary Turner 
161763dd5d25SJonas Devlieghere StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo(
1618b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp) {
1619b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
16202c1f46dcSZachary Turner 
16212c1f46dcSZachary Turner   static char callee_name[] = "get_thread_info";
16222c1f46dcSZachary Turner 
16232c1f46dcSZachary Turner   if (!os_plugin_object_sp)
16242c1f46dcSZachary Turner     return StructuredData::ArraySP();
16252c1f46dcSZachary Turner 
16262c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
16272c1f46dcSZachary Turner   if (!generic)
16282c1f46dcSZachary Turner     return nullptr;
16292c1f46dcSZachary Turner 
1630b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1631b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
1632f8b22f8fSZachary Turner 
1633f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
16342c1f46dcSZachary Turner     return StructuredData::ArraySP();
16352c1f46dcSZachary Turner 
1636b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1637b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
16382c1f46dcSZachary Turner 
16392c1f46dcSZachary Turner   if (PyErr_Occurred())
16402c1f46dcSZachary Turner     PyErr_Clear();
16412c1f46dcSZachary Turner 
1642f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
16432c1f46dcSZachary Turner     return StructuredData::ArraySP();
16442c1f46dcSZachary Turner 
1645b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
16462c1f46dcSZachary Turner     if (PyErr_Occurred())
16472c1f46dcSZachary Turner       PyErr_Clear();
16482c1f46dcSZachary Turner 
16492c1f46dcSZachary Turner     return StructuredData::ArraySP();
16502c1f46dcSZachary Turner   }
16512c1f46dcSZachary Turner 
16522c1f46dcSZachary Turner   if (PyErr_Occurred())
16532c1f46dcSZachary Turner     PyErr_Clear();
16542c1f46dcSZachary Turner 
16552c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1656b9c1b51eSKate Stone   PythonObject py_return(
1657b9c1b51eSKate Stone       PyRefType::Owned,
1658b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
16592c1f46dcSZachary Turner 
16602c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1661b9c1b51eSKate Stone   if (PyErr_Occurred()) {
16622c1f46dcSZachary Turner     PyErr_Print();
16632c1f46dcSZachary Turner     PyErr_Clear();
16642c1f46dcSZachary Turner   }
16652c1f46dcSZachary Turner 
1666b9c1b51eSKate Stone   if (py_return.get()) {
1667f8b22f8fSZachary Turner     PythonList result_list(PyRefType::Borrowed, py_return.get());
1668f8b22f8fSZachary Turner     return result_list.CreateStructuredArray();
16692c1f46dcSZachary Turner   }
167058b794aeSGreg Clayton   return StructuredData::ArraySP();
167158b794aeSGreg Clayton }
16722c1f46dcSZachary Turner 
16732c1f46dcSZachary Turner // GetPythonValueFormatString provides a system independent type safe way to
16742c1f46dcSZachary Turner // convert a variable's type into a python value format. Python value formats
167505097246SAdrian Prantl // are defined in terms of builtin C types and could change from system to as
167605097246SAdrian Prantl // the underlying typedef for uint* types, size_t, off_t and other values
16772c1f46dcSZachary Turner // change.
16782c1f46dcSZachary Turner 
1679684c2c93SPavel Labath template <typename T> const char *GetPythonValueFormatString(T t);
16802c1f46dcSZachary Turner template <> const char *GetPythonValueFormatString(char *) { return "s"; }
16812c1f46dcSZachary Turner template <> const char *GetPythonValueFormatString(char) { return "b"; }
1682b9c1b51eSKate Stone template <> const char *GetPythonValueFormatString(unsigned char) {
1683b9c1b51eSKate Stone   return "B";
1684b9c1b51eSKate Stone }
16852c1f46dcSZachary Turner template <> const char *GetPythonValueFormatString(short) { return "h"; }
1686b9c1b51eSKate Stone template <> const char *GetPythonValueFormatString(unsigned short) {
1687b9c1b51eSKate Stone   return "H";
1688b9c1b51eSKate Stone }
16892c1f46dcSZachary Turner template <> const char *GetPythonValueFormatString(int) { return "i"; }
16902c1f46dcSZachary Turner template <> const char *GetPythonValueFormatString(unsigned int) { return "I"; }
16912c1f46dcSZachary Turner template <> const char *GetPythonValueFormatString(long) { return "l"; }
1692b9c1b51eSKate Stone template <> const char *GetPythonValueFormatString(unsigned long) {
1693b9c1b51eSKate Stone   return "k";
1694b9c1b51eSKate Stone }
16952c1f46dcSZachary Turner template <> const char *GetPythonValueFormatString(long long) { return "L"; }
1696b9c1b51eSKate Stone template <> const char *GetPythonValueFormatString(unsigned long long) {
1697b9c1b51eSKate Stone   return "K";
1698b9c1b51eSKate Stone }
16992c1f46dcSZachary Turner template <> const char *GetPythonValueFormatString(float t) { return "f"; }
17002c1f46dcSZachary Turner template <> const char *GetPythonValueFormatString(double t) { return "d"; }
17012c1f46dcSZachary Turner 
170263dd5d25SJonas Devlieghere StructuredData::StringSP
170363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData(
1704b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
1705b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
17062c1f46dcSZachary Turner 
17072c1f46dcSZachary Turner   static char callee_name[] = "get_register_data";
1708b9c1b51eSKate Stone   static char *param_format =
1709b9c1b51eSKate Stone       const_cast<char *>(GetPythonValueFormatString(tid));
17102c1f46dcSZachary Turner 
17112c1f46dcSZachary Turner   if (!os_plugin_object_sp)
17122c1f46dcSZachary Turner     return StructuredData::StringSP();
17132c1f46dcSZachary Turner 
17142c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
17152c1f46dcSZachary Turner   if (!generic)
17162c1f46dcSZachary Turner     return nullptr;
1717b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1718b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
17192c1f46dcSZachary Turner 
1720f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
17212c1f46dcSZachary Turner     return StructuredData::StringSP();
17222c1f46dcSZachary Turner 
1723b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1724b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
17252c1f46dcSZachary Turner 
17262c1f46dcSZachary Turner   if (PyErr_Occurred())
17272c1f46dcSZachary Turner     PyErr_Clear();
17282c1f46dcSZachary Turner 
1729f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
17302c1f46dcSZachary Turner     return StructuredData::StringSP();
17312c1f46dcSZachary Turner 
1732b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
17332c1f46dcSZachary Turner     if (PyErr_Occurred())
17342c1f46dcSZachary Turner       PyErr_Clear();
17352c1f46dcSZachary Turner     return StructuredData::StringSP();
17362c1f46dcSZachary Turner   }
17372c1f46dcSZachary Turner 
17382c1f46dcSZachary Turner   if (PyErr_Occurred())
17392c1f46dcSZachary Turner     PyErr_Clear();
17402c1f46dcSZachary Turner 
17412c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1742b9c1b51eSKate Stone   PythonObject py_return(
1743b9c1b51eSKate Stone       PyRefType::Owned,
1744b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, param_format, tid));
17452c1f46dcSZachary Turner 
17462c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1747b9c1b51eSKate Stone   if (PyErr_Occurred()) {
17482c1f46dcSZachary Turner     PyErr_Print();
17492c1f46dcSZachary Turner     PyErr_Clear();
17502c1f46dcSZachary Turner   }
1751f8b22f8fSZachary Turner 
1752b9c1b51eSKate Stone   if (py_return.get()) {
17537a76845cSZachary Turner     PythonBytes result(PyRefType::Borrowed, py_return.get());
17547a76845cSZachary Turner     return result.CreateStructuredString();
17552c1f46dcSZachary Turner   }
175658b794aeSGreg Clayton   return StructuredData::StringSP();
175758b794aeSGreg Clayton }
17582c1f46dcSZachary Turner 
175963dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread(
1760b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
1761b9c1b51eSKate Stone     lldb::addr_t context) {
1762b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
17632c1f46dcSZachary Turner 
17642c1f46dcSZachary Turner   static char callee_name[] = "create_thread";
17652c1f46dcSZachary Turner   std::string param_format;
17662c1f46dcSZachary Turner   param_format += GetPythonValueFormatString(tid);
17672c1f46dcSZachary Turner   param_format += GetPythonValueFormatString(context);
17682c1f46dcSZachary Turner 
17692c1f46dcSZachary Turner   if (!os_plugin_object_sp)
17702c1f46dcSZachary Turner     return StructuredData::DictionarySP();
17712c1f46dcSZachary Turner 
17722c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
17732c1f46dcSZachary Turner   if (!generic)
17742c1f46dcSZachary Turner     return nullptr;
17752c1f46dcSZachary Turner 
1776b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1777b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
1778f8b22f8fSZachary Turner 
1779f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
17802c1f46dcSZachary Turner     return StructuredData::DictionarySP();
17812c1f46dcSZachary Turner 
1782b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1783b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
17842c1f46dcSZachary Turner 
17852c1f46dcSZachary Turner   if (PyErr_Occurred())
17862c1f46dcSZachary Turner     PyErr_Clear();
17872c1f46dcSZachary Turner 
1788f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
17892c1f46dcSZachary Turner     return StructuredData::DictionarySP();
17902c1f46dcSZachary Turner 
1791b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
17922c1f46dcSZachary Turner     if (PyErr_Occurred())
17932c1f46dcSZachary Turner       PyErr_Clear();
17942c1f46dcSZachary Turner     return StructuredData::DictionarySP();
17952c1f46dcSZachary Turner   }
17962c1f46dcSZachary Turner 
17972c1f46dcSZachary Turner   if (PyErr_Occurred())
17982c1f46dcSZachary Turner     PyErr_Clear();
17992c1f46dcSZachary Turner 
18002c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1801b9c1b51eSKate Stone   PythonObject py_return(PyRefType::Owned,
1802b9c1b51eSKate Stone                          PyObject_CallMethod(implementor.get(), callee_name,
1803b9c1b51eSKate Stone                                              &param_format[0], tid, context));
18042c1f46dcSZachary Turner 
18052c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1806b9c1b51eSKate Stone   if (PyErr_Occurred()) {
18072c1f46dcSZachary Turner     PyErr_Print();
18082c1f46dcSZachary Turner     PyErr_Clear();
18092c1f46dcSZachary Turner   }
18102c1f46dcSZachary Turner 
1811b9c1b51eSKate Stone   if (py_return.get()) {
1812f8b22f8fSZachary Turner     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
18132c1f46dcSZachary Turner     return result_dict.CreateStructuredDictionary();
18142c1f46dcSZachary Turner   }
181558b794aeSGreg Clayton   return StructuredData::DictionarySP();
181658b794aeSGreg Clayton }
18172c1f46dcSZachary Turner 
181863dd5d25SJonas Devlieghere StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan(
181927a14f19SJim Ingham     const char *class_name, StructuredDataImpl *args_data,
1820a69bbe02SLawrence D'Anna     std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) {
18212c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
18222c1f46dcSZachary Turner     return StructuredData::ObjectSP();
18232c1f46dcSZachary Turner 
18242c1f46dcSZachary Turner   if (!thread_plan_sp.get())
182593c98346SJim Ingham     return {};
18262c1f46dcSZachary Turner 
18272c1f46dcSZachary Turner   Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
18282b29b432SJonas Devlieghere   ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
182963dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
183063dd5d25SJonas Devlieghere       static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
18312c1f46dcSZachary Turner 
18322c1f46dcSZachary Turner   if (!script_interpreter)
183393c98346SJim Ingham     return {};
18342c1f46dcSZachary Turner 
18352c1f46dcSZachary Turner   void *ret_val;
18362c1f46dcSZachary Turner 
18372c1f46dcSZachary Turner   {
1838b9c1b51eSKate Stone     Locker py_lock(this,
1839b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
184005495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateScriptedThreadPlan(
1841b9c1b51eSKate Stone         class_name, python_interpreter->m_dictionary_name.c_str(),
184227a14f19SJim Ingham         args_data, error_str, thread_plan_sp);
184393c98346SJim Ingham     if (!ret_val)
184493c98346SJim Ingham       return {};
18452c1f46dcSZachary Turner   }
18462c1f46dcSZachary Turner 
18472c1f46dcSZachary Turner   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
18482c1f46dcSZachary Turner }
18492c1f46dcSZachary Turner 
185063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop(
1851b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
18522c1f46dcSZachary Turner   bool explains_stop = true;
18532c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
18542c1f46dcSZachary Turner   if (implementor_sp)
18552c1f46dcSZachary Turner     generic = implementor_sp->GetAsGeneric();
1856b9c1b51eSKate Stone   if (generic) {
1857b9c1b51eSKate Stone     Locker py_lock(this,
1858b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
185905495c5dSJonas Devlieghere     explains_stop = LLDBSWIGPythonCallThreadPlan(
1860b9c1b51eSKate Stone         generic->GetValue(), "explains_stop", event, script_error);
18612c1f46dcSZachary Turner     if (script_error)
18622c1f46dcSZachary Turner       return true;
18632c1f46dcSZachary Turner   }
18642c1f46dcSZachary Turner   return explains_stop;
18652c1f46dcSZachary Turner }
18662c1f46dcSZachary Turner 
186763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop(
1868b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
18692c1f46dcSZachary Turner   bool should_stop = true;
18702c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
18712c1f46dcSZachary Turner   if (implementor_sp)
18722c1f46dcSZachary Turner     generic = implementor_sp->GetAsGeneric();
1873b9c1b51eSKate Stone   if (generic) {
1874b9c1b51eSKate Stone     Locker py_lock(this,
1875b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
187605495c5dSJonas Devlieghere     should_stop = LLDBSWIGPythonCallThreadPlan(
187705495c5dSJonas Devlieghere         generic->GetValue(), "should_stop", event, script_error);
18782c1f46dcSZachary Turner     if (script_error)
18792c1f46dcSZachary Turner       return true;
18802c1f46dcSZachary Turner   }
18812c1f46dcSZachary Turner   return should_stop;
18822c1f46dcSZachary Turner }
18832c1f46dcSZachary Turner 
188463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale(
1885b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1886c915a7d2SJim Ingham   bool is_stale = true;
1887c915a7d2SJim Ingham   StructuredData::Generic *generic = nullptr;
1888c915a7d2SJim Ingham   if (implementor_sp)
1889c915a7d2SJim Ingham     generic = implementor_sp->GetAsGeneric();
1890b9c1b51eSKate Stone   if (generic) {
1891b9c1b51eSKate Stone     Locker py_lock(this,
1892b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
189305495c5dSJonas Devlieghere     is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale",
189405495c5dSJonas Devlieghere                                             nullptr, script_error);
1895c915a7d2SJim Ingham     if (script_error)
1896c915a7d2SJim Ingham       return true;
1897c915a7d2SJim Ingham   }
1898c915a7d2SJim Ingham   return is_stale;
1899c915a7d2SJim Ingham }
1900c915a7d2SJim Ingham 
190163dd5d25SJonas Devlieghere lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState(
1902b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, bool &script_error) {
19032c1f46dcSZachary Turner   bool should_step = false;
19042c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
19052c1f46dcSZachary Turner   if (implementor_sp)
19062c1f46dcSZachary Turner     generic = implementor_sp->GetAsGeneric();
1907b9c1b51eSKate Stone   if (generic) {
1908b9c1b51eSKate Stone     Locker py_lock(this,
1909b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
191005495c5dSJonas Devlieghere     should_step = LLDBSWIGPythonCallThreadPlan(
1911248a1305SKonrad Kleine         generic->GetValue(), "should_step", nullptr, script_error);
19122c1f46dcSZachary Turner     if (script_error)
19132c1f46dcSZachary Turner       should_step = true;
19142c1f46dcSZachary Turner   }
19152c1f46dcSZachary Turner   if (should_step)
19162c1f46dcSZachary Turner     return lldb::eStateStepping;
19172c1f46dcSZachary Turner   return lldb::eStateRunning;
19182c1f46dcSZachary Turner }
19192c1f46dcSZachary Turner 
19203815e702SJim Ingham StructuredData::GenericSP
192163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
192263dd5d25SJonas Devlieghere     const char *class_name, StructuredDataImpl *args_data,
19233815e702SJim Ingham     lldb::BreakpointSP &bkpt_sp) {
19243815e702SJim Ingham 
19253815e702SJim Ingham   if (class_name == nullptr || class_name[0] == '\0')
19263815e702SJim Ingham     return StructuredData::GenericSP();
19273815e702SJim Ingham 
19283815e702SJim Ingham   if (!bkpt_sp.get())
19293815e702SJim Ingham     return StructuredData::GenericSP();
19303815e702SJim Ingham 
19313815e702SJim Ingham   Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
19322b29b432SJonas Devlieghere   ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
193363dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
193463dd5d25SJonas Devlieghere       static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
19353815e702SJim Ingham 
19363815e702SJim Ingham   if (!script_interpreter)
19373815e702SJim Ingham     return StructuredData::GenericSP();
19383815e702SJim Ingham 
19393815e702SJim Ingham   void *ret_val;
19403815e702SJim Ingham 
19413815e702SJim Ingham   {
19423815e702SJim Ingham     Locker py_lock(this,
19433815e702SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19443815e702SJim Ingham 
194505495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver(
194605495c5dSJonas Devlieghere         class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
194705495c5dSJonas Devlieghere         bkpt_sp);
19483815e702SJim Ingham   }
19493815e702SJim Ingham 
19503815e702SJim Ingham   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
19513815e702SJim Ingham }
19523815e702SJim Ingham 
195363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
195463dd5d25SJonas Devlieghere     StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
19553815e702SJim Ingham   bool should_continue = false;
19563815e702SJim Ingham 
19573815e702SJim Ingham   if (implementor_sp) {
19583815e702SJim Ingham     Locker py_lock(this,
19593815e702SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
196005495c5dSJonas Devlieghere     should_continue = LLDBSwigPythonCallBreakpointResolver(
196105495c5dSJonas Devlieghere         implementor_sp->GetValue(), "__callback__", sym_ctx);
19623815e702SJim Ingham     if (PyErr_Occurred()) {
19633815e702SJim Ingham       PyErr_Print();
19643815e702SJim Ingham       PyErr_Clear();
19653815e702SJim Ingham     }
19663815e702SJim Ingham   }
19673815e702SJim Ingham   return should_continue;
19683815e702SJim Ingham }
19693815e702SJim Ingham 
19703815e702SJim Ingham lldb::SearchDepth
197163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
19723815e702SJim Ingham     StructuredData::GenericSP implementor_sp) {
19733815e702SJim Ingham   int depth_as_int = lldb::eSearchDepthModule;
19743815e702SJim Ingham   if (implementor_sp) {
19753815e702SJim Ingham     Locker py_lock(this,
19763815e702SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
197705495c5dSJonas Devlieghere     depth_as_int = LLDBSwigPythonCallBreakpointResolver(
197805495c5dSJonas Devlieghere         implementor_sp->GetValue(), "__get_depth__", nullptr);
19793815e702SJim Ingham     if (PyErr_Occurred()) {
19803815e702SJim Ingham       PyErr_Print();
19813815e702SJim Ingham       PyErr_Clear();
19823815e702SJim Ingham     }
19833815e702SJim Ingham   }
19843815e702SJim Ingham   if (depth_as_int == lldb::eSearchDepthInvalid)
19853815e702SJim Ingham     return lldb::eSearchDepthModule;
19863815e702SJim Ingham 
19873815e702SJim Ingham   if (depth_as_int <= lldb::kLastSearchDepthKind)
19883815e702SJim Ingham     return (lldb::SearchDepth)depth_as_int;
19893815e702SJim Ingham   return lldb::eSearchDepthModule;
19903815e702SJim Ingham }
19913815e702SJim Ingham 
19921b1d9815SJim Ingham StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
19931b1d9815SJim Ingham     TargetSP target_sp, const char *class_name, StructuredDataImpl *args_data,
19941b1d9815SJim Ingham     Status &error) {
19951b1d9815SJim Ingham 
19961b1d9815SJim Ingham   if (!target_sp) {
19971b1d9815SJim Ingham     error.SetErrorString("No target for scripted stop-hook.");
19981b1d9815SJim Ingham     return StructuredData::GenericSP();
19991b1d9815SJim Ingham   }
20001b1d9815SJim Ingham 
20011b1d9815SJim Ingham   if (class_name == nullptr || class_name[0] == '\0') {
20021b1d9815SJim Ingham     error.SetErrorString("No class name for scripted stop-hook.");
20031b1d9815SJim Ingham     return StructuredData::GenericSP();
20041b1d9815SJim Ingham   }
20051b1d9815SJim Ingham 
20061b1d9815SJim Ingham   ScriptInterpreter *script_interpreter = m_debugger.GetScriptInterpreter();
20071b1d9815SJim Ingham   ScriptInterpreterPythonImpl *python_interpreter =
20081b1d9815SJim Ingham       static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
20091b1d9815SJim Ingham 
20101b1d9815SJim Ingham   if (!script_interpreter) {
20111b1d9815SJim Ingham     error.SetErrorString("No script interpreter for scripted stop-hook.");
20121b1d9815SJim Ingham     return StructuredData::GenericSP();
20131b1d9815SJim Ingham   }
20141b1d9815SJim Ingham 
20151b1d9815SJim Ingham   void *ret_val;
20161b1d9815SJim Ingham 
20171b1d9815SJim Ingham   {
20181b1d9815SJim Ingham     Locker py_lock(this,
20191b1d9815SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
20201b1d9815SJim Ingham 
20211b1d9815SJim Ingham     ret_val = LLDBSwigPythonCreateScriptedStopHook(
20221b1d9815SJim Ingham         target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
20231b1d9815SJim Ingham         args_data, error);
20241b1d9815SJim Ingham   }
20251b1d9815SJim Ingham 
20261b1d9815SJim Ingham   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
20271b1d9815SJim Ingham }
20281b1d9815SJim Ingham 
20291b1d9815SJim Ingham bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
20301b1d9815SJim Ingham     StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
20311b1d9815SJim Ingham     lldb::StreamSP stream_sp) {
20321b1d9815SJim Ingham   assert(implementor_sp &&
20331b1d9815SJim Ingham          "can't call a stop hook with an invalid implementor");
20341b1d9815SJim Ingham   assert(stream_sp && "can't call a stop hook with an invalid stream");
20351b1d9815SJim Ingham 
20361b1d9815SJim Ingham   Locker py_lock(this,
20371b1d9815SJim Ingham                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
20381b1d9815SJim Ingham 
20391b1d9815SJim Ingham   lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
20401b1d9815SJim Ingham 
20411b1d9815SJim Ingham   bool ret_val = LLDBSwigPythonStopHookCallHandleStop(
20421b1d9815SJim Ingham       implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
20431b1d9815SJim Ingham   return ret_val;
20441b1d9815SJim Ingham }
20451b1d9815SJim Ingham 
20462c1f46dcSZachary Turner StructuredData::ObjectSP
204763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
204897206d57SZachary Turner                                               lldb_private::Status &error) {
2049dbd7fabaSJonas Devlieghere   if (!FileSystem::Instance().Exists(file_spec)) {
20502c1f46dcSZachary Turner     error.SetErrorString("no such file");
20512c1f46dcSZachary Turner     return StructuredData::ObjectSP();
20522c1f46dcSZachary Turner   }
20532c1f46dcSZachary Turner 
20542c1f46dcSZachary Turner   StructuredData::ObjectSP module_sp;
20552c1f46dcSZachary Turner 
205615625112SJonas Devlieghere   if (LoadScriptingModule(file_spec.GetPath().c_str(), true, error, &module_sp))
20572c1f46dcSZachary Turner     return module_sp;
20582c1f46dcSZachary Turner 
20592c1f46dcSZachary Turner   return StructuredData::ObjectSP();
20602c1f46dcSZachary Turner }
20612c1f46dcSZachary Turner 
206263dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
2063b9c1b51eSKate Stone     StructuredData::ObjectSP plugin_module_sp, Target *target,
206497206d57SZachary Turner     const char *setting_name, lldb_private::Status &error) {
206505495c5dSJonas Devlieghere   if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
20662c1f46dcSZachary Turner     return StructuredData::DictionarySP();
20672c1f46dcSZachary Turner   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
20682c1f46dcSZachary Turner   if (!generic)
20692c1f46dcSZachary Turner     return StructuredData::DictionarySP();
20702c1f46dcSZachary Turner 
2071b9c1b51eSKate Stone   Locker py_lock(this,
2072b9c1b51eSKate Stone                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
20732c1f46dcSZachary Turner   TargetSP target_sp(target->shared_from_this());
20742c1f46dcSZachary Turner 
207504edd189SLawrence D'Anna   auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting(
207604edd189SLawrence D'Anna       generic->GetValue(), setting_name, target_sp);
207704edd189SLawrence D'Anna 
207804edd189SLawrence D'Anna   if (!setting)
207904edd189SLawrence D'Anna     return StructuredData::DictionarySP();
208004edd189SLawrence D'Anna 
208104edd189SLawrence D'Anna   PythonDictionary py_dict =
208204edd189SLawrence D'Anna       unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
208304edd189SLawrence D'Anna 
208404edd189SLawrence D'Anna   if (!py_dict)
208504edd189SLawrence D'Anna     return StructuredData::DictionarySP();
208604edd189SLawrence D'Anna 
20872c1f46dcSZachary Turner   return py_dict.CreateStructuredDictionary();
20882c1f46dcSZachary Turner }
20892c1f46dcSZachary Turner 
20902c1f46dcSZachary Turner StructuredData::ObjectSP
209163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
2092b9c1b51eSKate Stone     const char *class_name, lldb::ValueObjectSP valobj) {
20932c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
20942c1f46dcSZachary Turner     return StructuredData::ObjectSP();
20952c1f46dcSZachary Turner 
20962c1f46dcSZachary Turner   if (!valobj.get())
20972c1f46dcSZachary Turner     return StructuredData::ObjectSP();
20982c1f46dcSZachary Turner 
20992c1f46dcSZachary Turner   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
21002c1f46dcSZachary Turner   Target *target = exe_ctx.GetTargetPtr();
21012c1f46dcSZachary Turner 
21022c1f46dcSZachary Turner   if (!target)
21032c1f46dcSZachary Turner     return StructuredData::ObjectSP();
21042c1f46dcSZachary Turner 
21052c1f46dcSZachary Turner   Debugger &debugger = target->GetDebugger();
21062b29b432SJonas Devlieghere   ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
210763dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
210863dd5d25SJonas Devlieghere       (ScriptInterpreterPythonImpl *)script_interpreter;
21092c1f46dcSZachary Turner 
21102c1f46dcSZachary Turner   if (!script_interpreter)
21112c1f46dcSZachary Turner     return StructuredData::ObjectSP();
21122c1f46dcSZachary Turner 
21132c1f46dcSZachary Turner   void *ret_val = nullptr;
21142c1f46dcSZachary Turner 
21152c1f46dcSZachary Turner   {
2116b9c1b51eSKate Stone     Locker py_lock(this,
2117b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
211805495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateSyntheticProvider(
2119b9c1b51eSKate Stone         class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
21202c1f46dcSZachary Turner   }
21212c1f46dcSZachary Turner 
21222c1f46dcSZachary Turner   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
21232c1f46dcSZachary Turner }
21242c1f46dcSZachary Turner 
21252c1f46dcSZachary Turner StructuredData::GenericSP
212663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
21278d1fb843SJonas Devlieghere   DebuggerSP debugger_sp(m_debugger.shared_from_this());
21282c1f46dcSZachary Turner 
21292c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
21302c1f46dcSZachary Turner     return StructuredData::GenericSP();
21312c1f46dcSZachary Turner 
21322c1f46dcSZachary Turner   if (!debugger_sp.get())
21332c1f46dcSZachary Turner     return StructuredData::GenericSP();
21342c1f46dcSZachary Turner 
21352c1f46dcSZachary Turner   void *ret_val;
21362c1f46dcSZachary Turner 
21372c1f46dcSZachary Turner   {
2138b9c1b51eSKate Stone     Locker py_lock(this,
2139b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
214005495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateCommandObject(
214105495c5dSJonas Devlieghere         class_name, m_dictionary_name.c_str(), debugger_sp);
21422c1f46dcSZachary Turner   }
21432c1f46dcSZachary Turner 
21442c1f46dcSZachary Turner   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
21452c1f46dcSZachary Turner }
21462c1f46dcSZachary Turner 
214763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
2148b9c1b51eSKate Stone     const char *oneliner, std::string &output, const void *name_token) {
21492c1f46dcSZachary Turner   StringList input;
21502c1f46dcSZachary Turner   input.SplitIntoLines(oneliner, strlen(oneliner));
21512c1f46dcSZachary Turner   return GenerateTypeScriptFunction(input, output, name_token);
21522c1f46dcSZachary Turner }
21532c1f46dcSZachary Turner 
215463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
215563dd5d25SJonas Devlieghere     const char *oneliner, std::string &output, const void *name_token) {
21562c1f46dcSZachary Turner   StringList input;
21572c1f46dcSZachary Turner   input.SplitIntoLines(oneliner, strlen(oneliner));
21582c1f46dcSZachary Turner   return GenerateTypeSynthClass(input, output, name_token);
21592c1f46dcSZachary Turner }
21602c1f46dcSZachary Turner 
216163dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
2162738af7a6SJim Ingham     StringList &user_input, std::string &output,
2163738af7a6SJim Ingham     bool has_extra_args) {
21642c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
21652c1f46dcSZachary Turner   user_input.RemoveBlankLines();
21662c1f46dcSZachary Turner   StreamString sstr;
216797206d57SZachary Turner   Status error;
2168b9c1b51eSKate Stone   if (user_input.GetSize() == 0) {
21692c1f46dcSZachary Turner     error.SetErrorString("No input data.");
21702c1f46dcSZachary Turner     return error;
21712c1f46dcSZachary Turner   }
21722c1f46dcSZachary Turner 
2173b9c1b51eSKate Stone   std::string auto_generated_function_name(GenerateUniqueName(
2174b9c1b51eSKate Stone       "lldb_autogen_python_bp_callback_func_", num_created_functions));
2175738af7a6SJim Ingham   if (has_extra_args)
2176738af7a6SJim Ingham     sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
2177738af7a6SJim Ingham                 auto_generated_function_name.c_str());
2178738af7a6SJim Ingham   else
2179b9c1b51eSKate Stone     sstr.Printf("def %s (frame, bp_loc, internal_dict):",
2180b9c1b51eSKate Stone                 auto_generated_function_name.c_str());
21812c1f46dcSZachary Turner 
21822c1f46dcSZachary Turner   error = GenerateFunction(sstr.GetData(), user_input);
21832c1f46dcSZachary Turner   if (!error.Success())
21842c1f46dcSZachary Turner     return error;
21852c1f46dcSZachary Turner 
21862c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
21872c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
21882c1f46dcSZachary Turner   return error;
21892c1f46dcSZachary Turner }
21902c1f46dcSZachary Turner 
219163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
2192b9c1b51eSKate Stone     StringList &user_input, std::string &output) {
21932c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
21942c1f46dcSZachary Turner   user_input.RemoveBlankLines();
21952c1f46dcSZachary Turner   StreamString sstr;
21962c1f46dcSZachary Turner 
21972c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
21982c1f46dcSZachary Turner     return false;
21992c1f46dcSZachary Turner 
2200b9c1b51eSKate Stone   std::string auto_generated_function_name(GenerateUniqueName(
2201b9c1b51eSKate Stone       "lldb_autogen_python_wp_callback_func_", num_created_functions));
2202b9c1b51eSKate Stone   sstr.Printf("def %s (frame, wp, internal_dict):",
2203b9c1b51eSKate Stone               auto_generated_function_name.c_str());
22042c1f46dcSZachary Turner 
22052c1f46dcSZachary Turner   if (!GenerateFunction(sstr.GetData(), user_input).Success())
22062c1f46dcSZachary Turner     return false;
22072c1f46dcSZachary Turner 
22082c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
22092c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
22102c1f46dcSZachary Turner   return true;
22112c1f46dcSZachary Turner }
22122c1f46dcSZachary Turner 
221363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetScriptedSummary(
2214b9c1b51eSKate Stone     const char *python_function_name, lldb::ValueObjectSP valobj,
2215b9c1b51eSKate Stone     StructuredData::ObjectSP &callee_wrapper_sp,
2216b9c1b51eSKate Stone     const TypeSummaryOptions &options, std::string &retval) {
22172c1f46dcSZachary Turner 
2218f9d16476SPavel Labath   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2219f9d16476SPavel Labath   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
22202c1f46dcSZachary Turner 
2221b9c1b51eSKate Stone   if (!valobj.get()) {
22222c1f46dcSZachary Turner     retval.assign("<no object>");
22232c1f46dcSZachary Turner     return false;
22242c1f46dcSZachary Turner   }
22252c1f46dcSZachary Turner 
22262c1f46dcSZachary Turner   void *old_callee = nullptr;
22272c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
2228b9c1b51eSKate Stone   if (callee_wrapper_sp) {
22292c1f46dcSZachary Turner     generic = callee_wrapper_sp->GetAsGeneric();
22302c1f46dcSZachary Turner     if (generic)
22312c1f46dcSZachary Turner       old_callee = generic->GetValue();
22322c1f46dcSZachary Turner   }
22332c1f46dcSZachary Turner   void *new_callee = old_callee;
22342c1f46dcSZachary Turner 
22352c1f46dcSZachary Turner   bool ret_val;
2236b9c1b51eSKate Stone   if (python_function_name && *python_function_name) {
22372c1f46dcSZachary Turner     {
2238b9c1b51eSKate Stone       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
2239b9c1b51eSKate Stone                                Locker::NoSTDIN);
22402c1f46dcSZachary Turner       {
22412c1f46dcSZachary Turner         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
22422c1f46dcSZachary Turner 
224305495c5dSJonas Devlieghere         static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
224405495c5dSJonas Devlieghere         Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
224505495c5dSJonas Devlieghere         ret_val = LLDBSwigPythonCallTypeScript(
2246b9c1b51eSKate Stone             python_function_name, GetSessionDictionary().get(), valobj,
2247b9c1b51eSKate Stone             &new_callee, options_sp, retval);
22482c1f46dcSZachary Turner       }
22492c1f46dcSZachary Turner     }
2250b9c1b51eSKate Stone   } else {
22512c1f46dcSZachary Turner     retval.assign("<no function name>");
22522c1f46dcSZachary Turner     return false;
22532c1f46dcSZachary Turner   }
22542c1f46dcSZachary Turner 
22552c1f46dcSZachary Turner   if (new_callee && old_callee != new_callee)
2256796ac80bSJonas Devlieghere     callee_wrapper_sp = std::make_shared<StructuredPythonObject>(new_callee);
22572c1f46dcSZachary Turner 
22582c1f46dcSZachary Turner   return ret_val;
22592c1f46dcSZachary Turner }
22602c1f46dcSZachary Turner 
226163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
2262b9c1b51eSKate Stone     void *baton, StoppointCallbackContext *context, user_id_t break_id,
2263b9c1b51eSKate Stone     user_id_t break_loc_id) {
2264f7e07256SJim Ingham   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
22652c1f46dcSZachary Turner   const char *python_function_name = bp_option_data->script_source.c_str();
22662c1f46dcSZachary Turner 
22672c1f46dcSZachary Turner   if (!context)
22682c1f46dcSZachary Turner     return true;
22692c1f46dcSZachary Turner 
22702c1f46dcSZachary Turner   ExecutionContext exe_ctx(context->exe_ctx_ref);
22712c1f46dcSZachary Turner   Target *target = exe_ctx.GetTargetPtr();
22722c1f46dcSZachary Turner 
22732c1f46dcSZachary Turner   if (!target)
22742c1f46dcSZachary Turner     return true;
22752c1f46dcSZachary Turner 
22762c1f46dcSZachary Turner   Debugger &debugger = target->GetDebugger();
22772b29b432SJonas Devlieghere   ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
227863dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
227963dd5d25SJonas Devlieghere       (ScriptInterpreterPythonImpl *)script_interpreter;
22802c1f46dcSZachary Turner 
22812c1f46dcSZachary Turner   if (!script_interpreter)
22822c1f46dcSZachary Turner     return true;
22832c1f46dcSZachary Turner 
2284b9c1b51eSKate Stone   if (python_function_name && python_function_name[0]) {
22852c1f46dcSZachary Turner     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
22862c1f46dcSZachary Turner     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2287b9c1b51eSKate Stone     if (breakpoint_sp) {
2288b9c1b51eSKate Stone       const BreakpointLocationSP bp_loc_sp(
2289b9c1b51eSKate Stone           breakpoint_sp->FindLocationByID(break_loc_id));
22902c1f46dcSZachary Turner 
2291b9c1b51eSKate Stone       if (stop_frame_sp && bp_loc_sp) {
22922c1f46dcSZachary Turner         bool ret_val = true;
22932c1f46dcSZachary Turner         {
2294b9c1b51eSKate Stone           Locker py_lock(python_interpreter, Locker::AcquireLock |
2295b9c1b51eSKate Stone                                                  Locker::InitSession |
2296b9c1b51eSKate Stone                                                  Locker::NoSTDIN);
2297a69bbe02SLawrence D'Anna           Expected<bool> maybe_ret_val =
2298a69bbe02SLawrence D'Anna               LLDBSwigPythonBreakpointCallbackFunction(
2299b9c1b51eSKate Stone                   python_function_name,
2300b9c1b51eSKate Stone                   python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2301a69bbe02SLawrence D'Anna                   bp_loc_sp, bp_option_data->m_extra_args_up.get());
2302a69bbe02SLawrence D'Anna 
2303a69bbe02SLawrence D'Anna           if (!maybe_ret_val) {
2304a69bbe02SLawrence D'Anna 
2305a69bbe02SLawrence D'Anna             llvm::handleAllErrors(
2306a69bbe02SLawrence D'Anna                 maybe_ret_val.takeError(),
2307a69bbe02SLawrence D'Anna                 [&](PythonException &E) {
2308a69bbe02SLawrence D'Anna                   debugger.GetErrorStream() << E.ReadBacktrace();
2309a69bbe02SLawrence D'Anna                 },
2310a69bbe02SLawrence D'Anna                 [&](const llvm::ErrorInfoBase &E) {
2311a69bbe02SLawrence D'Anna                   debugger.GetErrorStream() << E.message();
2312a69bbe02SLawrence D'Anna                 });
2313a69bbe02SLawrence D'Anna 
2314a69bbe02SLawrence D'Anna           } else {
2315a69bbe02SLawrence D'Anna             ret_val = maybe_ret_val.get();
2316a69bbe02SLawrence D'Anna           }
23172c1f46dcSZachary Turner         }
23182c1f46dcSZachary Turner         return ret_val;
23192c1f46dcSZachary Turner       }
23202c1f46dcSZachary Turner     }
23212c1f46dcSZachary Turner   }
23222c1f46dcSZachary Turner   // We currently always true so we stop in case anything goes wrong when
23232c1f46dcSZachary Turner   // trying to call the script function
23242c1f46dcSZachary Turner   return true;
23252c1f46dcSZachary Turner }
23262c1f46dcSZachary Turner 
232763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
2328b9c1b51eSKate Stone     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2329b9c1b51eSKate Stone   WatchpointOptions::CommandData *wp_option_data =
2330b9c1b51eSKate Stone       (WatchpointOptions::CommandData *)baton;
23312c1f46dcSZachary Turner   const char *python_function_name = wp_option_data->script_source.c_str();
23322c1f46dcSZachary Turner 
23332c1f46dcSZachary Turner   if (!context)
23342c1f46dcSZachary Turner     return true;
23352c1f46dcSZachary Turner 
23362c1f46dcSZachary Turner   ExecutionContext exe_ctx(context->exe_ctx_ref);
23372c1f46dcSZachary Turner   Target *target = exe_ctx.GetTargetPtr();
23382c1f46dcSZachary Turner 
23392c1f46dcSZachary Turner   if (!target)
23402c1f46dcSZachary Turner     return true;
23412c1f46dcSZachary Turner 
23422c1f46dcSZachary Turner   Debugger &debugger = target->GetDebugger();
23432b29b432SJonas Devlieghere   ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
234463dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
234563dd5d25SJonas Devlieghere       (ScriptInterpreterPythonImpl *)script_interpreter;
23462c1f46dcSZachary Turner 
23472c1f46dcSZachary Turner   if (!script_interpreter)
23482c1f46dcSZachary Turner     return true;
23492c1f46dcSZachary Turner 
2350b9c1b51eSKate Stone   if (python_function_name && python_function_name[0]) {
23512c1f46dcSZachary Turner     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
23522c1f46dcSZachary Turner     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2353b9c1b51eSKate Stone     if (wp_sp) {
2354b9c1b51eSKate Stone       if (stop_frame_sp && wp_sp) {
23552c1f46dcSZachary Turner         bool ret_val = true;
23562c1f46dcSZachary Turner         {
2357b9c1b51eSKate Stone           Locker py_lock(python_interpreter, Locker::AcquireLock |
2358b9c1b51eSKate Stone                                                  Locker::InitSession |
2359b9c1b51eSKate Stone                                                  Locker::NoSTDIN);
236005495c5dSJonas Devlieghere           ret_val = LLDBSwigPythonWatchpointCallbackFunction(
2361b9c1b51eSKate Stone               python_function_name,
2362b9c1b51eSKate Stone               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
23632c1f46dcSZachary Turner               wp_sp);
23642c1f46dcSZachary Turner         }
23652c1f46dcSZachary Turner         return ret_val;
23662c1f46dcSZachary Turner       }
23672c1f46dcSZachary Turner     }
23682c1f46dcSZachary Turner   }
23692c1f46dcSZachary Turner   // We currently always true so we stop in case anything goes wrong when
23702c1f46dcSZachary Turner   // trying to call the script function
23712c1f46dcSZachary Turner   return true;
23722c1f46dcSZachary Turner }
23732c1f46dcSZachary Turner 
237463dd5d25SJonas Devlieghere size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2375b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
23762c1f46dcSZachary Turner   if (!implementor_sp)
23772c1f46dcSZachary Turner     return 0;
23782c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
23792c1f46dcSZachary Turner   if (!generic)
23802c1f46dcSZachary Turner     return 0;
23812c1f46dcSZachary Turner   void *implementor = generic->GetValue();
23822c1f46dcSZachary Turner   if (!implementor)
23832c1f46dcSZachary Turner     return 0;
23842c1f46dcSZachary Turner 
23852c1f46dcSZachary Turner   size_t ret_val = 0;
23862c1f46dcSZachary Turner 
23872c1f46dcSZachary Turner   {
2388b9c1b51eSKate Stone     Locker py_lock(this,
2389b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
239005495c5dSJonas Devlieghere     ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max);
23912c1f46dcSZachary Turner   }
23922c1f46dcSZachary Turner 
23932c1f46dcSZachary Turner   return ret_val;
23942c1f46dcSZachary Turner }
23952c1f46dcSZachary Turner 
239663dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
2397b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
23982c1f46dcSZachary Turner   if (!implementor_sp)
23992c1f46dcSZachary Turner     return lldb::ValueObjectSP();
24002c1f46dcSZachary Turner 
24012c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24022c1f46dcSZachary Turner   if (!generic)
24032c1f46dcSZachary Turner     return lldb::ValueObjectSP();
24042c1f46dcSZachary Turner   void *implementor = generic->GetValue();
24052c1f46dcSZachary Turner   if (!implementor)
24062c1f46dcSZachary Turner     return lldb::ValueObjectSP();
24072c1f46dcSZachary Turner 
24082c1f46dcSZachary Turner   lldb::ValueObjectSP ret_val;
24092c1f46dcSZachary Turner   {
2410b9c1b51eSKate Stone     Locker py_lock(this,
2411b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
241205495c5dSJonas Devlieghere     void *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx);
2413b9c1b51eSKate Stone     if (child_ptr != nullptr && child_ptr != Py_None) {
2414b9c1b51eSKate Stone       lldb::SBValue *sb_value_ptr =
241505495c5dSJonas Devlieghere           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
24162c1f46dcSZachary Turner       if (sb_value_ptr == nullptr)
24172c1f46dcSZachary Turner         Py_XDECREF(child_ptr);
24182c1f46dcSZachary Turner       else
241905495c5dSJonas Devlieghere         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2420b9c1b51eSKate Stone     } else {
24212c1f46dcSZachary Turner       Py_XDECREF(child_ptr);
24222c1f46dcSZachary Turner     }
24232c1f46dcSZachary Turner   }
24242c1f46dcSZachary Turner 
24252c1f46dcSZachary Turner   return ret_val;
24262c1f46dcSZachary Turner }
24272c1f46dcSZachary Turner 
242863dd5d25SJonas Devlieghere int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2429b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
24302c1f46dcSZachary Turner   if (!implementor_sp)
24312c1f46dcSZachary Turner     return UINT32_MAX;
24322c1f46dcSZachary Turner 
24332c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24342c1f46dcSZachary Turner   if (!generic)
24352c1f46dcSZachary Turner     return UINT32_MAX;
24362c1f46dcSZachary Turner   void *implementor = generic->GetValue();
24372c1f46dcSZachary Turner   if (!implementor)
24382c1f46dcSZachary Turner     return UINT32_MAX;
24392c1f46dcSZachary Turner 
24402c1f46dcSZachary Turner   int ret_val = UINT32_MAX;
24412c1f46dcSZachary Turner 
24422c1f46dcSZachary Turner   {
2443b9c1b51eSKate Stone     Locker py_lock(this,
2444b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
244505495c5dSJonas Devlieghere     ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
24462c1f46dcSZachary Turner   }
24472c1f46dcSZachary Turner 
24482c1f46dcSZachary Turner   return ret_val;
24492c1f46dcSZachary Turner }
24502c1f46dcSZachary Turner 
245163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2452b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
24532c1f46dcSZachary Turner   bool ret_val = false;
24542c1f46dcSZachary Turner 
24552c1f46dcSZachary Turner   if (!implementor_sp)
24562c1f46dcSZachary Turner     return ret_val;
24572c1f46dcSZachary Turner 
24582c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24592c1f46dcSZachary Turner   if (!generic)
24602c1f46dcSZachary Turner     return ret_val;
24612c1f46dcSZachary Turner   void *implementor = generic->GetValue();
24622c1f46dcSZachary Turner   if (!implementor)
24632c1f46dcSZachary Turner     return ret_val;
24642c1f46dcSZachary Turner 
24652c1f46dcSZachary Turner   {
2466b9c1b51eSKate Stone     Locker py_lock(this,
2467b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
246805495c5dSJonas Devlieghere     ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor);
24692c1f46dcSZachary Turner   }
24702c1f46dcSZachary Turner 
24712c1f46dcSZachary Turner   return ret_val;
24722c1f46dcSZachary Turner }
24732c1f46dcSZachary Turner 
247463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2475b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
24762c1f46dcSZachary Turner   bool ret_val = false;
24772c1f46dcSZachary Turner 
24782c1f46dcSZachary Turner   if (!implementor_sp)
24792c1f46dcSZachary Turner     return ret_val;
24802c1f46dcSZachary Turner 
24812c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24822c1f46dcSZachary Turner   if (!generic)
24832c1f46dcSZachary Turner     return ret_val;
24842c1f46dcSZachary Turner   void *implementor = generic->GetValue();
24852c1f46dcSZachary Turner   if (!implementor)
24862c1f46dcSZachary Turner     return ret_val;
24872c1f46dcSZachary Turner 
24882c1f46dcSZachary Turner   {
2489b9c1b51eSKate Stone     Locker py_lock(this,
2490b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
249105495c5dSJonas Devlieghere     ret_val =
249205495c5dSJonas Devlieghere         LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor);
24932c1f46dcSZachary Turner   }
24942c1f46dcSZachary Turner 
24952c1f46dcSZachary Turner   return ret_val;
24962c1f46dcSZachary Turner }
24972c1f46dcSZachary Turner 
249863dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
2499b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
25002c1f46dcSZachary Turner   lldb::ValueObjectSP ret_val(nullptr);
25012c1f46dcSZachary Turner 
25022c1f46dcSZachary Turner   if (!implementor_sp)
25032c1f46dcSZachary Turner     return ret_val;
25042c1f46dcSZachary Turner 
25052c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
25062c1f46dcSZachary Turner   if (!generic)
25072c1f46dcSZachary Turner     return ret_val;
25082c1f46dcSZachary Turner   void *implementor = generic->GetValue();
25092c1f46dcSZachary Turner   if (!implementor)
25102c1f46dcSZachary Turner     return ret_val;
25112c1f46dcSZachary Turner 
25122c1f46dcSZachary Turner   {
2513b9c1b51eSKate Stone     Locker py_lock(this,
2514b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
251505495c5dSJonas Devlieghere     void *child_ptr = LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2516b9c1b51eSKate Stone     if (child_ptr != nullptr && child_ptr != Py_None) {
2517b9c1b51eSKate Stone       lldb::SBValue *sb_value_ptr =
251805495c5dSJonas Devlieghere           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
25192c1f46dcSZachary Turner       if (sb_value_ptr == nullptr)
25202c1f46dcSZachary Turner         Py_XDECREF(child_ptr);
25212c1f46dcSZachary Turner       else
252205495c5dSJonas Devlieghere         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2523b9c1b51eSKate Stone     } else {
25242c1f46dcSZachary Turner       Py_XDECREF(child_ptr);
25252c1f46dcSZachary Turner     }
25262c1f46dcSZachary Turner   }
25272c1f46dcSZachary Turner 
25282c1f46dcSZachary Turner   return ret_val;
25292c1f46dcSZachary Turner }
25302c1f46dcSZachary Turner 
253163dd5d25SJonas Devlieghere ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2532b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
2533b9c1b51eSKate Stone   Locker py_lock(this,
2534b9c1b51eSKate Stone                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
25356eec8d6cSEnrico Granata 
25366eec8d6cSEnrico Granata   static char callee_name[] = "get_type_name";
25376eec8d6cSEnrico Granata 
25386eec8d6cSEnrico Granata   ConstString ret_val;
25396eec8d6cSEnrico Granata   bool got_string = false;
25406eec8d6cSEnrico Granata   std::string buffer;
25416eec8d6cSEnrico Granata 
25426eec8d6cSEnrico Granata   if (!implementor_sp)
25436eec8d6cSEnrico Granata     return ret_val;
25446eec8d6cSEnrico Granata 
25456eec8d6cSEnrico Granata   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
25466eec8d6cSEnrico Granata   if (!generic)
25476eec8d6cSEnrico Granata     return ret_val;
2548b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
2549b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
25506eec8d6cSEnrico Granata   if (!implementor.IsAllocated())
25516eec8d6cSEnrico Granata     return ret_val;
25526eec8d6cSEnrico Granata 
2553b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
2554b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
25556eec8d6cSEnrico Granata 
25566eec8d6cSEnrico Granata   if (PyErr_Occurred())
25576eec8d6cSEnrico Granata     PyErr_Clear();
25586eec8d6cSEnrico Granata 
25596eec8d6cSEnrico Granata   if (!pmeth.IsAllocated())
25606eec8d6cSEnrico Granata     return ret_val;
25616eec8d6cSEnrico Granata 
2562b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
25636eec8d6cSEnrico Granata     if (PyErr_Occurred())
25646eec8d6cSEnrico Granata       PyErr_Clear();
25656eec8d6cSEnrico Granata     return ret_val;
25666eec8d6cSEnrico Granata   }
25676eec8d6cSEnrico Granata 
25686eec8d6cSEnrico Granata   if (PyErr_Occurred())
25696eec8d6cSEnrico Granata     PyErr_Clear();
25706eec8d6cSEnrico Granata 
25716eec8d6cSEnrico Granata   // right now we know this function exists and is callable..
2572b9c1b51eSKate Stone   PythonObject py_return(
2573b9c1b51eSKate Stone       PyRefType::Owned,
2574b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
25756eec8d6cSEnrico Granata 
25766eec8d6cSEnrico Granata   // if it fails, print the error but otherwise go on
2577b9c1b51eSKate Stone   if (PyErr_Occurred()) {
25786eec8d6cSEnrico Granata     PyErr_Print();
25796eec8d6cSEnrico Granata     PyErr_Clear();
25806eec8d6cSEnrico Granata   }
25816eec8d6cSEnrico Granata 
2582b9c1b51eSKate Stone   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
25836eec8d6cSEnrico Granata     PythonString py_string(PyRefType::Borrowed, py_return.get());
25846eec8d6cSEnrico Granata     llvm::StringRef return_data(py_string.GetString());
2585b9c1b51eSKate Stone     if (!return_data.empty()) {
25866eec8d6cSEnrico Granata       buffer.assign(return_data.data(), return_data.size());
25876eec8d6cSEnrico Granata       got_string = true;
25886eec8d6cSEnrico Granata     }
25896eec8d6cSEnrico Granata   }
25906eec8d6cSEnrico Granata 
25916eec8d6cSEnrico Granata   if (got_string)
25926eec8d6cSEnrico Granata     ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
25936eec8d6cSEnrico Granata 
25946eec8d6cSEnrico Granata   return ret_val;
25956eec8d6cSEnrico Granata }
25966eec8d6cSEnrico Granata 
259763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
259863dd5d25SJonas Devlieghere     const char *impl_function, Process *process, std::string &output,
259997206d57SZachary Turner     Status &error) {
26002c1f46dcSZachary Turner   bool ret_val;
2601b9c1b51eSKate Stone   if (!process) {
26022c1f46dcSZachary Turner     error.SetErrorString("no process");
26032c1f46dcSZachary Turner     return false;
26042c1f46dcSZachary Turner   }
2605b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
26062c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
26072c1f46dcSZachary Turner     return false;
26082c1f46dcSZachary Turner   }
260905495c5dSJonas Devlieghere 
26102c1f46dcSZachary Turner   {
26112c1f46dcSZachary Turner     ProcessSP process_sp(process->shared_from_this());
2612b9c1b51eSKate Stone     Locker py_lock(this,
2613b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
261405495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordProcess(
2615b9c1b51eSKate Stone         impl_function, m_dictionary_name.c_str(), process_sp, output);
26162c1f46dcSZachary Turner     if (!ret_val)
26172c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
26182c1f46dcSZachary Turner   }
26192c1f46dcSZachary Turner   return ret_val;
26202c1f46dcSZachary Turner }
26212c1f46dcSZachary Turner 
262263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
262363dd5d25SJonas Devlieghere     const char *impl_function, Thread *thread, std::string &output,
262497206d57SZachary Turner     Status &error) {
26252c1f46dcSZachary Turner   bool ret_val;
2626b9c1b51eSKate Stone   if (!thread) {
26272c1f46dcSZachary Turner     error.SetErrorString("no thread");
26282c1f46dcSZachary Turner     return false;
26292c1f46dcSZachary Turner   }
2630b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
26312c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
26322c1f46dcSZachary Turner     return false;
26332c1f46dcSZachary Turner   }
263405495c5dSJonas Devlieghere 
26352c1f46dcSZachary Turner   {
26362c1f46dcSZachary Turner     ThreadSP thread_sp(thread->shared_from_this());
2637b9c1b51eSKate Stone     Locker py_lock(this,
2638b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
263905495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordThread(
2640b9c1b51eSKate Stone         impl_function, m_dictionary_name.c_str(), thread_sp, output);
26412c1f46dcSZachary Turner     if (!ret_val)
26422c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
26432c1f46dcSZachary Turner   }
26442c1f46dcSZachary Turner   return ret_val;
26452c1f46dcSZachary Turner }
26462c1f46dcSZachary Turner 
264763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
264863dd5d25SJonas Devlieghere     const char *impl_function, Target *target, std::string &output,
264997206d57SZachary Turner     Status &error) {
26502c1f46dcSZachary Turner   bool ret_val;
2651b9c1b51eSKate Stone   if (!target) {
26522c1f46dcSZachary Turner     error.SetErrorString("no thread");
26532c1f46dcSZachary Turner     return false;
26542c1f46dcSZachary Turner   }
2655b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
26562c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
26572c1f46dcSZachary Turner     return false;
26582c1f46dcSZachary Turner   }
265905495c5dSJonas Devlieghere 
26602c1f46dcSZachary Turner   {
26612c1f46dcSZachary Turner     TargetSP target_sp(target->shared_from_this());
2662b9c1b51eSKate Stone     Locker py_lock(this,
2663b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
266405495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordTarget(
2665b9c1b51eSKate Stone         impl_function, m_dictionary_name.c_str(), target_sp, output);
26662c1f46dcSZachary Turner     if (!ret_val)
26672c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
26682c1f46dcSZachary Turner   }
26692c1f46dcSZachary Turner   return ret_val;
26702c1f46dcSZachary Turner }
26712c1f46dcSZachary Turner 
267263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
267363dd5d25SJonas Devlieghere     const char *impl_function, StackFrame *frame, std::string &output,
267497206d57SZachary Turner     Status &error) {
26752c1f46dcSZachary Turner   bool ret_val;
2676b9c1b51eSKate Stone   if (!frame) {
26772c1f46dcSZachary Turner     error.SetErrorString("no frame");
26782c1f46dcSZachary Turner     return false;
26792c1f46dcSZachary Turner   }
2680b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
26812c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
26822c1f46dcSZachary Turner     return false;
26832c1f46dcSZachary Turner   }
268405495c5dSJonas Devlieghere 
26852c1f46dcSZachary Turner   {
26862c1f46dcSZachary Turner     StackFrameSP frame_sp(frame->shared_from_this());
2687b9c1b51eSKate Stone     Locker py_lock(this,
2688b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
268905495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordFrame(
2690b9c1b51eSKate Stone         impl_function, m_dictionary_name.c_str(), frame_sp, output);
26912c1f46dcSZachary Turner     if (!ret_val)
26922c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
26932c1f46dcSZachary Turner   }
26942c1f46dcSZachary Turner   return ret_val;
26952c1f46dcSZachary Turner }
26962c1f46dcSZachary Turner 
269763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
269863dd5d25SJonas Devlieghere     const char *impl_function, ValueObject *value, std::string &output,
269997206d57SZachary Turner     Status &error) {
27002c1f46dcSZachary Turner   bool ret_val;
2701b9c1b51eSKate Stone   if (!value) {
27022c1f46dcSZachary Turner     error.SetErrorString("no value");
27032c1f46dcSZachary Turner     return false;
27042c1f46dcSZachary Turner   }
2705b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
27062c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
27072c1f46dcSZachary Turner     return false;
27082c1f46dcSZachary Turner   }
270905495c5dSJonas Devlieghere 
27102c1f46dcSZachary Turner   {
27112c1f46dcSZachary Turner     ValueObjectSP value_sp(value->GetSP());
2712b9c1b51eSKate Stone     Locker py_lock(this,
2713b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
271405495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordValue(
2715b9c1b51eSKate Stone         impl_function, m_dictionary_name.c_str(), value_sp, output);
27162c1f46dcSZachary Turner     if (!ret_val)
27172c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
27182c1f46dcSZachary Turner   }
27192c1f46dcSZachary Turner   return ret_val;
27202c1f46dcSZachary Turner }
27212c1f46dcSZachary Turner 
2722b9c1b51eSKate Stone uint64_t replace_all(std::string &str, const std::string &oldStr,
2723b9c1b51eSKate Stone                      const std::string &newStr) {
27242c1f46dcSZachary Turner   size_t pos = 0;
27252c1f46dcSZachary Turner   uint64_t matches = 0;
2726b9c1b51eSKate Stone   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
27272c1f46dcSZachary Turner     matches++;
27282c1f46dcSZachary Turner     str.replace(pos, oldStr.length(), newStr);
27292c1f46dcSZachary Turner     pos += newStr.length();
27302c1f46dcSZachary Turner   }
27312c1f46dcSZachary Turner   return matches;
27322c1f46dcSZachary Turner }
27332c1f46dcSZachary Turner 
273463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::LoadScriptingModule(
273515625112SJonas Devlieghere     const char *pathname, bool init_session, lldb_private::Status &error,
2736*00bb397bSJonas Devlieghere     StructuredData::ObjectSP *module_sp, FileSpec extra_search_dir) {
27373b33b416SJonas Devlieghere   namespace fs = llvm::sys::fs;
2738*00bb397bSJonas Devlieghere   namespace path = llvm::sys::path;
27393b33b416SJonas Devlieghere 
2740b9c1b51eSKate Stone   if (!pathname || !pathname[0]) {
27412c1f46dcSZachary Turner     error.SetErrorString("invalid pathname");
27422c1f46dcSZachary Turner     return false;
27432c1f46dcSZachary Turner   }
27442c1f46dcSZachary Turner 
27458d1fb843SJonas Devlieghere   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
27462c1f46dcSZachary Turner 
2747f9f36097SAdrian McCarthy   // Before executing Python code, lock the GIL.
274820b52c33SJonas Devlieghere   Locker py_lock(this,
274920b52c33SJonas Devlieghere                  Locker::AcquireLock |
27503b33b416SJonas Devlieghere                      (init_session ? Locker::InitSession : 0) | Locker::NoSTDIN,
2751b9c1b51eSKate Stone                  Locker::FreeAcquiredLock |
2752b9c1b51eSKate Stone                      (init_session ? Locker::TearDownSession : 0));
27532c1f46dcSZachary Turner 
2754*00bb397bSJonas Devlieghere   auto ExtendSysPath = [this](std::string directory) -> llvm::Error {
2755*00bb397bSJonas Devlieghere     if (directory.empty()) {
2756*00bb397bSJonas Devlieghere       return llvm::make_error<llvm::StringError>(
2757*00bb397bSJonas Devlieghere           "invalid directory name", llvm::inconvertibleErrorCode());
275842a9da7bSStefan Granitz     }
275942a9da7bSStefan Granitz 
2760f9f36097SAdrian McCarthy     replace_all(directory, "\\", "\\\\");
27612c1f46dcSZachary Turner     replace_all(directory, "'", "\\'");
27622c1f46dcSZachary Turner 
2763*00bb397bSJonas Devlieghere     // Make sure that Python has "directory" in the search path.
27642c1f46dcSZachary Turner     StreamString command_stream;
2765b9c1b51eSKate Stone     command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
2766b9c1b51eSKate Stone                           "sys.path.insert(1,'%s');\n\n",
2767b9c1b51eSKate Stone                           directory.c_str(), directory.c_str());
2768b9c1b51eSKate Stone     bool syspath_retval =
2769b9c1b51eSKate Stone         ExecuteMultipleLines(command_stream.GetData(),
2770b9c1b51eSKate Stone                              ScriptInterpreter::ExecuteScriptOptions()
2771b9c1b51eSKate Stone                                  .SetEnableIO(false)
2772b9c1b51eSKate Stone                                  .SetSetLLDBGlobals(false))
2773b9c1b51eSKate Stone             .Success();
2774b9c1b51eSKate Stone     if (!syspath_retval) {
2775*00bb397bSJonas Devlieghere       return llvm::make_error<llvm::StringError>(
2776*00bb397bSJonas Devlieghere           "Python sys.path handling failed", llvm::inconvertibleErrorCode());
27772c1f46dcSZachary Turner     }
27782c1f46dcSZachary Turner 
2779*00bb397bSJonas Devlieghere     return llvm::Error::success();
2780*00bb397bSJonas Devlieghere   };
2781*00bb397bSJonas Devlieghere 
2782*00bb397bSJonas Devlieghere   std::string module_name(pathname);
2783*00bb397bSJonas Devlieghere 
2784*00bb397bSJonas Devlieghere   if (extra_search_dir) {
2785*00bb397bSJonas Devlieghere     if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2786*00bb397bSJonas Devlieghere       error = std::move(e);
2787*00bb397bSJonas Devlieghere       return false;
2788*00bb397bSJonas Devlieghere     }
2789*00bb397bSJonas Devlieghere   } else {
2790*00bb397bSJonas Devlieghere     FileSpec module_file(pathname);
2791*00bb397bSJonas Devlieghere     FileSystem::Instance().Resolve(module_file);
2792*00bb397bSJonas Devlieghere     FileSystem::Instance().Collect(module_file);
2793*00bb397bSJonas Devlieghere 
2794*00bb397bSJonas Devlieghere     fs::file_status st;
2795*00bb397bSJonas Devlieghere     std::error_code ec = status(module_file.GetPath(), st);
2796*00bb397bSJonas Devlieghere 
2797*00bb397bSJonas Devlieghere     if (ec || st.type() == fs::file_type::status_error ||
2798*00bb397bSJonas Devlieghere         st.type() == fs::file_type::type_unknown ||
2799*00bb397bSJonas Devlieghere         st.type() == fs::file_type::file_not_found) {
2800*00bb397bSJonas Devlieghere       // if not a valid file of any sort, check if it might be a filename still
2801*00bb397bSJonas Devlieghere       // dot can't be used but / and \ can, and if either is found, reject
2802*00bb397bSJonas Devlieghere       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2803*00bb397bSJonas Devlieghere         error.SetErrorString("invalid pathname");
2804*00bb397bSJonas Devlieghere         return false;
2805*00bb397bSJonas Devlieghere       }
2806*00bb397bSJonas Devlieghere       // Not a filename, probably a package of some sort, let it go through.
2807*00bb397bSJonas Devlieghere     } else if (is_directory(st) || is_regular_file(st)) {
2808*00bb397bSJonas Devlieghere       if (module_file.GetDirectory().IsEmpty()) {
2809*00bb397bSJonas Devlieghere         error.SetErrorString("invalid directory name");
2810*00bb397bSJonas Devlieghere         return false;
2811*00bb397bSJonas Devlieghere       }
2812*00bb397bSJonas Devlieghere       if (llvm::Error e =
2813*00bb397bSJonas Devlieghere               ExtendSysPath(module_file.GetDirectory().GetCString())) {
2814*00bb397bSJonas Devlieghere         error = std::move(e);
2815*00bb397bSJonas Devlieghere         return false;
2816*00bb397bSJonas Devlieghere       }
2817*00bb397bSJonas Devlieghere       module_name = module_file.GetFilename().GetCString();
2818b9c1b51eSKate Stone     } else {
28192c1f46dcSZachary Turner       error.SetErrorString("no known way to import this module specification");
28202c1f46dcSZachary Turner       return false;
28212c1f46dcSZachary Turner     }
2822*00bb397bSJonas Devlieghere   }
28232c1f46dcSZachary Turner 
28241197ee35SJonas Devlieghere   // Strip .py or .pyc extension
2825*00bb397bSJonas Devlieghere   llvm::StringRef extension = llvm::sys::path::extension(module_name);
28261197ee35SJonas Devlieghere   if (!extension.empty()) {
28271197ee35SJonas Devlieghere     if (extension == ".py")
2828*00bb397bSJonas Devlieghere       module_name.resize(module_name.length() - 3);
28291197ee35SJonas Devlieghere     else if (extension == ".pyc")
2830*00bb397bSJonas Devlieghere       module_name.resize(module_name.length() - 4);
28311197ee35SJonas Devlieghere   }
28321197ee35SJonas Devlieghere 
28332c1f46dcSZachary Turner   // check if the module is already import-ed
2834*00bb397bSJonas Devlieghere   StreamString command_stream;
28352c1f46dcSZachary Turner   command_stream.Clear();
2836*00bb397bSJonas Devlieghere   command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
28372c1f46dcSZachary Turner   bool does_contain = false;
283805097246SAdrian Prantl   // this call will succeed if the module was ever imported in any Debugger
283905097246SAdrian Prantl   // in the lifetime of the process in which this LLDB framework is living
2840b9c1b51eSKate Stone   bool was_imported_globally =
2841b9c1b51eSKate Stone       (ExecuteOneLineWithReturn(
2842b9c1b51eSKate Stone            command_stream.GetData(),
284363dd5d25SJonas Devlieghere            ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain,
2844b9c1b51eSKate Stone            ScriptInterpreter::ExecuteScriptOptions()
2845b9c1b51eSKate Stone                .SetEnableIO(false)
2846b9c1b51eSKate Stone                .SetSetLLDBGlobals(false)) &&
2847b9c1b51eSKate Stone        does_contain);
2848b9c1b51eSKate Stone   // this call will fail if the module was not imported in this Debugger
2849b9c1b51eSKate Stone   // before
28502c1f46dcSZachary Turner   command_stream.Clear();
2851*00bb397bSJonas Devlieghere   command_stream.Printf("sys.getrefcount(%s)", module_name.c_str());
2852b9c1b51eSKate Stone   bool was_imported_locally = GetSessionDictionary()
2853*00bb397bSJonas Devlieghere                                   .GetItemForKey(PythonString(module_name))
2854b9c1b51eSKate Stone                                   .IsAllocated();
28552c1f46dcSZachary Turner 
28562c1f46dcSZachary Turner   bool was_imported = (was_imported_globally || was_imported_locally);
28572c1f46dcSZachary Turner 
28582c1f46dcSZachary Turner   // now actually do the import
28592c1f46dcSZachary Turner   command_stream.Clear();
28602c1f46dcSZachary Turner 
2861b9c1b51eSKate Stone   if (was_imported) {
28622c1f46dcSZachary Turner     if (!was_imported_locally)
2863*00bb397bSJonas Devlieghere       command_stream.Printf("import %s ; reload_module(%s)",
2864*00bb397bSJonas Devlieghere                             module_name.c_str(), module_name.c_str());
28652c1f46dcSZachary Turner     else
2866*00bb397bSJonas Devlieghere       command_stream.Printf("reload_module(%s)", module_name.c_str());
2867b9c1b51eSKate Stone   } else
2868*00bb397bSJonas Devlieghere     command_stream.Printf("import %s", module_name.c_str());
28692c1f46dcSZachary Turner 
2870b9c1b51eSKate Stone   error = ExecuteMultipleLines(command_stream.GetData(),
2871b9c1b51eSKate Stone                                ScriptInterpreter::ExecuteScriptOptions()
2872b9c1b51eSKate Stone                                    .SetEnableIO(false)
2873b9c1b51eSKate Stone                                    .SetSetLLDBGlobals(false));
28742c1f46dcSZachary Turner   if (error.Fail())
28752c1f46dcSZachary Turner     return false;
28762c1f46dcSZachary Turner 
28772c1f46dcSZachary Turner   // if we are here, everything worked
28782c1f46dcSZachary Turner   // call __lldb_init_module(debugger,dict)
2879*00bb397bSJonas Devlieghere   if (!LLDBSwigPythonCallModuleInit(module_name.c_str(),
2880*00bb397bSJonas Devlieghere                                     m_dictionary_name.c_str(), debugger_sp)) {
28812c1f46dcSZachary Turner     error.SetErrorString("calling __lldb_init_module failed");
28822c1f46dcSZachary Turner     return false;
28832c1f46dcSZachary Turner   }
28842c1f46dcSZachary Turner 
2885b9c1b51eSKate Stone   if (module_sp) {
28862c1f46dcSZachary Turner     // everything went just great, now set the module object
28872c1f46dcSZachary Turner     command_stream.Clear();
2888*00bb397bSJonas Devlieghere     command_stream.Printf("%s", module_name.c_str());
28892c1f46dcSZachary Turner     void *module_pyobj = nullptr;
2890b9c1b51eSKate Stone     if (ExecuteOneLineWithReturn(
2891b9c1b51eSKate Stone             command_stream.GetData(),
28923b33b416SJonas Devlieghere             ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj) &&
2893b9c1b51eSKate Stone         module_pyobj)
2894796ac80bSJonas Devlieghere       *module_sp = std::make_shared<StructuredPythonObject>(module_pyobj);
28952c1f46dcSZachary Turner   }
28962c1f46dcSZachary Turner 
28972c1f46dcSZachary Turner   return true;
28982c1f46dcSZachary Turner }
28992c1f46dcSZachary Turner 
290063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
29012c1f46dcSZachary Turner   if (!word || !word[0])
29022c1f46dcSZachary Turner     return false;
29032c1f46dcSZachary Turner 
29042c1f46dcSZachary Turner   llvm::StringRef word_sr(word);
29052c1f46dcSZachary Turner 
290605097246SAdrian Prantl   // filter out a few characters that would just confuse us and that are
290705097246SAdrian Prantl   // clearly not keyword material anyway
290810b113e8SJonas Devlieghere   if (word_sr.find('"') != llvm::StringRef::npos ||
290910b113e8SJonas Devlieghere       word_sr.find('\'') != llvm::StringRef::npos)
29102c1f46dcSZachary Turner     return false;
29112c1f46dcSZachary Turner 
29122c1f46dcSZachary Turner   StreamString command_stream;
29132c1f46dcSZachary Turner   command_stream.Printf("keyword.iskeyword('%s')", word);
29142c1f46dcSZachary Turner   bool result;
29152c1f46dcSZachary Turner   ExecuteScriptOptions options;
29162c1f46dcSZachary Turner   options.SetEnableIO(false);
29172c1f46dcSZachary Turner   options.SetMaskoutErrors(true);
29182c1f46dcSZachary Turner   options.SetSetLLDBGlobals(false);
2919b9c1b51eSKate Stone   if (ExecuteOneLineWithReturn(command_stream.GetData(),
2920b9c1b51eSKate Stone                                ScriptInterpreter::eScriptReturnTypeBool,
2921b9c1b51eSKate Stone                                &result, options))
29222c1f46dcSZachary Turner     return result;
29232c1f46dcSZachary Turner   return false;
29242c1f46dcSZachary Turner }
29252c1f46dcSZachary Turner 
292663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2927b9c1b51eSKate Stone     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2928b9c1b51eSKate Stone     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2929b9c1b51eSKate Stone       m_old_asynch(debugger_sp->GetAsyncExecution()) {
29302c1f46dcSZachary Turner   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
29312c1f46dcSZachary Turner     m_debugger_sp->SetAsyncExecution(false);
29322c1f46dcSZachary Turner   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
29332c1f46dcSZachary Turner     m_debugger_sp->SetAsyncExecution(true);
29342c1f46dcSZachary Turner }
29352c1f46dcSZachary Turner 
293663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
29372c1f46dcSZachary Turner   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
29382c1f46dcSZachary Turner     m_debugger_sp->SetAsyncExecution(m_old_asynch);
29392c1f46dcSZachary Turner }
29402c1f46dcSZachary Turner 
294163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
29424d51a902SRaphael Isemann     const char *impl_function, llvm::StringRef args,
29432c1f46dcSZachary Turner     ScriptedCommandSynchronicity synchronicity,
294497206d57SZachary Turner     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2945b9c1b51eSKate Stone     const lldb_private::ExecutionContext &exe_ctx) {
2946b9c1b51eSKate Stone   if (!impl_function) {
29472c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
29482c1f46dcSZachary Turner     return false;
29492c1f46dcSZachary Turner   }
29502c1f46dcSZachary Turner 
29518d1fb843SJonas Devlieghere   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
29522c1f46dcSZachary Turner   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
29532c1f46dcSZachary Turner 
2954b9c1b51eSKate Stone   if (!debugger_sp.get()) {
29552c1f46dcSZachary Turner     error.SetErrorString("invalid Debugger pointer");
29562c1f46dcSZachary Turner     return false;
29572c1f46dcSZachary Turner   }
29582c1f46dcSZachary Turner 
29592c1f46dcSZachary Turner   bool ret_val = false;
29602c1f46dcSZachary Turner 
29612c1f46dcSZachary Turner   std::string err_msg;
29622c1f46dcSZachary Turner 
29632c1f46dcSZachary Turner   {
29642c1f46dcSZachary Turner     Locker py_lock(this,
2965b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession |
2966b9c1b51eSKate Stone                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
29672c1f46dcSZachary Turner                    Locker::FreeLock | Locker::TearDownSession);
29682c1f46dcSZachary Turner 
2969b9c1b51eSKate Stone     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
29702c1f46dcSZachary Turner 
29714d51a902SRaphael Isemann     std::string args_str = args.str();
297205495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCallCommand(
297305495c5dSJonas Devlieghere         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
297405495c5dSJonas Devlieghere         cmd_retobj, exe_ctx_ref_sp);
29752c1f46dcSZachary Turner   }
29762c1f46dcSZachary Turner 
29772c1f46dcSZachary Turner   if (!ret_val)
29782c1f46dcSZachary Turner     error.SetErrorString("unable to execute script function");
29792c1f46dcSZachary Turner   else
29802c1f46dcSZachary Turner     error.Clear();
29812c1f46dcSZachary Turner 
29822c1f46dcSZachary Turner   return ret_val;
29832c1f46dcSZachary Turner }
29842c1f46dcSZachary Turner 
298563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
29864d51a902SRaphael Isemann     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
29872c1f46dcSZachary Turner     ScriptedCommandSynchronicity synchronicity,
298897206d57SZachary Turner     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2989b9c1b51eSKate Stone     const lldb_private::ExecutionContext &exe_ctx) {
2990b9c1b51eSKate Stone   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
29912c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
29922c1f46dcSZachary Turner     return false;
29932c1f46dcSZachary Turner   }
29942c1f46dcSZachary Turner 
29958d1fb843SJonas Devlieghere   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
29962c1f46dcSZachary Turner   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
29972c1f46dcSZachary Turner 
2998b9c1b51eSKate Stone   if (!debugger_sp.get()) {
29992c1f46dcSZachary Turner     error.SetErrorString("invalid Debugger pointer");
30002c1f46dcSZachary Turner     return false;
30012c1f46dcSZachary Turner   }
30022c1f46dcSZachary Turner 
30032c1f46dcSZachary Turner   bool ret_val = false;
30042c1f46dcSZachary Turner 
30052c1f46dcSZachary Turner   std::string err_msg;
30062c1f46dcSZachary Turner 
30072c1f46dcSZachary Turner   {
30082c1f46dcSZachary Turner     Locker py_lock(this,
3009b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession |
3010b9c1b51eSKate Stone                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
30112c1f46dcSZachary Turner                    Locker::FreeLock | Locker::TearDownSession);
30122c1f46dcSZachary Turner 
3013b9c1b51eSKate Stone     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
30142c1f46dcSZachary Turner 
30154d51a902SRaphael Isemann     std::string args_str = args.str();
301605495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCallCommandObject(impl_obj_sp->GetValue(),
301705495c5dSJonas Devlieghere                                               debugger_sp, args_str.c_str(),
301805495c5dSJonas Devlieghere                                               cmd_retobj, exe_ctx_ref_sp);
30192c1f46dcSZachary Turner   }
30202c1f46dcSZachary Turner 
30212c1f46dcSZachary Turner   if (!ret_val)
30222c1f46dcSZachary Turner     error.SetErrorString("unable to execute script function");
30232c1f46dcSZachary Turner   else
30242c1f46dcSZachary Turner     error.Clear();
30252c1f46dcSZachary Turner 
30262c1f46dcSZachary Turner   return ret_val;
30272c1f46dcSZachary Turner }
30282c1f46dcSZachary Turner 
302993571c3cSJonas Devlieghere /// In Python, a special attribute __doc__ contains the docstring for an object
303093571c3cSJonas Devlieghere /// (function, method, class, ...) if any is defined Otherwise, the attribute's
303193571c3cSJonas Devlieghere /// value is None.
303263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
3033b9c1b51eSKate Stone                                                           std::string &dest) {
30342c1f46dcSZachary Turner   dest.clear();
303593571c3cSJonas Devlieghere 
30362c1f46dcSZachary Turner   if (!item || !*item)
30372c1f46dcSZachary Turner     return false;
303893571c3cSJonas Devlieghere 
30392c1f46dcSZachary Turner   std::string command(item);
30402c1f46dcSZachary Turner   command += ".__doc__";
30412c1f46dcSZachary Turner 
304293571c3cSJonas Devlieghere   // Python is going to point this to valid data if ExecuteOneLineWithReturn
304393571c3cSJonas Devlieghere   // returns successfully.
304493571c3cSJonas Devlieghere   char *result_ptr = nullptr;
30452c1f46dcSZachary Turner 
3046b9c1b51eSKate Stone   if (ExecuteOneLineWithReturn(
304793571c3cSJonas Devlieghere           command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
30482c1f46dcSZachary Turner           &result_ptr,
3049b9c1b51eSKate Stone           ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false))) {
30502c1f46dcSZachary Turner     if (result_ptr)
30512c1f46dcSZachary Turner       dest.assign(result_ptr);
30522c1f46dcSZachary Turner     return true;
30532c1f46dcSZachary Turner   }
305493571c3cSJonas Devlieghere 
305593571c3cSJonas Devlieghere   StreamString str_stream;
305693571c3cSJonas Devlieghere   str_stream << "Function " << item
305793571c3cSJonas Devlieghere              << " was not found. Containing module might be missing.";
305893571c3cSJonas Devlieghere   dest = std::string(str_stream.GetString());
305993571c3cSJonas Devlieghere 
306093571c3cSJonas Devlieghere   return false;
30612c1f46dcSZachary Turner }
30622c1f46dcSZachary Turner 
306363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
3064b9c1b51eSKate Stone     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
30652c1f46dcSZachary Turner   dest.clear();
30662c1f46dcSZachary Turner 
3067b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
30682c1f46dcSZachary Turner 
30692c1f46dcSZachary Turner   static char callee_name[] = "get_short_help";
30702c1f46dcSZachary Turner 
30712c1f46dcSZachary Turner   if (!cmd_obj_sp)
30722c1f46dcSZachary Turner     return false;
30732c1f46dcSZachary Turner 
3074b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
3075b9c1b51eSKate Stone                            (PyObject *)cmd_obj_sp->GetValue());
30762c1f46dcSZachary Turner 
3077f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
30782c1f46dcSZachary Turner     return false;
30792c1f46dcSZachary Turner 
3080b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
3081b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
30822c1f46dcSZachary Turner 
30832c1f46dcSZachary Turner   if (PyErr_Occurred())
30842c1f46dcSZachary Turner     PyErr_Clear();
30852c1f46dcSZachary Turner 
3086f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
30872c1f46dcSZachary Turner     return false;
30882c1f46dcSZachary Turner 
3089b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
30902c1f46dcSZachary Turner     if (PyErr_Occurred())
30912c1f46dcSZachary Turner       PyErr_Clear();
30922c1f46dcSZachary Turner     return false;
30932c1f46dcSZachary Turner   }
30942c1f46dcSZachary Turner 
30952c1f46dcSZachary Turner   if (PyErr_Occurred())
30962c1f46dcSZachary Turner     PyErr_Clear();
30972c1f46dcSZachary Turner 
309893571c3cSJonas Devlieghere   // Right now we know this function exists and is callable.
3099b9c1b51eSKate Stone   PythonObject py_return(
3100b9c1b51eSKate Stone       PyRefType::Owned,
3101b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
31022c1f46dcSZachary Turner 
310393571c3cSJonas Devlieghere   // If it fails, print the error but otherwise go on.
3104b9c1b51eSKate Stone   if (PyErr_Occurred()) {
31052c1f46dcSZachary Turner     PyErr_Print();
31062c1f46dcSZachary Turner     PyErr_Clear();
31072c1f46dcSZachary Turner   }
31082c1f46dcSZachary Turner 
3109b9c1b51eSKate Stone   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3110f8b22f8fSZachary Turner     PythonString py_string(PyRefType::Borrowed, py_return.get());
311122c8efcdSZachary Turner     llvm::StringRef return_data(py_string.GetString());
311222c8efcdSZachary Turner     dest.assign(return_data.data(), return_data.size());
311393571c3cSJonas Devlieghere     return true;
31142c1f46dcSZachary Turner   }
311593571c3cSJonas Devlieghere 
311693571c3cSJonas Devlieghere   return false;
31172c1f46dcSZachary Turner }
31182c1f46dcSZachary Turner 
311963dd5d25SJonas Devlieghere uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
3120b9c1b51eSKate Stone     StructuredData::GenericSP cmd_obj_sp) {
31212c1f46dcSZachary Turner   uint32_t result = 0;
31222c1f46dcSZachary Turner 
3123b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
31242c1f46dcSZachary Turner 
31252c1f46dcSZachary Turner   static char callee_name[] = "get_flags";
31262c1f46dcSZachary Turner 
31272c1f46dcSZachary Turner   if (!cmd_obj_sp)
31282c1f46dcSZachary Turner     return result;
31292c1f46dcSZachary Turner 
3130b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
3131b9c1b51eSKate Stone                            (PyObject *)cmd_obj_sp->GetValue());
31322c1f46dcSZachary Turner 
3133f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
31342c1f46dcSZachary Turner     return result;
31352c1f46dcSZachary Turner 
3136b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
3137b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
31382c1f46dcSZachary Turner 
31392c1f46dcSZachary Turner   if (PyErr_Occurred())
31402c1f46dcSZachary Turner     PyErr_Clear();
31412c1f46dcSZachary Turner 
3142f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
31432c1f46dcSZachary Turner     return result;
31442c1f46dcSZachary Turner 
3145b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
31462c1f46dcSZachary Turner     if (PyErr_Occurred())
31472c1f46dcSZachary Turner       PyErr_Clear();
31482c1f46dcSZachary Turner     return result;
31492c1f46dcSZachary Turner   }
31502c1f46dcSZachary Turner 
31512c1f46dcSZachary Turner   if (PyErr_Occurred())
31522c1f46dcSZachary Turner     PyErr_Clear();
31532c1f46dcSZachary Turner 
315452712d3fSLawrence D'Anna   long long py_return = unwrapOrSetPythonException(
315552712d3fSLawrence D'Anna       As<long long>(implementor.CallMethod(callee_name)));
31562c1f46dcSZachary Turner 
31572c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
3158b9c1b51eSKate Stone   if (PyErr_Occurred()) {
31592c1f46dcSZachary Turner     PyErr_Print();
31602c1f46dcSZachary Turner     PyErr_Clear();
316152712d3fSLawrence D'Anna   } else {
316252712d3fSLawrence D'Anna     result = py_return;
31632c1f46dcSZachary Turner   }
31642c1f46dcSZachary Turner 
31652c1f46dcSZachary Turner   return result;
31662c1f46dcSZachary Turner }
31672c1f46dcSZachary Turner 
316863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3169b9c1b51eSKate Stone     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
31702c1f46dcSZachary Turner   bool got_string = false;
31712c1f46dcSZachary Turner   dest.clear();
31722c1f46dcSZachary Turner 
3173b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
31742c1f46dcSZachary Turner 
31752c1f46dcSZachary Turner   static char callee_name[] = "get_long_help";
31762c1f46dcSZachary Turner 
31772c1f46dcSZachary Turner   if (!cmd_obj_sp)
31782c1f46dcSZachary Turner     return false;
31792c1f46dcSZachary Turner 
3180b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
3181b9c1b51eSKate Stone                            (PyObject *)cmd_obj_sp->GetValue());
31822c1f46dcSZachary Turner 
3183f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
31842c1f46dcSZachary Turner     return false;
31852c1f46dcSZachary Turner 
3186b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
3187b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
31882c1f46dcSZachary Turner 
31892c1f46dcSZachary Turner   if (PyErr_Occurred())
31902c1f46dcSZachary Turner     PyErr_Clear();
31912c1f46dcSZachary Turner 
3192f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
31932c1f46dcSZachary Turner     return false;
31942c1f46dcSZachary Turner 
3195b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
31962c1f46dcSZachary Turner     if (PyErr_Occurred())
31972c1f46dcSZachary Turner       PyErr_Clear();
31982c1f46dcSZachary Turner 
31992c1f46dcSZachary Turner     return false;
32002c1f46dcSZachary Turner   }
32012c1f46dcSZachary Turner 
32022c1f46dcSZachary Turner   if (PyErr_Occurred())
32032c1f46dcSZachary Turner     PyErr_Clear();
32042c1f46dcSZachary Turner 
32052c1f46dcSZachary Turner   // right now we know this function exists and is callable..
3206b9c1b51eSKate Stone   PythonObject py_return(
3207b9c1b51eSKate Stone       PyRefType::Owned,
3208b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
32092c1f46dcSZachary Turner 
32102c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
3211b9c1b51eSKate Stone   if (PyErr_Occurred()) {
32122c1f46dcSZachary Turner     PyErr_Print();
32132c1f46dcSZachary Turner     PyErr_Clear();
32142c1f46dcSZachary Turner   }
32152c1f46dcSZachary Turner 
3216b9c1b51eSKate Stone   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3217f8b22f8fSZachary Turner     PythonString str(PyRefType::Borrowed, py_return.get());
321822c8efcdSZachary Turner     llvm::StringRef str_data(str.GetString());
321922c8efcdSZachary Turner     dest.assign(str_data.data(), str_data.size());
32202c1f46dcSZachary Turner     got_string = true;
32212c1f46dcSZachary Turner   }
32222c1f46dcSZachary Turner 
32232c1f46dcSZachary Turner   return got_string;
32242c1f46dcSZachary Turner }
32252c1f46dcSZachary Turner 
32262c1f46dcSZachary Turner std::unique_ptr<ScriptInterpreterLocker>
322763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3228b9c1b51eSKate Stone   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3229b9c1b51eSKate Stone       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
32302c1f46dcSZachary Turner       Locker::FreeLock | Locker::TearDownSession));
32312c1f46dcSZachary Turner   return py_lock;
32322c1f46dcSZachary Turner }
32332c1f46dcSZachary Turner 
323463dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::InitializePrivate() {
323515d1b4e2SEnrico Granata   if (g_initialized)
323615d1b4e2SEnrico Granata     return;
323715d1b4e2SEnrico Granata 
32382c1f46dcSZachary Turner   g_initialized = true;
32392c1f46dcSZachary Turner 
3240f9d16476SPavel Labath   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
3241f9d16476SPavel Labath   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
32422c1f46dcSZachary Turner 
3243b9c1b51eSKate Stone   // RAII-based initialization which correctly handles multiple-initialization,
324405097246SAdrian Prantl   // version- specific differences among Python 2 and Python 3, and saving and
324505097246SAdrian Prantl   // restoring various other pieces of state that can get mucked with during
324605097246SAdrian Prantl   // initialization.
3247079fe48aSZachary Turner   InitializePythonRAII initialize_guard;
32482c1f46dcSZachary Turner 
324905495c5dSJonas Devlieghere   LLDBSwigPyInit();
32502c1f46dcSZachary Turner 
3251b9c1b51eSKate Stone   // Update the path python uses to search for modules to include the current
3252b9c1b51eSKate Stone   // directory.
32532c1f46dcSZachary Turner 
32542c1f46dcSZachary Turner   PyRun_SimpleString("import sys");
32552c1f46dcSZachary Turner   AddToSysPath(AddLocation::End, ".");
32562c1f46dcSZachary Turner 
3257b9c1b51eSKate Stone   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
325805097246SAdrian Prantl   // that use a backslash as the path separator, this will result in executing
325905097246SAdrian Prantl   // python code containing paths with unescaped backslashes.  But Python also
326005097246SAdrian Prantl   // accepts forward slashes, so to make life easier we just use that.
32612df331b0SPavel Labath   if (FileSpec file_spec = GetPythonDir())
32622c1f46dcSZachary Turner     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
326360f028ffSPavel Labath   if (FileSpec file_spec = HostInfo::GetShlibDir())
32642c1f46dcSZachary Turner     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
32652c1f46dcSZachary Turner 
3266b9c1b51eSKate Stone   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3267b9c1b51eSKate Stone                      "lldb.embedded_interpreter; from "
3268b9c1b51eSKate Stone                      "lldb.embedded_interpreter import run_python_interpreter; "
3269b9c1b51eSKate Stone                      "from lldb.embedded_interpreter import run_one_line");
32702c1f46dcSZachary Turner }
32712c1f46dcSZachary Turner 
327263dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3273b9c1b51eSKate Stone                                                std::string path) {
32742c1f46dcSZachary Turner   std::string path_copy;
32752c1f46dcSZachary Turner 
32762c1f46dcSZachary Turner   std::string statement;
3277b9c1b51eSKate Stone   if (location == AddLocation::Beginning) {
32782c1f46dcSZachary Turner     statement.assign("sys.path.insert(0,\"");
32792c1f46dcSZachary Turner     statement.append(path);
32802c1f46dcSZachary Turner     statement.append("\")");
3281b9c1b51eSKate Stone   } else {
32822c1f46dcSZachary Turner     statement.assign("sys.path.append(\"");
32832c1f46dcSZachary Turner     statement.append(path);
32842c1f46dcSZachary Turner     statement.append("\")");
32852c1f46dcSZachary Turner   }
32862c1f46dcSZachary Turner   PyRun_SimpleString(statement.c_str());
32872c1f46dcSZachary Turner }
32882c1f46dcSZachary Turner 
3289bcadb5a3SPavel Labath // We are intentionally NOT calling Py_Finalize here (this would be the logical
3290bcadb5a3SPavel Labath // place to call it).  Calling Py_Finalize here causes test suite runs to seg
3291bcadb5a3SPavel Labath // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
3292bcadb5a3SPavel Labath // be called 'at_exit'.  When the test suite Python harness finishes up, it
3293bcadb5a3SPavel Labath // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3294bcadb5a3SPavel Labath // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3295bcadb5a3SPavel Labath // which calls ScriptInterpreter::Terminate, which calls
329663dd5d25SJonas Devlieghere // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
329763dd5d25SJonas Devlieghere // end up with Py_Finalize being called from within Py_Finalize, which results
329863dd5d25SJonas Devlieghere // in a seg fault. Since this function only gets called when lldb is shutting
329963dd5d25SJonas Devlieghere // down and going away anyway, the fact that we don't actually call Py_Finalize
3300bcadb5a3SPavel Labath // should not cause any problems (everything should shut down/go away anyway
3301bcadb5a3SPavel Labath // when the process exits).
3302bcadb5a3SPavel Labath //
330363dd5d25SJonas Devlieghere // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3304d68983e3SPavel Labath 
33054e26cf2cSJonas Devlieghere #endif
3306