180814287SRaphael Isemann //===-- ScriptInterpreterPython.cpp ---------------------------------------===//
22c1f46dcSZachary Turner //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
62c1f46dcSZachary Turner //
72c1f46dcSZachary Turner //===----------------------------------------------------------------------===//
82c1f46dcSZachary Turner 
959998b7bSJonas Devlieghere #include "lldb/Host/Config.h"
10d055e3a0SPedro Tammela #include "lldb/lldb-enumerations.h"
11d68983e3SPavel Labath 
124e26cf2cSJonas Devlieghere #if LLDB_ENABLE_PYTHON
13d68983e3SPavel Labath 
1441de9a97SKate Stone // LLDB Python header must be included first
152c1f46dcSZachary Turner #include "lldb-python.h"
1641de9a97SKate Stone 
172c1f46dcSZachary Turner #include "PythonDataObjects.h"
189357b5d0Sserge-sans-paille #include "PythonReadline.h"
19*1f6a57c1SMed Ismail Bennani #include "SWIGPythonBridge.h"
2063dd5d25SJonas Devlieghere #include "ScriptInterpreterPythonImpl.h"
21*1f6a57c1SMed Ismail Bennani #include "ScriptedProcessPythonInterface.h"
22*1f6a57c1SMed Ismail Bennani 
23*1f6a57c1SMed Ismail Bennani #include "lldb/API/SBError.h"
2441ae8e74SKuba Mracek #include "lldb/API/SBFrame.h"
2563dd5d25SJonas Devlieghere #include "lldb/API/SBValue.h"
262c1f46dcSZachary Turner #include "lldb/Breakpoint/StoppointCallbackContext.h"
272c1f46dcSZachary Turner #include "lldb/Breakpoint/WatchpointOptions.h"
282c1f46dcSZachary Turner #include "lldb/Core/Communication.h"
292c1f46dcSZachary Turner #include "lldb/Core/Debugger.h"
302c1f46dcSZachary Turner #include "lldb/Core/PluginManager.h"
312c1f46dcSZachary Turner #include "lldb/Core/ValueObject.h"
322c1f46dcSZachary Turner #include "lldb/DataFormatters/TypeSummary.h"
334eff2d31SZachary Turner #include "lldb/Host/FileSystem.h"
342c1f46dcSZachary Turner #include "lldb/Host/HostInfo.h"
352c1f46dcSZachary Turner #include "lldb/Host/Pipe.h"
362c1f46dcSZachary Turner #include "lldb/Interpreter/CommandInterpreter.h"
372c1f46dcSZachary Turner #include "lldb/Interpreter/CommandReturnObject.h"
382c1f46dcSZachary Turner #include "lldb/Target/Thread.h"
392c1f46dcSZachary Turner #include "lldb/Target/ThreadPlan.h"
405861234eSJonas Devlieghere #include "lldb/Utility/ReproducerInstrumentation.h"
4138d0632eSPavel Labath #include "lldb/Utility/Timer.h"
4222c8efcdSZachary Turner #include "llvm/ADT/STLExtras.h"
43b9c1b51eSKate Stone #include "llvm/ADT/StringRef.h"
44d79273c9SJonas Devlieghere #include "llvm/Support/Error.h"
457d86ee5aSZachary Turner #include "llvm/Support/FileSystem.h"
462fce1137SLawrence D'Anna #include "llvm/Support/FormatAdapters.h"
472c1f46dcSZachary Turner 
489a6c7572SJonas Devlieghere #include <memory>
499a6c7572SJonas Devlieghere #include <mutex>
509a6c7572SJonas Devlieghere #include <stdio.h>
519a6c7572SJonas Devlieghere #include <stdlib.h>
529a6c7572SJonas Devlieghere #include <string>
539a6c7572SJonas Devlieghere 
542c1f46dcSZachary Turner using namespace lldb;
552c1f46dcSZachary Turner using namespace lldb_private;
56722b6189SLawrence D'Anna using namespace lldb_private::python;
5704edd189SLawrence D'Anna using llvm::Expected;
582c1f46dcSZachary Turner 
59bba9ba8dSJonas Devlieghere LLDB_PLUGIN_DEFINE(ScriptInterpreterPython)
60fbb4d1e4SJonas Devlieghere 
61b01b1087SJonas Devlieghere // Defined in the SWIG source file
62b01b1087SJonas Devlieghere #if PY_MAJOR_VERSION >= 3
63b01b1087SJonas Devlieghere extern "C" PyObject *PyInit__lldb(void);
64b01b1087SJonas Devlieghere 
65b01b1087SJonas Devlieghere #define LLDBSwigPyInit PyInit__lldb
66b01b1087SJonas Devlieghere 
67b01b1087SJonas Devlieghere #else
68b01b1087SJonas Devlieghere extern "C" void init_lldb(void);
69b01b1087SJonas Devlieghere 
70b01b1087SJonas Devlieghere #define LLDBSwigPyInit init_lldb
71b01b1087SJonas Devlieghere #endif
72b01b1087SJonas Devlieghere 
7305495c5dSJonas Devlieghere // These prototypes are the Pythonic implementations of the required callbacks.
7405495c5dSJonas Devlieghere // Although these are scripting-language specific, their definition depends on
7505495c5dSJonas Devlieghere // the public API.
76a69bbe02SLawrence D'Anna 
77a69bbe02SLawrence D'Anna #pragma clang diagnostic push
78a69bbe02SLawrence D'Anna #pragma clang diagnostic ignored "-Wreturn-type-c-linkage"
79a69bbe02SLawrence D'Anna 
801cc0ba4cSAlexandre Ganea // Disable warning C4190: 'LLDBSwigPythonBreakpointCallbackFunction' has
811cc0ba4cSAlexandre Ganea // C-linkage specified, but returns UDT 'llvm::Expected<bool>' which is
821cc0ba4cSAlexandre Ganea // incompatible with C
831cc0ba4cSAlexandre Ganea #if _MSC_VER
841cc0ba4cSAlexandre Ganea #pragma warning (push)
851cc0ba4cSAlexandre Ganea #pragma warning (disable : 4190)
861cc0ba4cSAlexandre Ganea #endif
871cc0ba4cSAlexandre Ganea 
88a69bbe02SLawrence D'Anna extern "C" llvm::Expected<bool> LLDBSwigPythonBreakpointCallbackFunction(
89b01b1087SJonas Devlieghere     const char *python_function_name, const char *session_dictionary_name,
90b01b1087SJonas Devlieghere     const lldb::StackFrameSP &sb_frame,
91a69bbe02SLawrence D'Anna     const lldb::BreakpointLocationSP &sb_bp_loc, StructuredDataImpl *args_impl);
92a69bbe02SLawrence D'Anna 
931cc0ba4cSAlexandre Ganea #if _MSC_VER
941cc0ba4cSAlexandre Ganea #pragma warning (pop)
951cc0ba4cSAlexandre Ganea #endif
961cc0ba4cSAlexandre Ganea 
97a69bbe02SLawrence D'Anna #pragma clang diagnostic pop
98b01b1087SJonas Devlieghere 
99b01b1087SJonas Devlieghere extern "C" bool LLDBSwigPythonWatchpointCallbackFunction(
100b01b1087SJonas Devlieghere     const char *python_function_name, const char *session_dictionary_name,
101b01b1087SJonas Devlieghere     const lldb::StackFrameSP &sb_frame, const lldb::WatchpointSP &sb_wp);
102b01b1087SJonas Devlieghere 
103b01b1087SJonas Devlieghere extern "C" bool LLDBSwigPythonCallTypeScript(
104b01b1087SJonas Devlieghere     const char *python_function_name, void *session_dictionary,
105b01b1087SJonas Devlieghere     const lldb::ValueObjectSP &valobj_sp, void **pyfunct_wrapper,
106b01b1087SJonas Devlieghere     const lldb::TypeSummaryOptionsSP &options_sp, std::string &retval);
107b01b1087SJonas Devlieghere 
108b01b1087SJonas Devlieghere extern "C" void *
109b01b1087SJonas Devlieghere LLDBSwigPythonCreateSyntheticProvider(const char *python_class_name,
110b01b1087SJonas Devlieghere                                       const char *session_dictionary_name,
111b01b1087SJonas Devlieghere                                       const lldb::ValueObjectSP &valobj_sp);
112b01b1087SJonas Devlieghere 
113b01b1087SJonas Devlieghere extern "C" void *
114b01b1087SJonas Devlieghere LLDBSwigPythonCreateCommandObject(const char *python_class_name,
115b01b1087SJonas Devlieghere                                   const char *session_dictionary_name,
116b01b1087SJonas Devlieghere                                   const lldb::DebuggerSP debugger_sp);
117b01b1087SJonas Devlieghere 
118b01b1087SJonas Devlieghere extern "C" void *LLDBSwigPythonCreateScriptedThreadPlan(
119b01b1087SJonas Devlieghere     const char *python_class_name, const char *session_dictionary_name,
12027a14f19SJim Ingham     StructuredDataImpl *args_data,
12193c98346SJim Ingham     std::string &error_string,
122b01b1087SJonas Devlieghere     const lldb::ThreadPlanSP &thread_plan_sp);
123b01b1087SJonas Devlieghere 
124b01b1087SJonas Devlieghere extern "C" bool LLDBSWIGPythonCallThreadPlan(void *implementor,
125b01b1087SJonas Devlieghere                                              const char *method_name,
126b01b1087SJonas Devlieghere                                              Event *event_sp, bool &got_error);
127b01b1087SJonas Devlieghere 
128b01b1087SJonas Devlieghere extern "C" void *LLDBSwigPythonCreateScriptedBreakpointResolver(
129b01b1087SJonas Devlieghere     const char *python_class_name, const char *session_dictionary_name,
130b01b1087SJonas Devlieghere     lldb_private::StructuredDataImpl *args, lldb::BreakpointSP &bkpt_sp);
131b01b1087SJonas Devlieghere 
132b01b1087SJonas Devlieghere extern "C" unsigned int
133b01b1087SJonas Devlieghere LLDBSwigPythonCallBreakpointResolver(void *implementor, const char *method_name,
134b01b1087SJonas Devlieghere                                      lldb_private::SymbolContext *sym_ctx);
135b01b1087SJonas Devlieghere 
1361b1d9815SJim Ingham extern "C" void *LLDBSwigPythonCreateScriptedStopHook(
1371b1d9815SJim Ingham     TargetSP target_sp, const char *python_class_name,
1381b1d9815SJim Ingham     const char *session_dictionary_name, lldb_private::StructuredDataImpl *args,
1391b1d9815SJim Ingham     lldb_private::Status &error);
1401b1d9815SJim Ingham 
1411b1d9815SJim Ingham extern "C" bool
1421b1d9815SJim Ingham LLDBSwigPythonStopHookCallHandleStop(void *implementor,
1431b1d9815SJim Ingham                                      lldb::ExecutionContextRefSP exc_ctx,
1441b1d9815SJim Ingham                                      lldb::StreamSP stream);
1451b1d9815SJim Ingham 
146b01b1087SJonas Devlieghere extern "C" size_t LLDBSwigPython_CalculateNumChildren(void *implementor,
147b01b1087SJonas Devlieghere                                                       uint32_t max);
148b01b1087SJonas Devlieghere 
149b01b1087SJonas Devlieghere extern "C" void *LLDBSwigPython_GetChildAtIndex(void *implementor,
150b01b1087SJonas Devlieghere                                                 uint32_t idx);
151b01b1087SJonas Devlieghere 
152b01b1087SJonas Devlieghere extern "C" int LLDBSwigPython_GetIndexOfChildWithName(void *implementor,
153b01b1087SJonas Devlieghere                                                       const char *child_name);
154b01b1087SJonas Devlieghere 
155b01b1087SJonas Devlieghere extern lldb::ValueObjectSP
156b01b1087SJonas Devlieghere LLDBSWIGPython_GetValueObjectSPFromSBValue(void *data);
157b01b1087SJonas Devlieghere 
158b01b1087SJonas Devlieghere extern "C" bool LLDBSwigPython_UpdateSynthProviderInstance(void *implementor);
159b01b1087SJonas Devlieghere 
160b01b1087SJonas Devlieghere extern "C" bool
161b01b1087SJonas Devlieghere LLDBSwigPython_MightHaveChildrenSynthProviderInstance(void *implementor);
162b01b1087SJonas Devlieghere 
163b01b1087SJonas Devlieghere extern "C" void *
164b01b1087SJonas Devlieghere LLDBSwigPython_GetValueSynthProviderInstance(void *implementor);
165b01b1087SJonas Devlieghere 
166b01b1087SJonas Devlieghere extern "C" bool
167b01b1087SJonas Devlieghere LLDBSwigPythonCallCommand(const char *python_function_name,
168b01b1087SJonas Devlieghere                           const char *session_dictionary_name,
169b01b1087SJonas Devlieghere                           lldb::DebuggerSP &debugger, const char *args,
170b01b1087SJonas Devlieghere                           lldb_private::CommandReturnObject &cmd_retobj,
171b01b1087SJonas Devlieghere                           lldb::ExecutionContextRefSP exe_ctx_ref_sp);
172b01b1087SJonas Devlieghere 
173b01b1087SJonas Devlieghere extern "C" bool
174b01b1087SJonas Devlieghere LLDBSwigPythonCallCommandObject(void *implementor, lldb::DebuggerSP &debugger,
175b01b1087SJonas Devlieghere                                 const char *args,
176b01b1087SJonas Devlieghere                                 lldb_private::CommandReturnObject &cmd_retobj,
177b01b1087SJonas Devlieghere                                 lldb::ExecutionContextRefSP exe_ctx_ref_sp);
178b01b1087SJonas Devlieghere 
179b01b1087SJonas Devlieghere extern "C" bool
180b01b1087SJonas Devlieghere LLDBSwigPythonCallModuleInit(const char *python_module_name,
181b01b1087SJonas Devlieghere                              const char *session_dictionary_name,
182b01b1087SJonas Devlieghere                              lldb::DebuggerSP &debugger);
183b01b1087SJonas Devlieghere 
184b01b1087SJonas Devlieghere extern "C" void *
185b01b1087SJonas Devlieghere LLDBSWIGPythonCreateOSPlugin(const char *python_class_name,
186b01b1087SJonas Devlieghere                              const char *session_dictionary_name,
187b01b1087SJonas Devlieghere                              const lldb::ProcessSP &process_sp);
188b01b1087SJonas Devlieghere 
189b01b1087SJonas Devlieghere extern "C" void *
190b01b1087SJonas Devlieghere LLDBSWIGPython_CreateFrameRecognizer(const char *python_class_name,
191b01b1087SJonas Devlieghere                                      const char *session_dictionary_name);
192b01b1087SJonas Devlieghere 
193b01b1087SJonas Devlieghere extern "C" void *
194b01b1087SJonas Devlieghere LLDBSwigPython_GetRecognizedArguments(void *implementor,
195b01b1087SJonas Devlieghere                                       const lldb::StackFrameSP &frame_sp);
196b01b1087SJonas Devlieghere 
197b01b1087SJonas Devlieghere extern "C" bool LLDBSWIGPythonRunScriptKeywordProcess(
198b01b1087SJonas Devlieghere     const char *python_function_name, const char *session_dictionary_name,
199b01b1087SJonas Devlieghere     lldb::ProcessSP &process, std::string &output);
200b01b1087SJonas Devlieghere 
201b01b1087SJonas Devlieghere extern "C" bool LLDBSWIGPythonRunScriptKeywordThread(
202b01b1087SJonas Devlieghere     const char *python_function_name, const char *session_dictionary_name,
203b01b1087SJonas Devlieghere     lldb::ThreadSP &thread, std::string &output);
204b01b1087SJonas Devlieghere 
205b01b1087SJonas Devlieghere extern "C" bool LLDBSWIGPythonRunScriptKeywordTarget(
206b01b1087SJonas Devlieghere     const char *python_function_name, const char *session_dictionary_name,
207b01b1087SJonas Devlieghere     lldb::TargetSP &target, std::string &output);
208b01b1087SJonas Devlieghere 
209b01b1087SJonas Devlieghere extern "C" bool LLDBSWIGPythonRunScriptKeywordFrame(
210b01b1087SJonas Devlieghere     const char *python_function_name, const char *session_dictionary_name,
211b01b1087SJonas Devlieghere     lldb::StackFrameSP &frame, std::string &output);
212b01b1087SJonas Devlieghere 
213b01b1087SJonas Devlieghere extern "C" bool LLDBSWIGPythonRunScriptKeywordValue(
214b01b1087SJonas Devlieghere     const char *python_function_name, const char *session_dictionary_name,
215b01b1087SJonas Devlieghere     lldb::ValueObjectSP &value, std::string &output);
216b01b1087SJonas Devlieghere 
217b01b1087SJonas Devlieghere extern "C" void *
218b01b1087SJonas Devlieghere LLDBSWIGPython_GetDynamicSetting(void *module, const char *setting,
219b01b1087SJonas Devlieghere                                  const lldb::TargetSP &target_sp);
220b01b1087SJonas Devlieghere 
221d055e3a0SPedro Tammela static ScriptInterpreterPythonImpl *GetPythonInterpreter(Debugger &debugger) {
222d055e3a0SPedro Tammela   ScriptInterpreter *script_interpreter =
223d055e3a0SPedro Tammela       debugger.GetScriptInterpreter(true, lldb::eScriptLanguagePython);
224d055e3a0SPedro Tammela   return static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
225d055e3a0SPedro Tammela }
226d055e3a0SPedro Tammela 
2272c1f46dcSZachary Turner static bool g_initialized = false;
2282c1f46dcSZachary Turner 
229b9c1b51eSKate Stone namespace {
23022c8efcdSZachary Turner 
23105097246SAdrian Prantl // Initializing Python is not a straightforward process.  We cannot control
23205097246SAdrian Prantl // what external code may have done before getting to this point in LLDB,
23305097246SAdrian Prantl // including potentially having already initialized Python, so we need to do a
23405097246SAdrian Prantl // lot of work to ensure that the existing state of the system is maintained
23505097246SAdrian Prantl // across our initialization.  We do this by using an RAII pattern where we
23605097246SAdrian Prantl // save off initial state at the beginning, and restore it at the end
237b9c1b51eSKate Stone struct InitializePythonRAII {
238079fe48aSZachary Turner public:
239b9c1b51eSKate Stone   InitializePythonRAII()
240b9c1b51eSKate Stone       : m_gil_state(PyGILState_UNLOCKED), m_was_already_initialized(false) {
241079fe48aSZachary Turner     InitializePythonHome();
242079fe48aSZachary Turner 
2439357b5d0Sserge-sans-paille #ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
2449357b5d0Sserge-sans-paille     // Python's readline is incompatible with libedit being linked into lldb.
2459357b5d0Sserge-sans-paille     // Provide a patched version local to the embedded interpreter.
2469357b5d0Sserge-sans-paille     bool ReadlinePatched = false;
2479357b5d0Sserge-sans-paille     for (auto *p = PyImport_Inittab; p->name != NULL; p++) {
2489357b5d0Sserge-sans-paille       if (strcmp(p->name, "readline") == 0) {
2499357b5d0Sserge-sans-paille         p->initfunc = initlldb_readline;
2509357b5d0Sserge-sans-paille         break;
2519357b5d0Sserge-sans-paille       }
2529357b5d0Sserge-sans-paille     }
2539357b5d0Sserge-sans-paille     if (!ReadlinePatched) {
2549357b5d0Sserge-sans-paille       PyImport_AppendInittab("readline", initlldb_readline);
2559357b5d0Sserge-sans-paille       ReadlinePatched = true;
2569357b5d0Sserge-sans-paille     }
2579357b5d0Sserge-sans-paille #endif
2589357b5d0Sserge-sans-paille 
25974587a0eSVadim Chugunov     // Register _lldb as a built-in module.
26005495c5dSJonas Devlieghere     PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
26174587a0eSVadim Chugunov 
262079fe48aSZachary Turner // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
263079fe48aSZachary Turner // calling `Py_Initialize` and `PyEval_InitThreads`.  < 3.2 requires that you
264079fe48aSZachary Turner // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
265079fe48aSZachary Turner #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
266079fe48aSZachary Turner     Py_InitializeEx(0);
267079fe48aSZachary Turner     InitializeThreadsPrivate();
268079fe48aSZachary Turner #else
269079fe48aSZachary Turner     InitializeThreadsPrivate();
270079fe48aSZachary Turner     Py_InitializeEx(0);
271079fe48aSZachary Turner #endif
272079fe48aSZachary Turner   }
273079fe48aSZachary Turner 
274b9c1b51eSKate Stone   ~InitializePythonRAII() {
275b9c1b51eSKate Stone     if (m_was_already_initialized) {
2763b7e1981SPavel Labath       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
2773b7e1981SPavel Labath       LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
2781b6700efSTatyana Krasnukha                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
279079fe48aSZachary Turner       PyGILState_Release(m_gil_state);
280b9c1b51eSKate Stone     } else {
281079fe48aSZachary Turner       // We initialized the threads in this function, just unlock the GIL.
282079fe48aSZachary Turner       PyEval_SaveThread();
283079fe48aSZachary Turner     }
284079fe48aSZachary Turner   }
285079fe48aSZachary Turner 
286079fe48aSZachary Turner private:
287b9c1b51eSKate Stone   void InitializePythonHome() {
2883ec3f62fSHaibo Huang #if LLDB_EMBED_PYTHON_HOME
2893ec3f62fSHaibo Huang #if PY_MAJOR_VERSION >= 3
2903ec3f62fSHaibo Huang     typedef wchar_t* str_type;
2913ec3f62fSHaibo Huang #else
2923ec3f62fSHaibo Huang     typedef char* str_type;
2933ec3f62fSHaibo Huang #endif
2943ec3f62fSHaibo Huang     static str_type g_python_home = []() -> str_type {
2953ec3f62fSHaibo Huang       const char *lldb_python_home = LLDB_PYTHON_HOME;
2963ec3f62fSHaibo Huang       const char *absolute_python_home = nullptr;
2973ec3f62fSHaibo Huang       llvm::SmallString<64> path;
2983ec3f62fSHaibo Huang       if (llvm::sys::path::is_absolute(lldb_python_home)) {
2993ec3f62fSHaibo Huang         absolute_python_home = lldb_python_home;
3003ec3f62fSHaibo Huang       } else {
3013ec3f62fSHaibo Huang         FileSpec spec = HostInfo::GetShlibDir();
3023ec3f62fSHaibo Huang         if (!spec)
3033ec3f62fSHaibo Huang           return nullptr;
3043ec3f62fSHaibo Huang         spec.GetPath(path);
3053ec3f62fSHaibo Huang         llvm::sys::path::append(path, lldb_python_home);
3063ec3f62fSHaibo Huang         absolute_python_home = path.c_str();
3073ec3f62fSHaibo Huang       }
30822c8efcdSZachary Turner #if PY_MAJOR_VERSION >= 3
30922c8efcdSZachary Turner       size_t size = 0;
3103ec3f62fSHaibo Huang       return Py_DecodeLocale(absolute_python_home, &size);
31122c8efcdSZachary Turner #else
3123ec3f62fSHaibo Huang       return strdup(absolute_python_home);
31322c8efcdSZachary Turner #endif
3143ec3f62fSHaibo Huang     }();
3153ec3f62fSHaibo Huang     if (g_python_home != nullptr) {
316079fe48aSZachary Turner       Py_SetPythonHome(g_python_home);
3173ec3f62fSHaibo Huang     }
318386f00dbSDavide Italiano #else
319386f00dbSDavide Italiano #if defined(__APPLE__) && PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION == 7
32063dd5d25SJonas Devlieghere     // For Darwin, the only Python version supported is the one shipped in the
32163dd5d25SJonas Devlieghere     // OS OS and linked with lldb. Other installation of Python may have higher
3224f9cb260SDavide Italiano     // priorities in the path, overriding PYTHONHOME and causing
3234f9cb260SDavide Italiano     // problems/incompatibilities. In order to avoid confusion, always hardcode
3244f9cb260SDavide Italiano     // the PythonHome to be right, as it's not going to change.
32563dd5d25SJonas Devlieghere     static char path[] =
32663dd5d25SJonas Devlieghere         "/System/Library/Frameworks/Python.framework/Versions/2.7";
3274f9cb260SDavide Italiano     Py_SetPythonHome(path);
328386f00dbSDavide Italiano #endif
329386f00dbSDavide Italiano #endif
33022c8efcdSZachary Turner   }
33122c8efcdSZachary Turner 
332b9c1b51eSKate Stone   void InitializeThreadsPrivate() {
3331b6700efSTatyana Krasnukha // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself,
3341b6700efSTatyana Krasnukha // so there is no way to determine whether the embedded interpreter
3351b6700efSTatyana Krasnukha // was already initialized by some external code. `PyEval_ThreadsInitialized`
3361b6700efSTatyana Krasnukha // would always return `true` and `PyGILState_Ensure/Release` flow would be
3371b6700efSTatyana Krasnukha // executed instead of unlocking GIL with `PyEval_SaveThread`. When
3381b6700efSTatyana Krasnukha // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock.
3391b6700efSTatyana Krasnukha #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3)
3401b6700efSTatyana Krasnukha     // The only case we should go further and acquire the GIL: it is unlocked.
3411b6700efSTatyana Krasnukha     if (PyGILState_Check())
3421b6700efSTatyana Krasnukha       return;
3431b6700efSTatyana Krasnukha #endif
3441b6700efSTatyana Krasnukha 
345b9c1b51eSKate Stone     if (PyEval_ThreadsInitialized()) {
3463b7e1981SPavel Labath       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
347079fe48aSZachary Turner 
348079fe48aSZachary Turner       m_was_already_initialized = true;
349079fe48aSZachary Turner       m_gil_state = PyGILState_Ensure();
3503b7e1981SPavel Labath       LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n",
351079fe48aSZachary Turner                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
352079fe48aSZachary Turner       return;
353079fe48aSZachary Turner     }
354079fe48aSZachary Turner 
355079fe48aSZachary Turner     // InitThreads acquires the GIL if it hasn't been called before.
356079fe48aSZachary Turner     PyEval_InitThreads();
357079fe48aSZachary Turner   }
358079fe48aSZachary Turner 
359079fe48aSZachary Turner   TerminalState m_stdin_tty_state;
360079fe48aSZachary Turner   PyGILState_STATE m_gil_state;
361079fe48aSZachary Turner   bool m_was_already_initialized;
362079fe48aSZachary Turner };
36363dd5d25SJonas Devlieghere } // namespace
3642c1f46dcSZachary Turner 
3652df331b0SPavel Labath void ScriptInterpreterPython::ComputePythonDirForApple(
3662df331b0SPavel Labath     llvm::SmallVectorImpl<char> &path) {
3672df331b0SPavel Labath   auto style = llvm::sys::path::Style::posix;
3682df331b0SPavel Labath 
3692df331b0SPavel Labath   llvm::StringRef path_ref(path.begin(), path.size());
3702df331b0SPavel Labath   auto rbegin = llvm::sys::path::rbegin(path_ref, style);
3712df331b0SPavel Labath   auto rend = llvm::sys::path::rend(path_ref);
3722df331b0SPavel Labath   auto framework = std::find(rbegin, rend, "LLDB.framework");
3732df331b0SPavel Labath   if (framework == rend) {
37461f471a7SHaibo Huang     ComputePythonDir(path);
3752df331b0SPavel Labath     return;
3762df331b0SPavel Labath   }
3772df331b0SPavel Labath   path.resize(framework - rend);
3782df331b0SPavel Labath   llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
3792df331b0SPavel Labath }
3802df331b0SPavel Labath 
38161f471a7SHaibo Huang void ScriptInterpreterPython::ComputePythonDir(
3822df331b0SPavel Labath     llvm::SmallVectorImpl<char> &path) {
3832df331b0SPavel Labath   // Build the path by backing out of the lib dir, then building with whatever
3842df331b0SPavel Labath   // the real python interpreter uses.  (e.g. lib for most, lib64 on RHEL
38561f471a7SHaibo Huang   // x86_64, or bin on Windows).
38661f471a7SHaibo Huang   llvm::sys::path::remove_filename(path);
38761f471a7SHaibo Huang   llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
3880016b450SHaibo Huang 
3890016b450SHaibo Huang #if defined(_WIN32)
3900016b450SHaibo Huang   // This will be injected directly through FileSpec.GetDirectory().SetString(),
3910016b450SHaibo Huang   // so we need to normalize manually.
3920016b450SHaibo Huang   std::replace(path.begin(), path.end(), '\\', '/');
3930016b450SHaibo Huang #endif
3942df331b0SPavel Labath }
3952df331b0SPavel Labath 
3962df331b0SPavel Labath FileSpec ScriptInterpreterPython::GetPythonDir() {
3972df331b0SPavel Labath   static FileSpec g_spec = []() {
3982df331b0SPavel Labath     FileSpec spec = HostInfo::GetShlibDir();
3992df331b0SPavel Labath     if (!spec)
4002df331b0SPavel Labath       return FileSpec();
4012df331b0SPavel Labath     llvm::SmallString<64> path;
4022df331b0SPavel Labath     spec.GetPath(path);
4032df331b0SPavel Labath 
4042df331b0SPavel Labath #if defined(__APPLE__)
4052df331b0SPavel Labath     ComputePythonDirForApple(path);
4062df331b0SPavel Labath #else
40761f471a7SHaibo Huang     ComputePythonDir(path);
4082df331b0SPavel Labath #endif
4092df331b0SPavel Labath     spec.GetDirectory().SetString(path);
4102df331b0SPavel Labath     return spec;
4112df331b0SPavel Labath   }();
4122df331b0SPavel Labath   return g_spec;
4132df331b0SPavel Labath }
4142df331b0SPavel Labath 
415004a264fSPavel Labath void ScriptInterpreterPython::SharedLibraryDirectoryHelper(
416004a264fSPavel Labath     FileSpec &this_file) {
417004a264fSPavel Labath   // When we're loaded from python, this_file will point to the file inside the
418004a264fSPavel Labath   // python package directory. Replace it with the one in the lib directory.
419004a264fSPavel Labath #ifdef _WIN32
420004a264fSPavel Labath   // On windows, we need to manually back out of the python tree, and go into
421004a264fSPavel Labath   // the bin directory. This is pretty much the inverse of what ComputePythonDir
422004a264fSPavel Labath   // does.
423004a264fSPavel Labath   if (this_file.GetFileNameExtension() == ConstString(".pyd")) {
424004a264fSPavel Labath     this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd
425004a264fSPavel Labath     this_file.RemoveLastPathComponent(); // lldb
4262e826088SPavel Labath     llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
4272e826088SPavel Labath     for (auto it = llvm::sys::path::begin(libdir),
4282e826088SPavel Labath               end = llvm::sys::path::end(libdir);
429004a264fSPavel Labath          it != end; ++it)
430004a264fSPavel Labath       this_file.RemoveLastPathComponent();
431004a264fSPavel Labath     this_file.AppendPathComponent("bin");
432004a264fSPavel Labath     this_file.AppendPathComponent("liblldb.dll");
433004a264fSPavel Labath   }
434004a264fSPavel Labath #else
435004a264fSPavel Labath   // The python file is a symlink, so we can find the real library by resolving
436004a264fSPavel Labath   // it. We can do this unconditionally.
437004a264fSPavel Labath   FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
438004a264fSPavel Labath #endif
439004a264fSPavel Labath }
440004a264fSPavel Labath 
44163dd5d25SJonas Devlieghere lldb_private::ConstString ScriptInterpreterPython::GetPluginNameStatic() {
44263dd5d25SJonas Devlieghere   static ConstString g_name("script-python");
44363dd5d25SJonas Devlieghere   return g_name;
44463dd5d25SJonas Devlieghere }
44563dd5d25SJonas Devlieghere 
44663dd5d25SJonas Devlieghere const char *ScriptInterpreterPython::GetPluginDescriptionStatic() {
44763dd5d25SJonas Devlieghere   return "Embedded Python interpreter";
44863dd5d25SJonas Devlieghere }
44963dd5d25SJonas Devlieghere 
45063dd5d25SJonas Devlieghere void ScriptInterpreterPython::Initialize() {
45163dd5d25SJonas Devlieghere   static llvm::once_flag g_once_flag;
45263dd5d25SJonas Devlieghere 
45363dd5d25SJonas Devlieghere   llvm::call_once(g_once_flag, []() {
45463dd5d25SJonas Devlieghere     PluginManager::RegisterPlugin(GetPluginNameStatic(),
45563dd5d25SJonas Devlieghere                                   GetPluginDescriptionStatic(),
45663dd5d25SJonas Devlieghere                                   lldb::eScriptLanguagePython,
45763dd5d25SJonas Devlieghere                                   ScriptInterpreterPythonImpl::CreateInstance);
45863dd5d25SJonas Devlieghere   });
45963dd5d25SJonas Devlieghere }
46063dd5d25SJonas Devlieghere 
46163dd5d25SJonas Devlieghere void ScriptInterpreterPython::Terminate() {}
46263dd5d25SJonas Devlieghere 
46363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::Locker(
46463dd5d25SJonas Devlieghere     ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
465b07823f3SLawrence D'Anna     uint16_t on_leave, FileSP in, FileSP out, FileSP err)
46663dd5d25SJonas Devlieghere     : ScriptInterpreterLocker(),
46763dd5d25SJonas Devlieghere       m_teardown_session((on_leave & TearDownSession) == TearDownSession),
46863dd5d25SJonas Devlieghere       m_python_interpreter(py_interpreter) {
4695861234eSJonas Devlieghere   repro::Recorder::PrivateThread();
47063dd5d25SJonas Devlieghere   DoAcquireLock();
47163dd5d25SJonas Devlieghere   if ((on_entry & InitSession) == InitSession) {
47263dd5d25SJonas Devlieghere     if (!DoInitSession(on_entry, in, out, err)) {
47363dd5d25SJonas Devlieghere       // Don't teardown the session if we didn't init it.
47463dd5d25SJonas Devlieghere       m_teardown_session = false;
47563dd5d25SJonas Devlieghere     }
47663dd5d25SJonas Devlieghere   }
47763dd5d25SJonas Devlieghere }
47863dd5d25SJonas Devlieghere 
47963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
48063dd5d25SJonas Devlieghere   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
48163dd5d25SJonas Devlieghere   m_GILState = PyGILState_Ensure();
48263dd5d25SJonas Devlieghere   LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked",
48363dd5d25SJonas Devlieghere             m_GILState == PyGILState_UNLOCKED ? "un" : "");
48463dd5d25SJonas Devlieghere 
48563dd5d25SJonas Devlieghere   // we need to save the thread state when we first start the command because
48663dd5d25SJonas Devlieghere   // we might decide to interrupt it while some action is taking place outside
48763dd5d25SJonas Devlieghere   // of Python (e.g. printing to screen, waiting for the network, ...) in that
48863dd5d25SJonas Devlieghere   // case, _PyThreadState_Current will be NULL - and we would be unable to set
48963dd5d25SJonas Devlieghere   // the asynchronous exception - not a desirable situation
49063dd5d25SJonas Devlieghere   m_python_interpreter->SetThreadState(PyThreadState_Get());
49163dd5d25SJonas Devlieghere   m_python_interpreter->IncrementLockCount();
49263dd5d25SJonas Devlieghere   return true;
49363dd5d25SJonas Devlieghere }
49463dd5d25SJonas Devlieghere 
49563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
496b07823f3SLawrence D'Anna                                                         FileSP in, FileSP out,
497b07823f3SLawrence D'Anna                                                         FileSP err) {
49863dd5d25SJonas Devlieghere   if (!m_python_interpreter)
49963dd5d25SJonas Devlieghere     return false;
50063dd5d25SJonas Devlieghere   return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
50163dd5d25SJonas Devlieghere }
50263dd5d25SJonas Devlieghere 
50363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
50463dd5d25SJonas Devlieghere   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
50563dd5d25SJonas Devlieghere   LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
50663dd5d25SJonas Devlieghere             m_GILState == PyGILState_UNLOCKED ? "un" : "");
50763dd5d25SJonas Devlieghere   PyGILState_Release(m_GILState);
50863dd5d25SJonas Devlieghere   m_python_interpreter->DecrementLockCount();
50963dd5d25SJonas Devlieghere   return true;
51063dd5d25SJonas Devlieghere }
51163dd5d25SJonas Devlieghere 
51263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
51363dd5d25SJonas Devlieghere   if (!m_python_interpreter)
51463dd5d25SJonas Devlieghere     return false;
51563dd5d25SJonas Devlieghere   m_python_interpreter->LeaveSession();
51663dd5d25SJonas Devlieghere   return true;
51763dd5d25SJonas Devlieghere }
51863dd5d25SJonas Devlieghere 
51963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::~Locker() {
52063dd5d25SJonas Devlieghere   if (m_teardown_session)
52163dd5d25SJonas Devlieghere     DoTearDownSession();
52263dd5d25SJonas Devlieghere   DoFreeLock();
52363dd5d25SJonas Devlieghere }
52463dd5d25SJonas Devlieghere 
5258d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger)
5268d1fb843SJonas Devlieghere     : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
52763dd5d25SJonas Devlieghere       m_saved_stderr(), m_main_module(),
52863dd5d25SJonas Devlieghere       m_session_dict(PyInitialValue::Invalid),
52963dd5d25SJonas Devlieghere       m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(),
53063dd5d25SJonas Devlieghere       m_run_one_line_str_global(),
5318d1fb843SJonas Devlieghere       m_dictionary_name(m_debugger.GetInstanceName().AsCString()),
532ea1752a7SJonas Devlieghere       m_active_io_handler(eIOHandlerNone), m_session_is_active(false),
53364ec505dSJonas Devlieghere       m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
534ea1752a7SJonas Devlieghere       m_command_thread_state(nullptr) {
53563dd5d25SJonas Devlieghere   InitializePrivate();
53663dd5d25SJonas Devlieghere 
537*1f6a57c1SMed Ismail Bennani   m_scripted_process_interface_up =
538*1f6a57c1SMed Ismail Bennani       std::make_unique<ScriptedProcessPythonInterface>(*this);
539*1f6a57c1SMed Ismail Bennani 
54063dd5d25SJonas Devlieghere   m_dictionary_name.append("_dict");
54163dd5d25SJonas Devlieghere   StreamString run_string;
54263dd5d25SJonas Devlieghere   run_string.Printf("%s = dict()", m_dictionary_name.c_str());
54363dd5d25SJonas Devlieghere 
54463dd5d25SJonas Devlieghere   Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock);
54563dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
54663dd5d25SJonas Devlieghere 
54763dd5d25SJonas Devlieghere   run_string.Clear();
54863dd5d25SJonas Devlieghere   run_string.Printf(
54963dd5d25SJonas Devlieghere       "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
55063dd5d25SJonas Devlieghere       m_dictionary_name.c_str());
55163dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
55263dd5d25SJonas Devlieghere 
55363dd5d25SJonas Devlieghere   // Reloading modules requires a different syntax in Python 2 and Python 3.
55463dd5d25SJonas Devlieghere   // This provides a consistent syntax no matter what version of Python.
55563dd5d25SJonas Devlieghere   run_string.Clear();
55663dd5d25SJonas Devlieghere   run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')",
55763dd5d25SJonas Devlieghere                     m_dictionary_name.c_str());
55863dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
55963dd5d25SJonas Devlieghere 
56063dd5d25SJonas Devlieghere   // WARNING: temporary code that loads Cocoa formatters - this should be done
56163dd5d25SJonas Devlieghere   // on a per-platform basis rather than loading the whole set and letting the
56263dd5d25SJonas Devlieghere   // individual formatter classes exploit APIs to check whether they can/cannot
56363dd5d25SJonas Devlieghere   // do their task
56463dd5d25SJonas Devlieghere   run_string.Clear();
56563dd5d25SJonas Devlieghere   run_string.Printf(
56663dd5d25SJonas Devlieghere       "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')",
56763dd5d25SJonas Devlieghere       m_dictionary_name.c_str());
56863dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
56963dd5d25SJonas Devlieghere   run_string.Clear();
57063dd5d25SJonas Devlieghere 
57163dd5d25SJonas Devlieghere   run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
57263dd5d25SJonas Devlieghere                     "lldb.embedded_interpreter import run_python_interpreter; "
57363dd5d25SJonas Devlieghere                     "from lldb.embedded_interpreter import run_one_line')",
57463dd5d25SJonas Devlieghere                     m_dictionary_name.c_str());
57563dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
57663dd5d25SJonas Devlieghere   run_string.Clear();
57763dd5d25SJonas Devlieghere 
57863dd5d25SJonas Devlieghere   run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
57963dd5d25SJonas Devlieghere                     "; pydoc.pager = pydoc.plainpager')",
5808d1fb843SJonas Devlieghere                     m_dictionary_name.c_str(), m_debugger.GetID());
58163dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
58263dd5d25SJonas Devlieghere }
58363dd5d25SJonas Devlieghere 
58463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
58563dd5d25SJonas Devlieghere   // the session dictionary may hold objects with complex state which means
58663dd5d25SJonas Devlieghere   // that they may need to be torn down with some level of smarts and that, in
58763dd5d25SJonas Devlieghere   // turn, requires a valid thread state force Python to procure itself such a
58863dd5d25SJonas Devlieghere   // thread state, nuke the session dictionary and then release it for others
58963dd5d25SJonas Devlieghere   // to use and proceed with the rest of the shutdown
59063dd5d25SJonas Devlieghere   auto gil_state = PyGILState_Ensure();
59163dd5d25SJonas Devlieghere   m_session_dict.Reset();
59263dd5d25SJonas Devlieghere   PyGILState_Release(gil_state);
59363dd5d25SJonas Devlieghere }
59463dd5d25SJonas Devlieghere 
59563dd5d25SJonas Devlieghere lldb_private::ConstString ScriptInterpreterPythonImpl::GetPluginName() {
5962c1f46dcSZachary Turner   return GetPluginNameStatic();
5972c1f46dcSZachary Turner }
5982c1f46dcSZachary Turner 
59963dd5d25SJonas Devlieghere uint32_t ScriptInterpreterPythonImpl::GetPluginVersion() { return 1; }
6002c1f46dcSZachary Turner 
60163dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler,
60263dd5d25SJonas Devlieghere                                                      bool interactive) {
6032c1f46dcSZachary Turner   const char *instructions = nullptr;
6042c1f46dcSZachary Turner 
605b9c1b51eSKate Stone   switch (m_active_io_handler) {
6062c1f46dcSZachary Turner   case eIOHandlerNone:
6072c1f46dcSZachary Turner     break;
6082c1f46dcSZachary Turner   case eIOHandlerBreakpoint:
6092c1f46dcSZachary Turner     instructions = R"(Enter your Python command(s). Type 'DONE' to end.
6102c1f46dcSZachary Turner def function (frame, bp_loc, internal_dict):
6112c1f46dcSZachary Turner     """frame: the lldb.SBFrame for the location at which you stopped
6122c1f46dcSZachary Turner        bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
6132c1f46dcSZachary Turner        internal_dict: an LLDB support object not to be used"""
6142c1f46dcSZachary Turner )";
6152c1f46dcSZachary Turner     break;
6162c1f46dcSZachary Turner   case eIOHandlerWatchpoint:
6172c1f46dcSZachary Turner     instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
6182c1f46dcSZachary Turner     break;
6192c1f46dcSZachary Turner   }
6202c1f46dcSZachary Turner 
621b9c1b51eSKate Stone   if (instructions) {
6227ca15ba7SLawrence D'Anna     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
6230affb582SDave Lee     if (output_sp && interactive) {
6242c1f46dcSZachary Turner       output_sp->PutCString(instructions);
6252c1f46dcSZachary Turner       output_sp->Flush();
6262c1f46dcSZachary Turner     }
6272c1f46dcSZachary Turner   }
6282c1f46dcSZachary Turner }
6292c1f46dcSZachary Turner 
63063dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler,
631b9c1b51eSKate Stone                                                          std::string &data) {
6322c1f46dcSZachary Turner   io_handler.SetIsDone(true);
6338d1fb843SJonas Devlieghere   bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
6342c1f46dcSZachary Turner 
635b9c1b51eSKate Stone   switch (m_active_io_handler) {
6362c1f46dcSZachary Turner   case eIOHandlerNone:
6372c1f46dcSZachary Turner     break;
638b9c1b51eSKate Stone   case eIOHandlerBreakpoint: {
639b9c1b51eSKate Stone     std::vector<BreakpointOptions *> *bp_options_vec =
640b9c1b51eSKate Stone         (std::vector<BreakpointOptions *> *)io_handler.GetUserData();
641b9c1b51eSKate Stone     for (auto bp_options : *bp_options_vec) {
6422c1f46dcSZachary Turner       if (!bp_options)
6432c1f46dcSZachary Turner         continue;
6442c1f46dcSZachary Turner 
645a8f3ae7cSJonas Devlieghere       auto data_up = std::make_unique<CommandDataPython>();
646d5b44036SJonas Devlieghere       if (!data_up)
6474e4fbe82SZachary Turner         break;
648d5b44036SJonas Devlieghere       data_up->user_source.SplitIntoLines(data);
6492c1f46dcSZachary Turner 
650738af7a6SJim Ingham       StructuredData::ObjectSP empty_args_sp;
651d5b44036SJonas Devlieghere       if (GenerateBreakpointCommandCallbackData(data_up->user_source,
652738af7a6SJim Ingham                                                 data_up->script_source,
653738af7a6SJim Ingham                                                 false)
654b9c1b51eSKate Stone               .Success()) {
6554e4fbe82SZachary Turner         auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
656d5b44036SJonas Devlieghere             std::move(data_up));
657b9c1b51eSKate Stone         bp_options->SetCallback(
65863dd5d25SJonas Devlieghere             ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
659b9c1b51eSKate Stone       } else if (!batch_mode) {
6607ca15ba7SLawrence D'Anna         StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
661b9c1b51eSKate Stone         if (error_sp) {
6622c1f46dcSZachary Turner           error_sp->Printf("Warning: No command attached to breakpoint.\n");
6632c1f46dcSZachary Turner           error_sp->Flush();
6642c1f46dcSZachary Turner         }
6652c1f46dcSZachary Turner       }
6662c1f46dcSZachary Turner     }
6672c1f46dcSZachary Turner     m_active_io_handler = eIOHandlerNone;
668b9c1b51eSKate Stone   } break;
669b9c1b51eSKate Stone   case eIOHandlerWatchpoint: {
670b9c1b51eSKate Stone     WatchpointOptions *wp_options =
671b9c1b51eSKate Stone         (WatchpointOptions *)io_handler.GetUserData();
672a8f3ae7cSJonas Devlieghere     auto data_up = std::make_unique<WatchpointOptions::CommandData>();
673d5b44036SJonas Devlieghere     data_up->user_source.SplitIntoLines(data);
6742c1f46dcSZachary Turner 
675d5b44036SJonas Devlieghere     if (GenerateWatchpointCommandCallbackData(data_up->user_source,
676d5b44036SJonas Devlieghere                                               data_up->script_source)) {
6774e4fbe82SZachary Turner       auto baton_sp =
678d5b44036SJonas Devlieghere           std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
679b9c1b51eSKate Stone       wp_options->SetCallback(
68063dd5d25SJonas Devlieghere           ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
681b9c1b51eSKate Stone     } else if (!batch_mode) {
6827ca15ba7SLawrence D'Anna       StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
683b9c1b51eSKate Stone       if (error_sp) {
6842c1f46dcSZachary Turner         error_sp->Printf("Warning: No command attached to breakpoint.\n");
6852c1f46dcSZachary Turner         error_sp->Flush();
6862c1f46dcSZachary Turner       }
6872c1f46dcSZachary Turner     }
6882c1f46dcSZachary Turner     m_active_io_handler = eIOHandlerNone;
689b9c1b51eSKate Stone   } break;
6902c1f46dcSZachary Turner   }
6912c1f46dcSZachary Turner }
6922c1f46dcSZachary Turner 
69363dd5d25SJonas Devlieghere lldb::ScriptInterpreterSP
6948d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) {
6958d1fb843SJonas Devlieghere   return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
69663dd5d25SJonas Devlieghere }
6972c1f46dcSZachary Turner 
69863dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::LeaveSession() {
6992c1f46dcSZachary Turner   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
7002c1f46dcSZachary Turner   if (log)
70163dd5d25SJonas Devlieghere     log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
7022c1f46dcSZachary Turner 
70320b52c33SJonas Devlieghere   // Unset the LLDB global variables.
70420b52c33SJonas Devlieghere   PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
70520b52c33SJonas Devlieghere                      "= None; lldb.thread = None; lldb.frame = None");
70620b52c33SJonas Devlieghere 
70705097246SAdrian Prantl   // checking that we have a valid thread state - since we use our own
70805097246SAdrian Prantl   // threading and locking in some (rare) cases during cleanup Python may end
70905097246SAdrian Prantl   // up believing we have no thread state and PyImport_AddModule will crash if
71005097246SAdrian Prantl   // that is the case - since that seems to only happen when destroying the
71105097246SAdrian Prantl   // SBDebugger, we can make do without clearing up stdout and stderr
7122c1f46dcSZachary Turner 
7132c1f46dcSZachary Turner   // rdar://problem/11292882
714b9c1b51eSKate Stone   // When the current thread state is NULL, PyThreadState_Get() issues a fatal
715b9c1b51eSKate Stone   // error.
716b9c1b51eSKate Stone   if (PyThreadState_GetDict()) {
7172c1f46dcSZachary Turner     PythonDictionary &sys_module_dict = GetSysModuleDictionary();
718b9c1b51eSKate Stone     if (sys_module_dict.IsValid()) {
719b9c1b51eSKate Stone       if (m_saved_stdin.IsValid()) {
720f8b22f8fSZachary Turner         sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
7212c1f46dcSZachary Turner         m_saved_stdin.Reset();
7222c1f46dcSZachary Turner       }
723b9c1b51eSKate Stone       if (m_saved_stdout.IsValid()) {
724f8b22f8fSZachary Turner         sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
7252c1f46dcSZachary Turner         m_saved_stdout.Reset();
7262c1f46dcSZachary Turner       }
727b9c1b51eSKate Stone       if (m_saved_stderr.IsValid()) {
728f8b22f8fSZachary Turner         sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
7292c1f46dcSZachary Turner         m_saved_stderr.Reset();
7302c1f46dcSZachary Turner       }
7312c1f46dcSZachary Turner     }
7322c1f46dcSZachary Turner   }
7332c1f46dcSZachary Turner 
7342c1f46dcSZachary Turner   m_session_is_active = false;
7352c1f46dcSZachary Turner }
7362c1f46dcSZachary Turner 
737b07823f3SLawrence D'Anna bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp,
738b07823f3SLawrence D'Anna                                                const char *py_name,
739b07823f3SLawrence D'Anna                                                PythonObject &save_file,
740b9c1b51eSKate Stone                                                const char *mode) {
741b07823f3SLawrence D'Anna   if (!file_sp || !*file_sp) {
742b07823f3SLawrence D'Anna     save_file.Reset();
743b07823f3SLawrence D'Anna     return false;
744b07823f3SLawrence D'Anna   }
745b07823f3SLawrence D'Anna   File &file = *file_sp;
746b07823f3SLawrence D'Anna 
747a31baf08SGreg Clayton   // Flush the file before giving it to python to avoid interleaved output.
748a31baf08SGreg Clayton   file.Flush();
749a31baf08SGreg Clayton 
750a31baf08SGreg Clayton   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
751a31baf08SGreg Clayton 
7520f783599SLawrence D'Anna   auto new_file = PythonFile::FromFile(file, mode);
7530f783599SLawrence D'Anna   if (!new_file) {
7540f783599SLawrence D'Anna     llvm::consumeError(new_file.takeError());
7550f783599SLawrence D'Anna     return false;
7560f783599SLawrence D'Anna   }
7570f783599SLawrence D'Anna 
758b07823f3SLawrence D'Anna   save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
759a31baf08SGreg Clayton 
7600f783599SLawrence D'Anna   sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
761a31baf08SGreg Clayton   return true;
762a31baf08SGreg Clayton }
763a31baf08SGreg Clayton 
76463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
765b07823f3SLawrence D'Anna                                                FileSP in_sp, FileSP out_sp,
766b07823f3SLawrence D'Anna                                                FileSP err_sp) {
767b9c1b51eSKate Stone   // If we have already entered the session, without having officially 'left'
76805097246SAdrian Prantl   // it, then there is no need to 'enter' it again.
7692c1f46dcSZachary Turner   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
770b9c1b51eSKate Stone   if (m_session_is_active) {
77163e5fb76SJonas Devlieghere     LLDB_LOGF(
77263e5fb76SJonas Devlieghere         log,
77363dd5d25SJonas Devlieghere         "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
774b9c1b51eSKate Stone         ") session is already active, returning without doing anything",
775b9c1b51eSKate Stone         on_entry_flags);
7762c1f46dcSZachary Turner     return false;
7772c1f46dcSZachary Turner   }
7782c1f46dcSZachary Turner 
77963e5fb76SJonas Devlieghere   LLDB_LOGF(
78063e5fb76SJonas Devlieghere       log,
78163e5fb76SJonas Devlieghere       "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
782b9c1b51eSKate Stone       on_entry_flags);
7832c1f46dcSZachary Turner 
7842c1f46dcSZachary Turner   m_session_is_active = true;
7852c1f46dcSZachary Turner 
7862c1f46dcSZachary Turner   StreamString run_string;
7872c1f46dcSZachary Turner 
788b9c1b51eSKate Stone   if (on_entry_flags & Locker::InitGlobals) {
789b9c1b51eSKate Stone     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
7908d1fb843SJonas Devlieghere                       m_dictionary_name.c_str(), m_debugger.GetID());
791b9c1b51eSKate Stone     run_string.Printf(
792b9c1b51eSKate Stone         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
7938d1fb843SJonas Devlieghere         m_debugger.GetID());
7942c1f46dcSZachary Turner     run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
7952c1f46dcSZachary Turner     run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
7962c1f46dcSZachary Turner     run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
7972c1f46dcSZachary Turner     run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
7982c1f46dcSZachary Turner     run_string.PutCString("')");
799b9c1b51eSKate Stone   } else {
80005097246SAdrian Prantl     // If we aren't initing the globals, we should still always set the
80105097246SAdrian Prantl     // debugger (since that is always unique.)
802b9c1b51eSKate Stone     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
8038d1fb843SJonas Devlieghere                       m_dictionary_name.c_str(), m_debugger.GetID());
804b9c1b51eSKate Stone     run_string.Printf(
805b9c1b51eSKate Stone         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
8068d1fb843SJonas Devlieghere         m_debugger.GetID());
8072c1f46dcSZachary Turner     run_string.PutCString("')");
8082c1f46dcSZachary Turner   }
8092c1f46dcSZachary Turner 
8102c1f46dcSZachary Turner   PyRun_SimpleString(run_string.GetData());
8112c1f46dcSZachary Turner   run_string.Clear();
8122c1f46dcSZachary Turner 
8132c1f46dcSZachary Turner   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
814b9c1b51eSKate Stone   if (sys_module_dict.IsValid()) {
815b07823f3SLawrence D'Anna     lldb::FileSP top_in_sp;
816b07823f3SLawrence D'Anna     lldb::StreamFileSP top_out_sp, top_err_sp;
817b07823f3SLawrence D'Anna     if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
818b07823f3SLawrence D'Anna       m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
819b07823f3SLawrence D'Anna                                                  top_err_sp);
8202c1f46dcSZachary Turner 
821b9c1b51eSKate Stone     if (on_entry_flags & Locker::NoSTDIN) {
8222c1f46dcSZachary Turner       m_saved_stdin.Reset();
823b9c1b51eSKate Stone     } else {
824b07823f3SLawrence D'Anna       if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
825b07823f3SLawrence D'Anna         if (top_in_sp)
826b07823f3SLawrence D'Anna           SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
8272c1f46dcSZachary Turner       }
828a31baf08SGreg Clayton     }
829a31baf08SGreg Clayton 
830b07823f3SLawrence D'Anna     if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
831b07823f3SLawrence D'Anna       if (top_out_sp)
832b07823f3SLawrence D'Anna         SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w");
833a31baf08SGreg Clayton     }
834a31baf08SGreg Clayton 
835b07823f3SLawrence D'Anna     if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
836b07823f3SLawrence D'Anna       if (top_err_sp)
837b07823f3SLawrence D'Anna         SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w");
838a31baf08SGreg Clayton     }
8392c1f46dcSZachary Turner   }
8402c1f46dcSZachary Turner 
8412c1f46dcSZachary Turner   if (PyErr_Occurred())
8422c1f46dcSZachary Turner     PyErr_Clear();
8432c1f46dcSZachary Turner 
8442c1f46dcSZachary Turner   return true;
8452c1f46dcSZachary Turner }
8462c1f46dcSZachary Turner 
84704edd189SLawrence D'Anna PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
848f8b22f8fSZachary Turner   if (!m_main_module.IsValid())
84904edd189SLawrence D'Anna     m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__"));
8502c1f46dcSZachary Turner   return m_main_module;
8512c1f46dcSZachary Turner }
8522c1f46dcSZachary Turner 
85363dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
854f8b22f8fSZachary Turner   if (m_session_dict.IsValid())
855f8b22f8fSZachary Turner     return m_session_dict;
856f8b22f8fSZachary Turner 
8572c1f46dcSZachary Turner   PythonObject &main_module = GetMainModule();
858f8b22f8fSZachary Turner   if (!main_module.IsValid())
859f8b22f8fSZachary Turner     return m_session_dict;
860f8b22f8fSZachary Turner 
861b9c1b51eSKate Stone   PythonDictionary main_dict(PyRefType::Borrowed,
862b9c1b51eSKate Stone                              PyModule_GetDict(main_module.get()));
863f8b22f8fSZachary Turner   if (!main_dict.IsValid())
864f8b22f8fSZachary Turner     return m_session_dict;
865f8b22f8fSZachary Turner 
866722b6189SLawrence D'Anna   m_session_dict = unwrapIgnoringErrors(
867722b6189SLawrence D'Anna       As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
8682c1f46dcSZachary Turner   return m_session_dict;
8692c1f46dcSZachary Turner }
8702c1f46dcSZachary Turner 
87163dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
872f8b22f8fSZachary Turner   if (m_sys_module_dict.IsValid())
873f8b22f8fSZachary Turner     return m_sys_module_dict;
874722b6189SLawrence D'Anna   PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys"));
875722b6189SLawrence D'Anna   m_sys_module_dict = sys_module.GetDictionary();
8762c1f46dcSZachary Turner   return m_sys_module_dict;
8772c1f46dcSZachary Turner }
8782c1f46dcSZachary Turner 
879a69bbe02SLawrence D'Anna llvm::Expected<unsigned>
880a69bbe02SLawrence D'Anna ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
881a69bbe02SLawrence D'Anna     const llvm::StringRef &callable_name) {
882738af7a6SJim Ingham   if (callable_name.empty()) {
883738af7a6SJim Ingham     return llvm::createStringError(
884738af7a6SJim Ingham         llvm::inconvertibleErrorCode(),
885738af7a6SJim Ingham         "called with empty callable name.");
886738af7a6SJim Ingham   }
887738af7a6SJim Ingham   Locker py_lock(this, Locker::AcquireLock |
888738af7a6SJim Ingham                  Locker::InitSession |
889738af7a6SJim Ingham                  Locker::NoSTDIN);
890738af7a6SJim Ingham   auto dict = PythonModule::MainModule()
891738af7a6SJim Ingham       .ResolveName<PythonDictionary>(m_dictionary_name);
892a69bbe02SLawrence D'Anna   auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
893a69bbe02SLawrence D'Anna       callable_name, dict);
894738af7a6SJim Ingham   if (!pfunc.IsAllocated()) {
895738af7a6SJim Ingham     return llvm::createStringError(
896738af7a6SJim Ingham         llvm::inconvertibleErrorCode(),
897738af7a6SJim Ingham         "can't find callable: %s", callable_name.str().c_str());
898738af7a6SJim Ingham   }
899adbf64ccSLawrence D'Anna   llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
900adbf64ccSLawrence D'Anna   if (!arg_info)
901adbf64ccSLawrence D'Anna     return arg_info.takeError();
902adbf64ccSLawrence D'Anna   return arg_info.get().max_positional_args;
903738af7a6SJim Ingham }
904738af7a6SJim Ingham 
905b9c1b51eSKate Stone static std::string GenerateUniqueName(const char *base_name_wanted,
9062c1f46dcSZachary Turner                                       uint32_t &functions_counter,
907b9c1b51eSKate Stone                                       const void *name_token = nullptr) {
9082c1f46dcSZachary Turner   StreamString sstr;
9092c1f46dcSZachary Turner 
9102c1f46dcSZachary Turner   if (!base_name_wanted)
9112c1f46dcSZachary Turner     return std::string();
9122c1f46dcSZachary Turner 
9132c1f46dcSZachary Turner   if (!name_token)
9142c1f46dcSZachary Turner     sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
9152c1f46dcSZachary Turner   else
9162c1f46dcSZachary Turner     sstr.Printf("%s_%p", base_name_wanted, name_token);
9172c1f46dcSZachary Turner 
918adcd0268SBenjamin Kramer   return std::string(sstr.GetString());
9192c1f46dcSZachary Turner }
9202c1f46dcSZachary Turner 
92163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
922f8b22f8fSZachary Turner   if (m_run_one_line_function.IsValid())
923f8b22f8fSZachary Turner     return true;
924f8b22f8fSZachary Turner 
925b9c1b51eSKate Stone   PythonObject module(PyRefType::Borrowed,
926b9c1b51eSKate Stone                       PyImport_AddModule("lldb.embedded_interpreter"));
927f8b22f8fSZachary Turner   if (!module.IsValid())
928f8b22f8fSZachary Turner     return false;
929f8b22f8fSZachary Turner 
930b9c1b51eSKate Stone   PythonDictionary module_dict(PyRefType::Borrowed,
931b9c1b51eSKate Stone                                PyModule_GetDict(module.get()));
932f8b22f8fSZachary Turner   if (!module_dict.IsValid())
933f8b22f8fSZachary Turner     return false;
934f8b22f8fSZachary Turner 
935b9c1b51eSKate Stone   m_run_one_line_function =
936b9c1b51eSKate Stone       module_dict.GetItemForKey(PythonString("run_one_line"));
937b9c1b51eSKate Stone   m_run_one_line_str_global =
938b9c1b51eSKate Stone       module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
939f8b22f8fSZachary Turner   return m_run_one_line_function.IsValid();
9402c1f46dcSZachary Turner }
9412c1f46dcSZachary Turner 
94263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLine(
9434d51a902SRaphael Isemann     llvm::StringRef command, CommandReturnObject *result,
944b9c1b51eSKate Stone     const ExecuteScriptOptions &options) {
945d6c062bcSRaphael Isemann   std::string command_str = command.str();
946d6c062bcSRaphael Isemann 
9472c1f46dcSZachary Turner   if (!m_valid_session)
9482c1f46dcSZachary Turner     return false;
9492c1f46dcSZachary Turner 
9504d51a902SRaphael Isemann   if (!command.empty()) {
951b9c1b51eSKate Stone     // We want to call run_one_line, passing in the dictionary and the command
95205097246SAdrian Prantl     // string.  We cannot do this through PyRun_SimpleString here because the
95305097246SAdrian Prantl     // command string may contain escaped characters, and putting it inside
954b9c1b51eSKate Stone     // another string to pass to PyRun_SimpleString messes up the escaping.  So
95505097246SAdrian Prantl     // we use the following more complicated method to pass the command string
95605097246SAdrian Prantl     // directly down to Python.
957d79273c9SJonas Devlieghere     llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
95884228365SJonas Devlieghere         io_redirect_or_error = ScriptInterpreterIORedirect::Create(
95984228365SJonas Devlieghere             options.GetEnableIO(), m_debugger, result);
960d79273c9SJonas Devlieghere     if (!io_redirect_or_error) {
961d79273c9SJonas Devlieghere       if (result)
962d79273c9SJonas Devlieghere         result->AppendErrorWithFormatv(
963d79273c9SJonas Devlieghere             "failed to redirect I/O: {0}\n",
964d79273c9SJonas Devlieghere             llvm::fmt_consume(io_redirect_or_error.takeError()));
965d79273c9SJonas Devlieghere       else
966d79273c9SJonas Devlieghere         llvm::consumeError(io_redirect_or_error.takeError());
9672fce1137SLawrence D'Anna       return false;
9682fce1137SLawrence D'Anna     }
969d79273c9SJonas Devlieghere 
970d79273c9SJonas Devlieghere     ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
9712c1f46dcSZachary Turner 
97232064024SZachary Turner     bool success = false;
97332064024SZachary Turner     {
97405097246SAdrian Prantl       // WARNING!  It's imperative that this RAII scope be as tight as
97505097246SAdrian Prantl       // possible. In particular, the scope must end *before* we try to join
97605097246SAdrian Prantl       // the read thread.  The reason for this is that a pre-requisite for
97705097246SAdrian Prantl       // joining the read thread is that we close the write handle (to break
97805097246SAdrian Prantl       // the pipe and cause it to wake up and exit).  But acquiring the GIL as
97905097246SAdrian Prantl       // below will redirect Python's stdio to use this same handle.  If we
98005097246SAdrian Prantl       // close the handle while Python is still using it, bad things will
98105097246SAdrian Prantl       // happen.
982b9c1b51eSKate Stone       Locker locker(
983b9c1b51eSKate Stone           this,
98463dd5d25SJonas Devlieghere           Locker::AcquireLock | Locker::InitSession |
98563dd5d25SJonas Devlieghere               (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
9862c1f46dcSZachary Turner               ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
987d79273c9SJonas Devlieghere           Locker::FreeAcquiredLock | Locker::TearDownSession,
988d79273c9SJonas Devlieghere           io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
989d79273c9SJonas Devlieghere           io_redirect.GetErrorFile());
9902c1f46dcSZachary Turner 
9912c1f46dcSZachary Turner       // Find the correct script interpreter dictionary in the main module.
9922c1f46dcSZachary Turner       PythonDictionary &session_dict = GetSessionDictionary();
993b9c1b51eSKate Stone       if (session_dict.IsValid()) {
994b9c1b51eSKate Stone         if (GetEmbeddedInterpreterModuleObjects()) {
995b9c1b51eSKate Stone           if (PyCallable_Check(m_run_one_line_function.get())) {
996b9c1b51eSKate Stone             PythonObject pargs(
997b9c1b51eSKate Stone                 PyRefType::Owned,
998d6c062bcSRaphael Isemann                 Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
999b9c1b51eSKate Stone             if (pargs.IsValid()) {
1000b9c1b51eSKate Stone               PythonObject return_value(
1001b9c1b51eSKate Stone                   PyRefType::Owned,
1002b9c1b51eSKate Stone                   PyObject_CallObject(m_run_one_line_function.get(),
1003b9c1b51eSKate Stone                                       pargs.get()));
1004f8b22f8fSZachary Turner               if (return_value.IsValid())
10052c1f46dcSZachary Turner                 success = true;
1006b9c1b51eSKate Stone               else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
10072c1f46dcSZachary Turner                 PyErr_Print();
10082c1f46dcSZachary Turner                 PyErr_Clear();
10092c1f46dcSZachary Turner               }
10102c1f46dcSZachary Turner             }
10112c1f46dcSZachary Turner           }
10122c1f46dcSZachary Turner         }
10132c1f46dcSZachary Turner       }
10142c1f46dcSZachary Turner 
1015d79273c9SJonas Devlieghere       io_redirect.Flush();
10162c1f46dcSZachary Turner     }
10172c1f46dcSZachary Turner 
10182c1f46dcSZachary Turner     if (success)
10192c1f46dcSZachary Turner       return true;
10202c1f46dcSZachary Turner 
10212c1f46dcSZachary Turner     // The one-liner failed.  Append the error message.
10224d51a902SRaphael Isemann     if (result) {
1023b9c1b51eSKate Stone       result->AppendErrorWithFormat(
10244d51a902SRaphael Isemann           "python failed attempting to evaluate '%s'\n", command_str.c_str());
10254d51a902SRaphael Isemann     }
10262c1f46dcSZachary Turner     return false;
10272c1f46dcSZachary Turner   }
10282c1f46dcSZachary Turner 
10292c1f46dcSZachary Turner   if (result)
10302c1f46dcSZachary Turner     result->AppendError("empty command passed to python\n");
10312c1f46dcSZachary Turner   return false;
10322c1f46dcSZachary Turner }
10332c1f46dcSZachary Turner 
103463dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
10355c1c8443SJonas Devlieghere   LLDB_SCOPED_TIMER();
10362c1f46dcSZachary Turner 
10378d1fb843SJonas Devlieghere   Debugger &debugger = m_debugger;
10382c1f46dcSZachary Turner 
1039b9c1b51eSKate Stone   // At the moment, the only time the debugger does not have an input file
104005097246SAdrian Prantl   // handle is when this is called directly from Python, in which case it is
104105097246SAdrian Prantl   // both dangerous and unnecessary (not to mention confusing) to try to embed
104205097246SAdrian Prantl   // a running interpreter loop inside the already running Python interpreter
104305097246SAdrian Prantl   // loop, so we won't do it.
10442c1f46dcSZachary Turner 
10457ca15ba7SLawrence D'Anna   if (!debugger.GetInputFile().IsValid())
10462c1f46dcSZachary Turner     return;
10472c1f46dcSZachary Turner 
10482c1f46dcSZachary Turner   IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
1049b9c1b51eSKate Stone   if (io_handler_sp) {
10507ce2de2cSJonas Devlieghere     debugger.RunIOHandlerAsync(io_handler_sp);
10512c1f46dcSZachary Turner   }
10522c1f46dcSZachary Turner }
10532c1f46dcSZachary Turner 
105463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Interrupt() {
10552c1f46dcSZachary Turner   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
10562c1f46dcSZachary Turner 
1057b9c1b51eSKate Stone   if (IsExecutingPython()) {
1058b1cf558dSEnrico Granata     PyThreadState *state = PyThreadState_GET();
10592c1f46dcSZachary Turner     if (!state)
10602c1f46dcSZachary Turner       state = GetThreadState();
1061b9c1b51eSKate Stone     if (state) {
10622c1f46dcSZachary Turner       long tid = state->thread_id;
106322c8efcdSZachary Turner       PyThreadState_Swap(state);
10642c1f46dcSZachary Turner       int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
106563e5fb76SJonas Devlieghere       LLDB_LOGF(log,
106663e5fb76SJonas Devlieghere                 "ScriptInterpreterPythonImpl::Interrupt() sending "
1067b9c1b51eSKate Stone                 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
1068b9c1b51eSKate Stone                 tid, num_threads);
10692c1f46dcSZachary Turner       return true;
10702c1f46dcSZachary Turner     }
10712c1f46dcSZachary Turner   }
107263e5fb76SJonas Devlieghere   LLDB_LOGF(log,
107363dd5d25SJonas Devlieghere             "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
1074b9c1b51eSKate Stone             "can't interrupt");
10752c1f46dcSZachary Turner   return false;
10762c1f46dcSZachary Turner }
107704edd189SLawrence D'Anna 
107863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
10794d51a902SRaphael Isemann     llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
1080b9c1b51eSKate Stone     void *ret_value, const ExecuteScriptOptions &options) {
10812c1f46dcSZachary Turner 
108263dd5d25SJonas Devlieghere   Locker locker(this,
108363dd5d25SJonas Devlieghere                 Locker::AcquireLock | Locker::InitSession |
108463dd5d25SJonas Devlieghere                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1085b9c1b51eSKate Stone                     Locker::NoSTDIN,
108663dd5d25SJonas Devlieghere                 Locker::FreeAcquiredLock | Locker::TearDownSession);
10872c1f46dcSZachary Turner 
108804edd189SLawrence D'Anna   PythonModule &main_module = GetMainModule();
108904edd189SLawrence D'Anna   PythonDictionary globals = main_module.GetDictionary();
10902c1f46dcSZachary Turner 
10912c1f46dcSZachary Turner   PythonDictionary locals = GetSessionDictionary();
109204edd189SLawrence D'Anna   if (!locals.IsValid())
1093722b6189SLawrence D'Anna     locals = unwrapIgnoringErrors(
1094722b6189SLawrence D'Anna         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1095f8b22f8fSZachary Turner   if (!locals.IsValid())
10962c1f46dcSZachary Turner     locals = globals;
10972c1f46dcSZachary Turner 
109804edd189SLawrence D'Anna   Expected<PythonObject> maybe_py_return =
109904edd189SLawrence D'Anna       runStringOneLine(in_string, globals, locals);
11002c1f46dcSZachary Turner 
110104edd189SLawrence D'Anna   if (!maybe_py_return) {
110204edd189SLawrence D'Anna     llvm::handleAllErrors(
110304edd189SLawrence D'Anna         maybe_py_return.takeError(),
110404edd189SLawrence D'Anna         [&](PythonException &E) {
110504edd189SLawrence D'Anna           E.Restore();
110604edd189SLawrence D'Anna           if (options.GetMaskoutErrors()) {
110704edd189SLawrence D'Anna             if (E.Matches(PyExc_SyntaxError)) {
110804edd189SLawrence D'Anna               PyErr_Print();
11092c1f46dcSZachary Turner             }
111004edd189SLawrence D'Anna             PyErr_Clear();
111104edd189SLawrence D'Anna           }
111204edd189SLawrence D'Anna         },
111304edd189SLawrence D'Anna         [](const llvm::ErrorInfoBase &E) {});
111404edd189SLawrence D'Anna     return false;
11152c1f46dcSZachary Turner   }
11162c1f46dcSZachary Turner 
111704edd189SLawrence D'Anna   PythonObject py_return = std::move(maybe_py_return.get());
111804edd189SLawrence D'Anna   assert(py_return.IsValid());
111904edd189SLawrence D'Anna 
1120b9c1b51eSKate Stone   switch (return_type) {
11212c1f46dcSZachary Turner   case eScriptReturnTypeCharPtr: // "char *"
11222c1f46dcSZachary Turner   {
11232c1f46dcSZachary Turner     const char format[3] = "s#";
112404edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
11252c1f46dcSZachary Turner   }
1126b9c1b51eSKate Stone   case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
1127b9c1b51eSKate Stone                                        // Py_None
11282c1f46dcSZachary Turner   {
11292c1f46dcSZachary Turner     const char format[3] = "z";
113004edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
11312c1f46dcSZachary Turner   }
1132b9c1b51eSKate Stone   case eScriptReturnTypeBool: {
11332c1f46dcSZachary Turner     const char format[2] = "b";
113404edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
11352c1f46dcSZachary Turner   }
1136b9c1b51eSKate Stone   case eScriptReturnTypeShortInt: {
11372c1f46dcSZachary Turner     const char format[2] = "h";
113804edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (short *)ret_value);
11392c1f46dcSZachary Turner   }
1140b9c1b51eSKate Stone   case eScriptReturnTypeShortIntUnsigned: {
11412c1f46dcSZachary Turner     const char format[2] = "H";
114204edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
11432c1f46dcSZachary Turner   }
1144b9c1b51eSKate Stone   case eScriptReturnTypeInt: {
11452c1f46dcSZachary Turner     const char format[2] = "i";
114604edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (int *)ret_value);
11472c1f46dcSZachary Turner   }
1148b9c1b51eSKate Stone   case eScriptReturnTypeIntUnsigned: {
11492c1f46dcSZachary Turner     const char format[2] = "I";
115004edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
11512c1f46dcSZachary Turner   }
1152b9c1b51eSKate Stone   case eScriptReturnTypeLongInt: {
11532c1f46dcSZachary Turner     const char format[2] = "l";
115404edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (long *)ret_value);
11552c1f46dcSZachary Turner   }
1156b9c1b51eSKate Stone   case eScriptReturnTypeLongIntUnsigned: {
11572c1f46dcSZachary Turner     const char format[2] = "k";
115804edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
11592c1f46dcSZachary Turner   }
1160b9c1b51eSKate Stone   case eScriptReturnTypeLongLong: {
11612c1f46dcSZachary Turner     const char format[2] = "L";
116204edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
11632c1f46dcSZachary Turner   }
1164b9c1b51eSKate Stone   case eScriptReturnTypeLongLongUnsigned: {
11652c1f46dcSZachary Turner     const char format[2] = "K";
116604edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format,
116704edd189SLawrence D'Anna                        (unsigned long long *)ret_value);
11682c1f46dcSZachary Turner   }
1169b9c1b51eSKate Stone   case eScriptReturnTypeFloat: {
11702c1f46dcSZachary Turner     const char format[2] = "f";
117104edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (float *)ret_value);
11722c1f46dcSZachary Turner   }
1173b9c1b51eSKate Stone   case eScriptReturnTypeDouble: {
11742c1f46dcSZachary Turner     const char format[2] = "d";
117504edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (double *)ret_value);
11762c1f46dcSZachary Turner   }
1177b9c1b51eSKate Stone   case eScriptReturnTypeChar: {
11782c1f46dcSZachary Turner     const char format[2] = "c";
117904edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (char *)ret_value);
11802c1f46dcSZachary Turner   }
1181b9c1b51eSKate Stone   case eScriptReturnTypeOpaqueObject: {
118204edd189SLawrence D'Anna     *((PyObject **)ret_value) = py_return.release();
118304edd189SLawrence D'Anna     return true;
11842c1f46dcSZachary Turner   }
11852c1f46dcSZachary Turner   }
11861dfb1a85SPavel Labath   llvm_unreachable("Fully covered switch!");
11872c1f46dcSZachary Turner }
11882c1f46dcSZachary Turner 
118963dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1190b9c1b51eSKate Stone     const char *in_string, const ExecuteScriptOptions &options) {
119104edd189SLawrence D'Anna 
119204edd189SLawrence D'Anna   if (in_string == nullptr)
119304edd189SLawrence D'Anna     return Status();
11942c1f46dcSZachary Turner 
119563dd5d25SJonas Devlieghere   Locker locker(this,
119663dd5d25SJonas Devlieghere                 Locker::AcquireLock | Locker::InitSession |
119763dd5d25SJonas Devlieghere                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1198b9c1b51eSKate Stone                     Locker::NoSTDIN,
119963dd5d25SJonas Devlieghere                 Locker::FreeAcquiredLock | Locker::TearDownSession);
12002c1f46dcSZachary Turner 
120104edd189SLawrence D'Anna   PythonModule &main_module = GetMainModule();
120204edd189SLawrence D'Anna   PythonDictionary globals = main_module.GetDictionary();
12032c1f46dcSZachary Turner 
12042c1f46dcSZachary Turner   PythonDictionary locals = GetSessionDictionary();
1205f8b22f8fSZachary Turner   if (!locals.IsValid())
1206722b6189SLawrence D'Anna     locals = unwrapIgnoringErrors(
1207722b6189SLawrence D'Anna         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1208f8b22f8fSZachary Turner   if (!locals.IsValid())
12092c1f46dcSZachary Turner     locals = globals;
12102c1f46dcSZachary Turner 
121104edd189SLawrence D'Anna   Expected<PythonObject> return_value =
121204edd189SLawrence D'Anna       runStringMultiLine(in_string, globals, locals);
12132c1f46dcSZachary Turner 
121404edd189SLawrence D'Anna   if (!return_value) {
121504edd189SLawrence D'Anna     llvm::Error error =
121604edd189SLawrence D'Anna         llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
121704edd189SLawrence D'Anna           llvm::Error error = llvm::createStringError(
121804edd189SLawrence D'Anna               llvm::inconvertibleErrorCode(), E.ReadBacktrace());
121904edd189SLawrence D'Anna           if (!options.GetMaskoutErrors())
122004edd189SLawrence D'Anna             E.Restore();
12212c1f46dcSZachary Turner           return error;
122204edd189SLawrence D'Anna         });
122304edd189SLawrence D'Anna     return Status(std::move(error));
122404edd189SLawrence D'Anna   }
122504edd189SLawrence D'Anna 
122604edd189SLawrence D'Anna   return Status();
12272c1f46dcSZachary Turner }
12282c1f46dcSZachary Turner 
122963dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1230b9c1b51eSKate Stone     std::vector<BreakpointOptions *> &bp_options_vec,
1231b9c1b51eSKate Stone     CommandReturnObject &result) {
12322c1f46dcSZachary Turner   m_active_io_handler = eIOHandlerBreakpoint;
12338d1fb843SJonas Devlieghere   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1234a6faf851SJonas Devlieghere       "    ", *this, &bp_options_vec);
12352c1f46dcSZachary Turner }
12362c1f46dcSZachary Turner 
123763dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1238b9c1b51eSKate Stone     WatchpointOptions *wp_options, CommandReturnObject &result) {
12392c1f46dcSZachary Turner   m_active_io_handler = eIOHandlerWatchpoint;
12408d1fb843SJonas Devlieghere   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1241a6faf851SJonas Devlieghere       "    ", *this, wp_options);
12422c1f46dcSZachary Turner }
12432c1f46dcSZachary Turner 
1244738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1245738af7a6SJim Ingham     BreakpointOptions *bp_options, const char *function_name,
1246738af7a6SJim Ingham     StructuredData::ObjectSP extra_args_sp) {
1247738af7a6SJim Ingham   Status error;
12482c1f46dcSZachary Turner   // For now just cons up a oneliner that calls the provided function.
12492c1f46dcSZachary Turner   std::string oneliner("return ");
12502c1f46dcSZachary Turner   oneliner += function_name;
1251738af7a6SJim Ingham 
1252a69bbe02SLawrence D'Anna   llvm::Expected<unsigned> maybe_args =
1253a69bbe02SLawrence D'Anna       GetMaxPositionalArgumentsForCallable(function_name);
1254738af7a6SJim Ingham   if (!maybe_args) {
1255a69bbe02SLawrence D'Anna     error.SetErrorStringWithFormat(
1256a69bbe02SLawrence D'Anna         "could not get num args: %s",
1257738af7a6SJim Ingham         llvm::toString(maybe_args.takeError()).c_str());
1258738af7a6SJim Ingham     return error;
1259738af7a6SJim Ingham   }
1260a69bbe02SLawrence D'Anna   size_t max_args = *maybe_args;
1261738af7a6SJim Ingham 
1262738af7a6SJim Ingham   bool uses_extra_args = false;
1263a69bbe02SLawrence D'Anna   if (max_args >= 4) {
1264738af7a6SJim Ingham     uses_extra_args = true;
1265738af7a6SJim Ingham     oneliner += "(frame, bp_loc, extra_args, internal_dict)";
1266a69bbe02SLawrence D'Anna   } else if (max_args >= 3) {
1267738af7a6SJim Ingham     if (extra_args_sp) {
1268738af7a6SJim Ingham       error.SetErrorString("cannot pass extra_args to a three argument callback"
1269738af7a6SJim Ingham                           );
1270738af7a6SJim Ingham       return error;
1271738af7a6SJim Ingham     }
1272738af7a6SJim Ingham     uses_extra_args = false;
12732c1f46dcSZachary Turner     oneliner += "(frame, bp_loc, internal_dict)";
1274738af7a6SJim Ingham   } else {
1275738af7a6SJim Ingham     error.SetErrorStringWithFormat("expected 3 or 4 argument "
1276a69bbe02SLawrence D'Anna                                    "function, %s can only take %zu",
1277a69bbe02SLawrence D'Anna                                    function_name, max_args);
1278738af7a6SJim Ingham     return error;
1279738af7a6SJim Ingham   }
1280738af7a6SJim Ingham 
1281738af7a6SJim Ingham   SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp,
1282738af7a6SJim Ingham                                uses_extra_args);
1283738af7a6SJim Ingham   return error;
12842c1f46dcSZachary Turner }
12852c1f46dcSZachary Turner 
128663dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1287f7e07256SJim Ingham     BreakpointOptions *bp_options,
1288f7e07256SJim Ingham     std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
128997206d57SZachary Turner   Status error;
1290f7e07256SJim Ingham   error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1291738af7a6SJim Ingham                                                 cmd_data_up->script_source,
1292738af7a6SJim Ingham                                                 false);
1293f7e07256SJim Ingham   if (error.Fail()) {
1294f7e07256SJim Ingham     return error;
1295f7e07256SJim Ingham   }
1296f7e07256SJim Ingham   auto baton_sp =
1297f7e07256SJim Ingham       std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
129863dd5d25SJonas Devlieghere   bp_options->SetCallback(
129963dd5d25SJonas Devlieghere       ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1300f7e07256SJim Ingham   return error;
1301f7e07256SJim Ingham }
1302f7e07256SJim Ingham 
130363dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1304b9c1b51eSKate Stone     BreakpointOptions *bp_options, const char *command_body_text) {
1305738af7a6SJim Ingham   return SetBreakpointCommandCallback(bp_options, command_body_text, {},false);
1306738af7a6SJim Ingham }
13072c1f46dcSZachary Turner 
1308738af7a6SJim Ingham // Set a Python one-liner as the callback for the breakpoint.
1309738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1310738af7a6SJim Ingham     BreakpointOptions *bp_options, const char *command_body_text,
1311738af7a6SJim Ingham     StructuredData::ObjectSP extra_args_sp,
1312738af7a6SJim Ingham     bool uses_extra_args) {
1313738af7a6SJim Ingham   auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1314b9c1b51eSKate Stone   // Split the command_body_text into lines, and pass that to
131505097246SAdrian Prantl   // GenerateBreakpointCommandCallbackData.  That will wrap the body in an
131605097246SAdrian Prantl   // auto-generated function, and return the function name in script_source.
131705097246SAdrian Prantl   // That is what the callback will actually invoke.
13182c1f46dcSZachary Turner 
1319d5b44036SJonas Devlieghere   data_up->user_source.SplitIntoLines(command_body_text);
1320d5b44036SJonas Devlieghere   Status error = GenerateBreakpointCommandCallbackData(data_up->user_source,
1321738af7a6SJim Ingham                                                        data_up->script_source,
1322738af7a6SJim Ingham                                                        uses_extra_args);
1323b9c1b51eSKate Stone   if (error.Success()) {
13244e4fbe82SZachary Turner     auto baton_sp =
1325d5b44036SJonas Devlieghere         std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
132663dd5d25SJonas Devlieghere     bp_options->SetCallback(
132763dd5d25SJonas Devlieghere         ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
13282c1f46dcSZachary Turner     return error;
132993571c3cSJonas Devlieghere   }
13302c1f46dcSZachary Turner   return error;
13312c1f46dcSZachary Turner }
13322c1f46dcSZachary Turner 
13332c1f46dcSZachary Turner // Set a Python one-liner as the callback for the watchpoint.
133463dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1335b9c1b51eSKate Stone     WatchpointOptions *wp_options, const char *oneliner) {
1336a8f3ae7cSJonas Devlieghere   auto data_up = std::make_unique<WatchpointOptions::CommandData>();
13372c1f46dcSZachary Turner 
13382c1f46dcSZachary Turner   // It's necessary to set both user_source and script_source to the oneliner.
1339b9c1b51eSKate Stone   // The former is used to generate callback description (as in watchpoint
134005097246SAdrian Prantl   // command list) while the latter is used for Python to interpret during the
134105097246SAdrian Prantl   // actual callback.
13422c1f46dcSZachary Turner 
1343d5b44036SJonas Devlieghere   data_up->user_source.AppendString(oneliner);
1344d5b44036SJonas Devlieghere   data_up->script_source.assign(oneliner);
13452c1f46dcSZachary Turner 
1346d5b44036SJonas Devlieghere   if (GenerateWatchpointCommandCallbackData(data_up->user_source,
1347d5b44036SJonas Devlieghere                                             data_up->script_source)) {
13484e4fbe82SZachary Turner     auto baton_sp =
1349d5b44036SJonas Devlieghere         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
135063dd5d25SJonas Devlieghere     wp_options->SetCallback(
135163dd5d25SJonas Devlieghere         ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
13522c1f46dcSZachary Turner   }
13532c1f46dcSZachary Turner 
13542c1f46dcSZachary Turner   return;
13552c1f46dcSZachary Turner }
13562c1f46dcSZachary Turner 
135763dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1358b9c1b51eSKate Stone     StringList &function_def) {
13592c1f46dcSZachary Turner   // Convert StringList to one long, newline delimited, const char *.
13602c1f46dcSZachary Turner   std::string function_def_string(function_def.CopyList());
13612c1f46dcSZachary Turner 
136297206d57SZachary Turner   Status error = ExecuteMultipleLines(
1363b9c1b51eSKate Stone       function_def_string.c_str(),
1364b9c1b51eSKate Stone       ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false));
13652c1f46dcSZachary Turner   return error;
13662c1f46dcSZachary Turner }
13672c1f46dcSZachary Turner 
136863dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature,
1369b9c1b51eSKate Stone                                                      const StringList &input) {
137097206d57SZachary Turner   Status error;
13712c1f46dcSZachary Turner   int num_lines = input.GetSize();
1372b9c1b51eSKate Stone   if (num_lines == 0) {
13732c1f46dcSZachary Turner     error.SetErrorString("No input data.");
13742c1f46dcSZachary Turner     return error;
13752c1f46dcSZachary Turner   }
13762c1f46dcSZachary Turner 
1377b9c1b51eSKate Stone   if (!signature || *signature == 0) {
13782c1f46dcSZachary Turner     error.SetErrorString("No output function name.");
13792c1f46dcSZachary Turner     return error;
13802c1f46dcSZachary Turner   }
13812c1f46dcSZachary Turner 
13822c1f46dcSZachary Turner   StreamString sstr;
13832c1f46dcSZachary Turner   StringList auto_generated_function;
13842c1f46dcSZachary Turner   auto_generated_function.AppendString(signature);
1385b9c1b51eSKate Stone   auto_generated_function.AppendString(
1386b9c1b51eSKate Stone       "     global_dict = globals()"); // Grab the global dictionary
1387b9c1b51eSKate Stone   auto_generated_function.AppendString(
1388b9c1b51eSKate Stone       "     new_keys = internal_dict.keys()"); // Make a list of keys in the
1389b9c1b51eSKate Stone                                                // session dict
1390b9c1b51eSKate Stone   auto_generated_function.AppendString(
1391b9c1b51eSKate Stone       "     old_keys = global_dict.keys()"); // Save list of keys in global dict
1392b9c1b51eSKate Stone   auto_generated_function.AppendString(
1393b9c1b51eSKate Stone       "     global_dict.update (internal_dict)"); // Add the session dictionary
1394b9c1b51eSKate Stone                                                   // to the
13952c1f46dcSZachary Turner   // global dictionary.
13962c1f46dcSZachary Turner 
13972c1f46dcSZachary Turner   // Wrap everything up inside the function, increasing the indentation.
13982c1f46dcSZachary Turner 
13992c1f46dcSZachary Turner   auto_generated_function.AppendString("     if True:");
1400b9c1b51eSKate Stone   for (int i = 0; i < num_lines; ++i) {
14012c1f46dcSZachary Turner     sstr.Clear();
14022c1f46dcSZachary Turner     sstr.Printf("       %s", input.GetStringAtIndex(i));
14032c1f46dcSZachary Turner     auto_generated_function.AppendString(sstr.GetData());
14042c1f46dcSZachary Turner   }
1405b9c1b51eSKate Stone   auto_generated_function.AppendString(
1406b9c1b51eSKate Stone       "     for key in new_keys:"); // Iterate over all the keys from session
1407b9c1b51eSKate Stone                                     // dict
1408b9c1b51eSKate Stone   auto_generated_function.AppendString(
1409b9c1b51eSKate Stone       "         internal_dict[key] = global_dict[key]"); // Update session dict
1410b9c1b51eSKate Stone                                                          // values
1411b9c1b51eSKate Stone   auto_generated_function.AppendString(
1412b9c1b51eSKate Stone       "         if key not in old_keys:"); // If key was not originally in
1413b9c1b51eSKate Stone                                            // global dict
1414b9c1b51eSKate Stone   auto_generated_function.AppendString(
1415b9c1b51eSKate Stone       "             del global_dict[key]"); //  ...then remove key/value from
1416b9c1b51eSKate Stone                                             //  global dict
14172c1f46dcSZachary Turner 
14182c1f46dcSZachary Turner   // Verify that the results are valid Python.
14192c1f46dcSZachary Turner 
14202c1f46dcSZachary Turner   error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
14212c1f46dcSZachary Turner 
14222c1f46dcSZachary Turner   return error;
14232c1f46dcSZachary Turner }
14242c1f46dcSZachary Turner 
142563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1426b9c1b51eSKate Stone     StringList &user_input, std::string &output, const void *name_token) {
14272c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
14282c1f46dcSZachary Turner   user_input.RemoveBlankLines();
14292c1f46dcSZachary Turner   StreamString sstr;
14302c1f46dcSZachary Turner 
14312c1f46dcSZachary Turner   // Check to see if we have any data; if not, just return.
14322c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
14332c1f46dcSZachary Turner     return false;
14342c1f46dcSZachary Turner 
1435b9c1b51eSKate Stone   // Take what the user wrote, wrap it all up inside one big auto-generated
143605097246SAdrian Prantl   // Python function, passing in the ValueObject as parameter to the function.
14372c1f46dcSZachary Turner 
1438b9c1b51eSKate Stone   std::string auto_generated_function_name(
1439b9c1b51eSKate Stone       GenerateUniqueName("lldb_autogen_python_type_print_func",
1440b9c1b51eSKate Stone                          num_created_functions, name_token));
1441b9c1b51eSKate Stone   sstr.Printf("def %s (valobj, internal_dict):",
1442b9c1b51eSKate Stone               auto_generated_function_name.c_str());
14432c1f46dcSZachary Turner 
14442c1f46dcSZachary Turner   if (!GenerateFunction(sstr.GetData(), user_input).Success())
14452c1f46dcSZachary Turner     return false;
14462c1f46dcSZachary Turner 
14472c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
14482c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
14492c1f46dcSZachary Turner   return true;
14502c1f46dcSZachary Turner }
14512c1f46dcSZachary Turner 
145263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1453b9c1b51eSKate Stone     StringList &user_input, std::string &output) {
14542c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
14552c1f46dcSZachary Turner   user_input.RemoveBlankLines();
14562c1f46dcSZachary Turner   StreamString sstr;
14572c1f46dcSZachary Turner 
14582c1f46dcSZachary Turner   // Check to see if we have any data; if not, just return.
14592c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
14602c1f46dcSZachary Turner     return false;
14612c1f46dcSZachary Turner 
1462b9c1b51eSKate Stone   std::string auto_generated_function_name(GenerateUniqueName(
1463b9c1b51eSKate Stone       "lldb_autogen_python_cmd_alias_func", num_created_functions));
14642c1f46dcSZachary Turner 
1465b9c1b51eSKate Stone   sstr.Printf("def %s (debugger, args, result, internal_dict):",
1466b9c1b51eSKate Stone               auto_generated_function_name.c_str());
14672c1f46dcSZachary Turner 
14682c1f46dcSZachary Turner   if (!GenerateFunction(sstr.GetData(), user_input).Success())
14692c1f46dcSZachary Turner     return false;
14702c1f46dcSZachary Turner 
14712c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
14722c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
14732c1f46dcSZachary Turner   return true;
14742c1f46dcSZachary Turner }
14752c1f46dcSZachary Turner 
147663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
147763dd5d25SJonas Devlieghere     StringList &user_input, std::string &output, const void *name_token) {
14782c1f46dcSZachary Turner   static uint32_t num_created_classes = 0;
14792c1f46dcSZachary Turner   user_input.RemoveBlankLines();
14802c1f46dcSZachary Turner   int num_lines = user_input.GetSize();
14812c1f46dcSZachary Turner   StreamString sstr;
14822c1f46dcSZachary Turner 
14832c1f46dcSZachary Turner   // Check to see if we have any data; if not, just return.
14842c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
14852c1f46dcSZachary Turner     return false;
14862c1f46dcSZachary Turner 
14872c1f46dcSZachary Turner   // Wrap all user input into a Python class
14882c1f46dcSZachary Turner 
1489b9c1b51eSKate Stone   std::string auto_generated_class_name(GenerateUniqueName(
1490b9c1b51eSKate Stone       "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
14912c1f46dcSZachary Turner 
14922c1f46dcSZachary Turner   StringList auto_generated_class;
14932c1f46dcSZachary Turner 
14942c1f46dcSZachary Turner   // Create the function name & definition string.
14952c1f46dcSZachary Turner 
14962c1f46dcSZachary Turner   sstr.Printf("class %s:", auto_generated_class_name.c_str());
1497c156427dSZachary Turner   auto_generated_class.AppendString(sstr.GetString());
14982c1f46dcSZachary Turner 
149905097246SAdrian Prantl   // Wrap everything up inside the class, increasing the indentation. we don't
150005097246SAdrian Prantl   // need to play any fancy indentation tricks here because there is no
15012c1f46dcSZachary Turner   // surrounding code whose indentation we need to honor
1502b9c1b51eSKate Stone   for (int i = 0; i < num_lines; ++i) {
15032c1f46dcSZachary Turner     sstr.Clear();
15042c1f46dcSZachary Turner     sstr.Printf("     %s", user_input.GetStringAtIndex(i));
1505c156427dSZachary Turner     auto_generated_class.AppendString(sstr.GetString());
15062c1f46dcSZachary Turner   }
15072c1f46dcSZachary Turner 
150805097246SAdrian Prantl   // Verify that the results are valid Python. (even though the method is
150905097246SAdrian Prantl   // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
15102c1f46dcSZachary Turner   // (TODO: rename that method to ExportDefinitionToInterpreter)
15112c1f46dcSZachary Turner   if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
15122c1f46dcSZachary Turner     return false;
15132c1f46dcSZachary Turner 
15142c1f46dcSZachary Turner   // Store the name of the auto-generated class
15152c1f46dcSZachary Turner 
15162c1f46dcSZachary Turner   output.assign(auto_generated_class_name);
15172c1f46dcSZachary Turner   return true;
15182c1f46dcSZachary Turner }
15192c1f46dcSZachary Turner 
152063dd5d25SJonas Devlieghere StructuredData::GenericSP
152163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
152241ae8e74SKuba Mracek   if (class_name == nullptr || class_name[0] == '\0')
152341ae8e74SKuba Mracek     return StructuredData::GenericSP();
152441ae8e74SKuba Mracek 
152541ae8e74SKuba Mracek   void *ret_val;
152641ae8e74SKuba Mracek 
152741ae8e74SKuba Mracek   {
152841ae8e74SKuba Mracek     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
152941ae8e74SKuba Mracek                    Locker::FreeLock);
153005495c5dSJonas Devlieghere     ret_val = LLDBSWIGPython_CreateFrameRecognizer(class_name,
153105495c5dSJonas Devlieghere                                                    m_dictionary_name.c_str());
153241ae8e74SKuba Mracek   }
153341ae8e74SKuba Mracek 
153441ae8e74SKuba Mracek   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
153541ae8e74SKuba Mracek }
153641ae8e74SKuba Mracek 
153763dd5d25SJonas Devlieghere lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
153841ae8e74SKuba Mracek     const StructuredData::ObjectSP &os_plugin_object_sp,
153941ae8e74SKuba Mracek     lldb::StackFrameSP frame_sp) {
154041ae8e74SKuba Mracek   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
154141ae8e74SKuba Mracek 
154263dd5d25SJonas Devlieghere   if (!os_plugin_object_sp)
154363dd5d25SJonas Devlieghere     return ValueObjectListSP();
154441ae8e74SKuba Mracek 
154541ae8e74SKuba Mracek   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
154663dd5d25SJonas Devlieghere   if (!generic)
154763dd5d25SJonas Devlieghere     return nullptr;
154841ae8e74SKuba Mracek 
154941ae8e74SKuba Mracek   PythonObject implementor(PyRefType::Borrowed,
155041ae8e74SKuba Mracek                            (PyObject *)generic->GetValue());
155141ae8e74SKuba Mracek 
155263dd5d25SJonas Devlieghere   if (!implementor.IsAllocated())
155363dd5d25SJonas Devlieghere     return ValueObjectListSP();
155441ae8e74SKuba Mracek 
155505495c5dSJonas Devlieghere   PythonObject py_return(PyRefType::Owned,
155605495c5dSJonas Devlieghere                          (PyObject *)LLDBSwigPython_GetRecognizedArguments(
155705495c5dSJonas Devlieghere                              implementor.get(), frame_sp));
155841ae8e74SKuba Mracek 
155941ae8e74SKuba Mracek   // if it fails, print the error but otherwise go on
156041ae8e74SKuba Mracek   if (PyErr_Occurred()) {
156141ae8e74SKuba Mracek     PyErr_Print();
156241ae8e74SKuba Mracek     PyErr_Clear();
156341ae8e74SKuba Mracek   }
156441ae8e74SKuba Mracek   if (py_return.get()) {
156541ae8e74SKuba Mracek     PythonList result_list(PyRefType::Borrowed, py_return.get());
156641ae8e74SKuba Mracek     ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
15678f81aed1SDavid Bolvansky     for (size_t i = 0; i < result_list.GetSize(); i++) {
156841ae8e74SKuba Mracek       PyObject *item = result_list.GetItemAtIndex(i).get();
156941ae8e74SKuba Mracek       lldb::SBValue *sb_value_ptr =
157005495c5dSJonas Devlieghere           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
157105495c5dSJonas Devlieghere       auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
157263dd5d25SJonas Devlieghere       if (valobj_sp)
157363dd5d25SJonas Devlieghere         result->Append(valobj_sp);
157441ae8e74SKuba Mracek     }
157541ae8e74SKuba Mracek     return result;
157641ae8e74SKuba Mracek   }
157741ae8e74SKuba Mracek   return ValueObjectListSP();
157841ae8e74SKuba Mracek }
157941ae8e74SKuba Mracek 
158063dd5d25SJonas Devlieghere StructuredData::GenericSP
158163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject(
1582b9c1b51eSKate Stone     const char *class_name, lldb::ProcessSP process_sp) {
15832c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
15842c1f46dcSZachary Turner     return StructuredData::GenericSP();
15852c1f46dcSZachary Turner 
15862c1f46dcSZachary Turner   if (!process_sp)
15872c1f46dcSZachary Turner     return StructuredData::GenericSP();
15882c1f46dcSZachary Turner 
15892c1f46dcSZachary Turner   void *ret_val;
15902c1f46dcSZachary Turner 
15912c1f46dcSZachary Turner   {
1592b9c1b51eSKate Stone     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
15932c1f46dcSZachary Turner                    Locker::FreeLock);
159405495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonCreateOSPlugin(
159505495c5dSJonas Devlieghere         class_name, m_dictionary_name.c_str(), process_sp);
15962c1f46dcSZachary Turner   }
15972c1f46dcSZachary Turner 
15982c1f46dcSZachary Turner   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
15992c1f46dcSZachary Turner }
16002c1f46dcSZachary Turner 
160163dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo(
1602b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp) {
1603b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
16042c1f46dcSZachary Turner 
16052c1f46dcSZachary Turner   static char callee_name[] = "get_register_info";
16062c1f46dcSZachary Turner 
16072c1f46dcSZachary Turner   if (!os_plugin_object_sp)
16082c1f46dcSZachary Turner     return StructuredData::DictionarySP();
16092c1f46dcSZachary Turner 
16102c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
16112c1f46dcSZachary Turner   if (!generic)
16122c1f46dcSZachary Turner     return nullptr;
16132c1f46dcSZachary Turner 
1614b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1615b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
16162c1f46dcSZachary Turner 
1617f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
16182c1f46dcSZachary Turner     return StructuredData::DictionarySP();
16192c1f46dcSZachary Turner 
1620b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1621b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
16222c1f46dcSZachary Turner 
16232c1f46dcSZachary Turner   if (PyErr_Occurred())
16242c1f46dcSZachary Turner     PyErr_Clear();
16252c1f46dcSZachary Turner 
1626f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
16272c1f46dcSZachary Turner     return StructuredData::DictionarySP();
16282c1f46dcSZachary Turner 
1629b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
16302c1f46dcSZachary Turner     if (PyErr_Occurred())
16312c1f46dcSZachary Turner       PyErr_Clear();
16322c1f46dcSZachary Turner 
16332c1f46dcSZachary Turner     return StructuredData::DictionarySP();
16342c1f46dcSZachary Turner   }
16352c1f46dcSZachary Turner 
16362c1f46dcSZachary Turner   if (PyErr_Occurred())
16372c1f46dcSZachary Turner     PyErr_Clear();
16382c1f46dcSZachary Turner 
16392c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1640b9c1b51eSKate Stone   PythonObject py_return(
1641b9c1b51eSKate Stone       PyRefType::Owned,
1642b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
16432c1f46dcSZachary Turner 
16442c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1645b9c1b51eSKate Stone   if (PyErr_Occurred()) {
16462c1f46dcSZachary Turner     PyErr_Print();
16472c1f46dcSZachary Turner     PyErr_Clear();
16482c1f46dcSZachary Turner   }
1649b9c1b51eSKate Stone   if (py_return.get()) {
1650f8b22f8fSZachary Turner     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
16512c1f46dcSZachary Turner     return result_dict.CreateStructuredDictionary();
16522c1f46dcSZachary Turner   }
165358b794aeSGreg Clayton   return StructuredData::DictionarySP();
165458b794aeSGreg Clayton }
16552c1f46dcSZachary Turner 
165663dd5d25SJonas Devlieghere StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo(
1657b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp) {
1658b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
16592c1f46dcSZachary Turner 
16602c1f46dcSZachary Turner   static char callee_name[] = "get_thread_info";
16612c1f46dcSZachary Turner 
16622c1f46dcSZachary Turner   if (!os_plugin_object_sp)
16632c1f46dcSZachary Turner     return StructuredData::ArraySP();
16642c1f46dcSZachary Turner 
16652c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
16662c1f46dcSZachary Turner   if (!generic)
16672c1f46dcSZachary Turner     return nullptr;
16682c1f46dcSZachary Turner 
1669b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1670b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
1671f8b22f8fSZachary Turner 
1672f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
16732c1f46dcSZachary Turner     return StructuredData::ArraySP();
16742c1f46dcSZachary Turner 
1675b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1676b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
16772c1f46dcSZachary Turner 
16782c1f46dcSZachary Turner   if (PyErr_Occurred())
16792c1f46dcSZachary Turner     PyErr_Clear();
16802c1f46dcSZachary Turner 
1681f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
16822c1f46dcSZachary Turner     return StructuredData::ArraySP();
16832c1f46dcSZachary Turner 
1684b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
16852c1f46dcSZachary Turner     if (PyErr_Occurred())
16862c1f46dcSZachary Turner       PyErr_Clear();
16872c1f46dcSZachary Turner 
16882c1f46dcSZachary Turner     return StructuredData::ArraySP();
16892c1f46dcSZachary Turner   }
16902c1f46dcSZachary Turner 
16912c1f46dcSZachary Turner   if (PyErr_Occurred())
16922c1f46dcSZachary Turner     PyErr_Clear();
16932c1f46dcSZachary Turner 
16942c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1695b9c1b51eSKate Stone   PythonObject py_return(
1696b9c1b51eSKate Stone       PyRefType::Owned,
1697b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
16982c1f46dcSZachary Turner 
16992c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1700b9c1b51eSKate Stone   if (PyErr_Occurred()) {
17012c1f46dcSZachary Turner     PyErr_Print();
17022c1f46dcSZachary Turner     PyErr_Clear();
17032c1f46dcSZachary Turner   }
17042c1f46dcSZachary Turner 
1705b9c1b51eSKate Stone   if (py_return.get()) {
1706f8b22f8fSZachary Turner     PythonList result_list(PyRefType::Borrowed, py_return.get());
1707f8b22f8fSZachary Turner     return result_list.CreateStructuredArray();
17082c1f46dcSZachary Turner   }
170958b794aeSGreg Clayton   return StructuredData::ArraySP();
171058b794aeSGreg Clayton }
17112c1f46dcSZachary Turner 
171263dd5d25SJonas Devlieghere StructuredData::StringSP
171363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData(
1714b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
1715b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
17162c1f46dcSZachary Turner 
17172c1f46dcSZachary Turner   static char callee_name[] = "get_register_data";
1718b9c1b51eSKate Stone   static char *param_format =
1719b9c1b51eSKate Stone       const_cast<char *>(GetPythonValueFormatString(tid));
17202c1f46dcSZachary Turner 
17212c1f46dcSZachary Turner   if (!os_plugin_object_sp)
17222c1f46dcSZachary Turner     return StructuredData::StringSP();
17232c1f46dcSZachary Turner 
17242c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
17252c1f46dcSZachary Turner   if (!generic)
17262c1f46dcSZachary Turner     return nullptr;
1727b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1728b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
17292c1f46dcSZachary Turner 
1730f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
17312c1f46dcSZachary Turner     return StructuredData::StringSP();
17322c1f46dcSZachary Turner 
1733b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1734b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
17352c1f46dcSZachary Turner 
17362c1f46dcSZachary Turner   if (PyErr_Occurred())
17372c1f46dcSZachary Turner     PyErr_Clear();
17382c1f46dcSZachary Turner 
1739f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
17402c1f46dcSZachary Turner     return StructuredData::StringSP();
17412c1f46dcSZachary Turner 
1742b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
17432c1f46dcSZachary Turner     if (PyErr_Occurred())
17442c1f46dcSZachary Turner       PyErr_Clear();
17452c1f46dcSZachary Turner     return StructuredData::StringSP();
17462c1f46dcSZachary Turner   }
17472c1f46dcSZachary Turner 
17482c1f46dcSZachary Turner   if (PyErr_Occurred())
17492c1f46dcSZachary Turner     PyErr_Clear();
17502c1f46dcSZachary Turner 
17512c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1752b9c1b51eSKate Stone   PythonObject py_return(
1753b9c1b51eSKate Stone       PyRefType::Owned,
1754b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, param_format, tid));
17552c1f46dcSZachary Turner 
17562c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1757b9c1b51eSKate Stone   if (PyErr_Occurred()) {
17582c1f46dcSZachary Turner     PyErr_Print();
17592c1f46dcSZachary Turner     PyErr_Clear();
17602c1f46dcSZachary Turner   }
1761f8b22f8fSZachary Turner 
1762b9c1b51eSKate Stone   if (py_return.get()) {
17637a76845cSZachary Turner     PythonBytes result(PyRefType::Borrowed, py_return.get());
17647a76845cSZachary Turner     return result.CreateStructuredString();
17652c1f46dcSZachary Turner   }
176658b794aeSGreg Clayton   return StructuredData::StringSP();
176758b794aeSGreg Clayton }
17682c1f46dcSZachary Turner 
176963dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread(
1770b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
1771b9c1b51eSKate Stone     lldb::addr_t context) {
1772b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
17732c1f46dcSZachary Turner 
17742c1f46dcSZachary Turner   static char callee_name[] = "create_thread";
17752c1f46dcSZachary Turner   std::string param_format;
17762c1f46dcSZachary Turner   param_format += GetPythonValueFormatString(tid);
17772c1f46dcSZachary Turner   param_format += GetPythonValueFormatString(context);
17782c1f46dcSZachary Turner 
17792c1f46dcSZachary Turner   if (!os_plugin_object_sp)
17802c1f46dcSZachary Turner     return StructuredData::DictionarySP();
17812c1f46dcSZachary Turner 
17822c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
17832c1f46dcSZachary Turner   if (!generic)
17842c1f46dcSZachary Turner     return nullptr;
17852c1f46dcSZachary Turner 
1786b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1787b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
1788f8b22f8fSZachary Turner 
1789f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
17902c1f46dcSZachary Turner     return StructuredData::DictionarySP();
17912c1f46dcSZachary Turner 
1792b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1793b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
17942c1f46dcSZachary Turner 
17952c1f46dcSZachary Turner   if (PyErr_Occurred())
17962c1f46dcSZachary Turner     PyErr_Clear();
17972c1f46dcSZachary Turner 
1798f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
17992c1f46dcSZachary Turner     return StructuredData::DictionarySP();
18002c1f46dcSZachary Turner 
1801b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
18022c1f46dcSZachary Turner     if (PyErr_Occurred())
18032c1f46dcSZachary Turner       PyErr_Clear();
18042c1f46dcSZachary Turner     return StructuredData::DictionarySP();
18052c1f46dcSZachary Turner   }
18062c1f46dcSZachary Turner 
18072c1f46dcSZachary Turner   if (PyErr_Occurred())
18082c1f46dcSZachary Turner     PyErr_Clear();
18092c1f46dcSZachary Turner 
18102c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1811b9c1b51eSKate Stone   PythonObject py_return(PyRefType::Owned,
1812b9c1b51eSKate Stone                          PyObject_CallMethod(implementor.get(), callee_name,
1813b9c1b51eSKate Stone                                              &param_format[0], tid, context));
18142c1f46dcSZachary Turner 
18152c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1816b9c1b51eSKate Stone   if (PyErr_Occurred()) {
18172c1f46dcSZachary Turner     PyErr_Print();
18182c1f46dcSZachary Turner     PyErr_Clear();
18192c1f46dcSZachary Turner   }
18202c1f46dcSZachary Turner 
1821b9c1b51eSKate Stone   if (py_return.get()) {
1822f8b22f8fSZachary Turner     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
18232c1f46dcSZachary Turner     return result_dict.CreateStructuredDictionary();
18242c1f46dcSZachary Turner   }
182558b794aeSGreg Clayton   return StructuredData::DictionarySP();
182658b794aeSGreg Clayton }
18272c1f46dcSZachary Turner 
182863dd5d25SJonas Devlieghere StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan(
182927a14f19SJim Ingham     const char *class_name, StructuredDataImpl *args_data,
1830a69bbe02SLawrence D'Anna     std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) {
18312c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
18322c1f46dcSZachary Turner     return StructuredData::ObjectSP();
18332c1f46dcSZachary Turner 
18342c1f46dcSZachary Turner   if (!thread_plan_sp.get())
183593c98346SJim Ingham     return {};
18362c1f46dcSZachary Turner 
18372c1f46dcSZachary Turner   Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
183863dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
1839d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
18402c1f46dcSZachary Turner 
1841d055e3a0SPedro Tammela   if (!python_interpreter)
184293c98346SJim Ingham     return {};
18432c1f46dcSZachary Turner 
18442c1f46dcSZachary Turner   void *ret_val;
18452c1f46dcSZachary Turner 
18462c1f46dcSZachary Turner   {
1847b9c1b51eSKate Stone     Locker py_lock(this,
1848b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
184905495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateScriptedThreadPlan(
1850b9c1b51eSKate Stone         class_name, python_interpreter->m_dictionary_name.c_str(),
185127a14f19SJim Ingham         args_data, error_str, thread_plan_sp);
185293c98346SJim Ingham     if (!ret_val)
185393c98346SJim Ingham       return {};
18542c1f46dcSZachary Turner   }
18552c1f46dcSZachary Turner 
18562c1f46dcSZachary Turner   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
18572c1f46dcSZachary Turner }
18582c1f46dcSZachary Turner 
185963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop(
1860b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
18612c1f46dcSZachary Turner   bool explains_stop = true;
18622c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
18632c1f46dcSZachary Turner   if (implementor_sp)
18642c1f46dcSZachary Turner     generic = implementor_sp->GetAsGeneric();
1865b9c1b51eSKate Stone   if (generic) {
1866b9c1b51eSKate Stone     Locker py_lock(this,
1867b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
186805495c5dSJonas Devlieghere     explains_stop = LLDBSWIGPythonCallThreadPlan(
1869b9c1b51eSKate Stone         generic->GetValue(), "explains_stop", event, script_error);
18702c1f46dcSZachary Turner     if (script_error)
18712c1f46dcSZachary Turner       return true;
18722c1f46dcSZachary Turner   }
18732c1f46dcSZachary Turner   return explains_stop;
18742c1f46dcSZachary Turner }
18752c1f46dcSZachary Turner 
187663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop(
1877b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
18782c1f46dcSZachary Turner   bool should_stop = true;
18792c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
18802c1f46dcSZachary Turner   if (implementor_sp)
18812c1f46dcSZachary Turner     generic = implementor_sp->GetAsGeneric();
1882b9c1b51eSKate Stone   if (generic) {
1883b9c1b51eSKate Stone     Locker py_lock(this,
1884b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
188505495c5dSJonas Devlieghere     should_stop = LLDBSWIGPythonCallThreadPlan(
188605495c5dSJonas Devlieghere         generic->GetValue(), "should_stop", event, script_error);
18872c1f46dcSZachary Turner     if (script_error)
18882c1f46dcSZachary Turner       return true;
18892c1f46dcSZachary Turner   }
18902c1f46dcSZachary Turner   return should_stop;
18912c1f46dcSZachary Turner }
18922c1f46dcSZachary Turner 
189363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale(
1894b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1895c915a7d2SJim Ingham   bool is_stale = true;
1896c915a7d2SJim Ingham   StructuredData::Generic *generic = nullptr;
1897c915a7d2SJim Ingham   if (implementor_sp)
1898c915a7d2SJim Ingham     generic = implementor_sp->GetAsGeneric();
1899b9c1b51eSKate Stone   if (generic) {
1900b9c1b51eSKate Stone     Locker py_lock(this,
1901b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
190205495c5dSJonas Devlieghere     is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale",
190305495c5dSJonas Devlieghere                                             nullptr, script_error);
1904c915a7d2SJim Ingham     if (script_error)
1905c915a7d2SJim Ingham       return true;
1906c915a7d2SJim Ingham   }
1907c915a7d2SJim Ingham   return is_stale;
1908c915a7d2SJim Ingham }
1909c915a7d2SJim Ingham 
191063dd5d25SJonas Devlieghere lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState(
1911b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, bool &script_error) {
19122c1f46dcSZachary Turner   bool should_step = false;
19132c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
19142c1f46dcSZachary Turner   if (implementor_sp)
19152c1f46dcSZachary Turner     generic = implementor_sp->GetAsGeneric();
1916b9c1b51eSKate Stone   if (generic) {
1917b9c1b51eSKate Stone     Locker py_lock(this,
1918b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
191905495c5dSJonas Devlieghere     should_step = LLDBSWIGPythonCallThreadPlan(
1920248a1305SKonrad Kleine         generic->GetValue(), "should_step", nullptr, script_error);
19212c1f46dcSZachary Turner     if (script_error)
19222c1f46dcSZachary Turner       should_step = true;
19232c1f46dcSZachary Turner   }
19242c1f46dcSZachary Turner   if (should_step)
19252c1f46dcSZachary Turner     return lldb::eStateStepping;
19262c1f46dcSZachary Turner   return lldb::eStateRunning;
19272c1f46dcSZachary Turner }
19282c1f46dcSZachary Turner 
19293815e702SJim Ingham StructuredData::GenericSP
193063dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
193163dd5d25SJonas Devlieghere     const char *class_name, StructuredDataImpl *args_data,
19323815e702SJim Ingham     lldb::BreakpointSP &bkpt_sp) {
19333815e702SJim Ingham 
19343815e702SJim Ingham   if (class_name == nullptr || class_name[0] == '\0')
19353815e702SJim Ingham     return StructuredData::GenericSP();
19363815e702SJim Ingham 
19373815e702SJim Ingham   if (!bkpt_sp.get())
19383815e702SJim Ingham     return StructuredData::GenericSP();
19393815e702SJim Ingham 
19403815e702SJim Ingham   Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
194163dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
1942d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
19433815e702SJim Ingham 
1944d055e3a0SPedro Tammela   if (!python_interpreter)
19453815e702SJim Ingham     return StructuredData::GenericSP();
19463815e702SJim Ingham 
19473815e702SJim Ingham   void *ret_val;
19483815e702SJim Ingham 
19493815e702SJim Ingham   {
19503815e702SJim Ingham     Locker py_lock(this,
19513815e702SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19523815e702SJim Ingham 
195305495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver(
195405495c5dSJonas Devlieghere         class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
195505495c5dSJonas Devlieghere         bkpt_sp);
19563815e702SJim Ingham   }
19573815e702SJim Ingham 
19583815e702SJim Ingham   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
19593815e702SJim Ingham }
19603815e702SJim Ingham 
196163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
196263dd5d25SJonas Devlieghere     StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
19633815e702SJim Ingham   bool should_continue = false;
19643815e702SJim Ingham 
19653815e702SJim Ingham   if (implementor_sp) {
19663815e702SJim Ingham     Locker py_lock(this,
19673815e702SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
196805495c5dSJonas Devlieghere     should_continue = LLDBSwigPythonCallBreakpointResolver(
196905495c5dSJonas Devlieghere         implementor_sp->GetValue(), "__callback__", sym_ctx);
19703815e702SJim Ingham     if (PyErr_Occurred()) {
19713815e702SJim Ingham       PyErr_Print();
19723815e702SJim Ingham       PyErr_Clear();
19733815e702SJim Ingham     }
19743815e702SJim Ingham   }
19753815e702SJim Ingham   return should_continue;
19763815e702SJim Ingham }
19773815e702SJim Ingham 
19783815e702SJim Ingham lldb::SearchDepth
197963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
19803815e702SJim Ingham     StructuredData::GenericSP implementor_sp) {
19813815e702SJim Ingham   int depth_as_int = lldb::eSearchDepthModule;
19823815e702SJim Ingham   if (implementor_sp) {
19833815e702SJim Ingham     Locker py_lock(this,
19843815e702SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
198505495c5dSJonas Devlieghere     depth_as_int = LLDBSwigPythonCallBreakpointResolver(
198605495c5dSJonas Devlieghere         implementor_sp->GetValue(), "__get_depth__", nullptr);
19873815e702SJim Ingham     if (PyErr_Occurred()) {
19883815e702SJim Ingham       PyErr_Print();
19893815e702SJim Ingham       PyErr_Clear();
19903815e702SJim Ingham     }
19913815e702SJim Ingham   }
19923815e702SJim Ingham   if (depth_as_int == lldb::eSearchDepthInvalid)
19933815e702SJim Ingham     return lldb::eSearchDepthModule;
19943815e702SJim Ingham 
19953815e702SJim Ingham   if (depth_as_int <= lldb::kLastSearchDepthKind)
19963815e702SJim Ingham     return (lldb::SearchDepth)depth_as_int;
19973815e702SJim Ingham   return lldb::eSearchDepthModule;
19983815e702SJim Ingham }
19993815e702SJim Ingham 
20001b1d9815SJim Ingham StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
20011b1d9815SJim Ingham     TargetSP target_sp, const char *class_name, StructuredDataImpl *args_data,
20021b1d9815SJim Ingham     Status &error) {
20031b1d9815SJim Ingham 
20041b1d9815SJim Ingham   if (!target_sp) {
20051b1d9815SJim Ingham     error.SetErrorString("No target for scripted stop-hook.");
20061b1d9815SJim Ingham     return StructuredData::GenericSP();
20071b1d9815SJim Ingham   }
20081b1d9815SJim Ingham 
20091b1d9815SJim Ingham   if (class_name == nullptr || class_name[0] == '\0') {
20101b1d9815SJim Ingham     error.SetErrorString("No class name for scripted stop-hook.");
20111b1d9815SJim Ingham     return StructuredData::GenericSP();
20121b1d9815SJim Ingham   }
20131b1d9815SJim Ingham 
20141b1d9815SJim Ingham   ScriptInterpreterPythonImpl *python_interpreter =
2015d055e3a0SPedro Tammela       GetPythonInterpreter(m_debugger);
20161b1d9815SJim Ingham 
2017d055e3a0SPedro Tammela   if (!python_interpreter) {
20181b1d9815SJim Ingham     error.SetErrorString("No script interpreter for scripted stop-hook.");
20191b1d9815SJim Ingham     return StructuredData::GenericSP();
20201b1d9815SJim Ingham   }
20211b1d9815SJim Ingham 
20221b1d9815SJim Ingham   void *ret_val;
20231b1d9815SJim Ingham 
20241b1d9815SJim Ingham   {
20251b1d9815SJim Ingham     Locker py_lock(this,
20261b1d9815SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
20271b1d9815SJim Ingham 
20281b1d9815SJim Ingham     ret_val = LLDBSwigPythonCreateScriptedStopHook(
20291b1d9815SJim Ingham         target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
20301b1d9815SJim Ingham         args_data, error);
20311b1d9815SJim Ingham   }
20321b1d9815SJim Ingham 
20331b1d9815SJim Ingham   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
20341b1d9815SJim Ingham }
20351b1d9815SJim Ingham 
20361b1d9815SJim Ingham bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
20371b1d9815SJim Ingham     StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
20381b1d9815SJim Ingham     lldb::StreamSP stream_sp) {
20391b1d9815SJim Ingham   assert(implementor_sp &&
20401b1d9815SJim Ingham          "can't call a stop hook with an invalid implementor");
20411b1d9815SJim Ingham   assert(stream_sp && "can't call a stop hook with an invalid stream");
20421b1d9815SJim Ingham 
20431b1d9815SJim Ingham   Locker py_lock(this,
20441b1d9815SJim Ingham                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
20451b1d9815SJim Ingham 
20461b1d9815SJim Ingham   lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
20471b1d9815SJim Ingham 
20481b1d9815SJim Ingham   bool ret_val = LLDBSwigPythonStopHookCallHandleStop(
20491b1d9815SJim Ingham       implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
20501b1d9815SJim Ingham   return ret_val;
20511b1d9815SJim Ingham }
20521b1d9815SJim Ingham 
20532c1f46dcSZachary Turner StructuredData::ObjectSP
205463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
205597206d57SZachary Turner                                               lldb_private::Status &error) {
2056dbd7fabaSJonas Devlieghere   if (!FileSystem::Instance().Exists(file_spec)) {
20572c1f46dcSZachary Turner     error.SetErrorString("no such file");
20582c1f46dcSZachary Turner     return StructuredData::ObjectSP();
20592c1f46dcSZachary Turner   }
20602c1f46dcSZachary Turner 
20612c1f46dcSZachary Turner   StructuredData::ObjectSP module_sp;
20622c1f46dcSZachary Turner 
206315625112SJonas Devlieghere   if (LoadScriptingModule(file_spec.GetPath().c_str(), true, error, &module_sp))
20642c1f46dcSZachary Turner     return module_sp;
20652c1f46dcSZachary Turner 
20662c1f46dcSZachary Turner   return StructuredData::ObjectSP();
20672c1f46dcSZachary Turner }
20682c1f46dcSZachary Turner 
206963dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
2070b9c1b51eSKate Stone     StructuredData::ObjectSP plugin_module_sp, Target *target,
207197206d57SZachary Turner     const char *setting_name, lldb_private::Status &error) {
207205495c5dSJonas Devlieghere   if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
20732c1f46dcSZachary Turner     return StructuredData::DictionarySP();
20742c1f46dcSZachary Turner   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
20752c1f46dcSZachary Turner   if (!generic)
20762c1f46dcSZachary Turner     return StructuredData::DictionarySP();
20772c1f46dcSZachary Turner 
2078b9c1b51eSKate Stone   Locker py_lock(this,
2079b9c1b51eSKate Stone                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
20802c1f46dcSZachary Turner   TargetSP target_sp(target->shared_from_this());
20812c1f46dcSZachary Turner 
208204edd189SLawrence D'Anna   auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting(
208304edd189SLawrence D'Anna       generic->GetValue(), setting_name, target_sp);
208404edd189SLawrence D'Anna 
208504edd189SLawrence D'Anna   if (!setting)
208604edd189SLawrence D'Anna     return StructuredData::DictionarySP();
208704edd189SLawrence D'Anna 
208804edd189SLawrence D'Anna   PythonDictionary py_dict =
208904edd189SLawrence D'Anna       unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
209004edd189SLawrence D'Anna 
209104edd189SLawrence D'Anna   if (!py_dict)
209204edd189SLawrence D'Anna     return StructuredData::DictionarySP();
209304edd189SLawrence D'Anna 
20942c1f46dcSZachary Turner   return py_dict.CreateStructuredDictionary();
20952c1f46dcSZachary Turner }
20962c1f46dcSZachary Turner 
20972c1f46dcSZachary Turner StructuredData::ObjectSP
209863dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
2099b9c1b51eSKate Stone     const char *class_name, lldb::ValueObjectSP valobj) {
21002c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
21012c1f46dcSZachary Turner     return StructuredData::ObjectSP();
21022c1f46dcSZachary Turner 
21032c1f46dcSZachary Turner   if (!valobj.get())
21042c1f46dcSZachary Turner     return StructuredData::ObjectSP();
21052c1f46dcSZachary Turner 
21062c1f46dcSZachary Turner   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
21072c1f46dcSZachary Turner   Target *target = exe_ctx.GetTargetPtr();
21082c1f46dcSZachary Turner 
21092c1f46dcSZachary Turner   if (!target)
21102c1f46dcSZachary Turner     return StructuredData::ObjectSP();
21112c1f46dcSZachary Turner 
21122c1f46dcSZachary Turner   Debugger &debugger = target->GetDebugger();
211363dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
2114d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
21152c1f46dcSZachary Turner 
2116d055e3a0SPedro Tammela   if (!python_interpreter)
21172c1f46dcSZachary Turner     return StructuredData::ObjectSP();
21182c1f46dcSZachary Turner 
21192c1f46dcSZachary Turner   void *ret_val = nullptr;
21202c1f46dcSZachary Turner 
21212c1f46dcSZachary Turner   {
2122b9c1b51eSKate Stone     Locker py_lock(this,
2123b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
212405495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateSyntheticProvider(
2125b9c1b51eSKate Stone         class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
21262c1f46dcSZachary Turner   }
21272c1f46dcSZachary Turner 
21282c1f46dcSZachary Turner   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
21292c1f46dcSZachary Turner }
21302c1f46dcSZachary Turner 
21312c1f46dcSZachary Turner StructuredData::GenericSP
213263dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
21338d1fb843SJonas Devlieghere   DebuggerSP debugger_sp(m_debugger.shared_from_this());
21342c1f46dcSZachary Turner 
21352c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
21362c1f46dcSZachary Turner     return StructuredData::GenericSP();
21372c1f46dcSZachary Turner 
21382c1f46dcSZachary Turner   if (!debugger_sp.get())
21392c1f46dcSZachary Turner     return StructuredData::GenericSP();
21402c1f46dcSZachary Turner 
21412c1f46dcSZachary Turner   void *ret_val;
21422c1f46dcSZachary Turner 
21432c1f46dcSZachary Turner   {
2144b9c1b51eSKate Stone     Locker py_lock(this,
2145b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
214605495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateCommandObject(
214705495c5dSJonas Devlieghere         class_name, m_dictionary_name.c_str(), debugger_sp);
21482c1f46dcSZachary Turner   }
21492c1f46dcSZachary Turner 
21502c1f46dcSZachary Turner   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
21512c1f46dcSZachary Turner }
21522c1f46dcSZachary Turner 
215363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
2154b9c1b51eSKate Stone     const char *oneliner, std::string &output, const void *name_token) {
21552c1f46dcSZachary Turner   StringList input;
21562c1f46dcSZachary Turner   input.SplitIntoLines(oneliner, strlen(oneliner));
21572c1f46dcSZachary Turner   return GenerateTypeScriptFunction(input, output, name_token);
21582c1f46dcSZachary Turner }
21592c1f46dcSZachary Turner 
216063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
216163dd5d25SJonas Devlieghere     const char *oneliner, std::string &output, const void *name_token) {
21622c1f46dcSZachary Turner   StringList input;
21632c1f46dcSZachary Turner   input.SplitIntoLines(oneliner, strlen(oneliner));
21642c1f46dcSZachary Turner   return GenerateTypeSynthClass(input, output, name_token);
21652c1f46dcSZachary Turner }
21662c1f46dcSZachary Turner 
216763dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
2168738af7a6SJim Ingham     StringList &user_input, std::string &output,
2169738af7a6SJim Ingham     bool has_extra_args) {
21702c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
21712c1f46dcSZachary Turner   user_input.RemoveBlankLines();
21722c1f46dcSZachary Turner   StreamString sstr;
217397206d57SZachary Turner   Status error;
2174b9c1b51eSKate Stone   if (user_input.GetSize() == 0) {
21752c1f46dcSZachary Turner     error.SetErrorString("No input data.");
21762c1f46dcSZachary Turner     return error;
21772c1f46dcSZachary Turner   }
21782c1f46dcSZachary Turner 
2179b9c1b51eSKate Stone   std::string auto_generated_function_name(GenerateUniqueName(
2180b9c1b51eSKate Stone       "lldb_autogen_python_bp_callback_func_", num_created_functions));
2181738af7a6SJim Ingham   if (has_extra_args)
2182738af7a6SJim Ingham     sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
2183738af7a6SJim Ingham                 auto_generated_function_name.c_str());
2184738af7a6SJim Ingham   else
2185b9c1b51eSKate Stone     sstr.Printf("def %s (frame, bp_loc, internal_dict):",
2186b9c1b51eSKate Stone                 auto_generated_function_name.c_str());
21872c1f46dcSZachary Turner 
21882c1f46dcSZachary Turner   error = GenerateFunction(sstr.GetData(), user_input);
21892c1f46dcSZachary Turner   if (!error.Success())
21902c1f46dcSZachary Turner     return error;
21912c1f46dcSZachary Turner 
21922c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
21932c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
21942c1f46dcSZachary Turner   return error;
21952c1f46dcSZachary Turner }
21962c1f46dcSZachary Turner 
219763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
2198b9c1b51eSKate Stone     StringList &user_input, std::string &output) {
21992c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
22002c1f46dcSZachary Turner   user_input.RemoveBlankLines();
22012c1f46dcSZachary Turner   StreamString sstr;
22022c1f46dcSZachary Turner 
22032c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
22042c1f46dcSZachary Turner     return false;
22052c1f46dcSZachary Turner 
2206b9c1b51eSKate Stone   std::string auto_generated_function_name(GenerateUniqueName(
2207b9c1b51eSKate Stone       "lldb_autogen_python_wp_callback_func_", num_created_functions));
2208b9c1b51eSKate Stone   sstr.Printf("def %s (frame, wp, internal_dict):",
2209b9c1b51eSKate Stone               auto_generated_function_name.c_str());
22102c1f46dcSZachary Turner 
22112c1f46dcSZachary Turner   if (!GenerateFunction(sstr.GetData(), user_input).Success())
22122c1f46dcSZachary Turner     return false;
22132c1f46dcSZachary Turner 
22142c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
22152c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
22162c1f46dcSZachary Turner   return true;
22172c1f46dcSZachary Turner }
22182c1f46dcSZachary Turner 
221963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetScriptedSummary(
2220b9c1b51eSKate Stone     const char *python_function_name, lldb::ValueObjectSP valobj,
2221b9c1b51eSKate Stone     StructuredData::ObjectSP &callee_wrapper_sp,
2222b9c1b51eSKate Stone     const TypeSummaryOptions &options, std::string &retval) {
22232c1f46dcSZachary Turner 
22245c1c8443SJonas Devlieghere   LLDB_SCOPED_TIMER();
22252c1f46dcSZachary Turner 
2226b9c1b51eSKate Stone   if (!valobj.get()) {
22272c1f46dcSZachary Turner     retval.assign("<no object>");
22282c1f46dcSZachary Turner     return false;
22292c1f46dcSZachary Turner   }
22302c1f46dcSZachary Turner 
22312c1f46dcSZachary Turner   void *old_callee = nullptr;
22322c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
2233b9c1b51eSKate Stone   if (callee_wrapper_sp) {
22342c1f46dcSZachary Turner     generic = callee_wrapper_sp->GetAsGeneric();
22352c1f46dcSZachary Turner     if (generic)
22362c1f46dcSZachary Turner       old_callee = generic->GetValue();
22372c1f46dcSZachary Turner   }
22382c1f46dcSZachary Turner   void *new_callee = old_callee;
22392c1f46dcSZachary Turner 
22402c1f46dcSZachary Turner   bool ret_val;
2241b9c1b51eSKate Stone   if (python_function_name && *python_function_name) {
22422c1f46dcSZachary Turner     {
2243b9c1b51eSKate Stone       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
2244b9c1b51eSKate Stone                                Locker::NoSTDIN);
22452c1f46dcSZachary Turner       {
22462c1f46dcSZachary Turner         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
22472c1f46dcSZachary Turner 
224805495c5dSJonas Devlieghere         static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
224905495c5dSJonas Devlieghere         Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
225005495c5dSJonas Devlieghere         ret_val = LLDBSwigPythonCallTypeScript(
2251b9c1b51eSKate Stone             python_function_name, GetSessionDictionary().get(), valobj,
2252b9c1b51eSKate Stone             &new_callee, options_sp, retval);
22532c1f46dcSZachary Turner       }
22542c1f46dcSZachary Turner     }
2255b9c1b51eSKate Stone   } else {
22562c1f46dcSZachary Turner     retval.assign("<no function name>");
22572c1f46dcSZachary Turner     return false;
22582c1f46dcSZachary Turner   }
22592c1f46dcSZachary Turner 
22602c1f46dcSZachary Turner   if (new_callee && old_callee != new_callee)
2261796ac80bSJonas Devlieghere     callee_wrapper_sp = std::make_shared<StructuredPythonObject>(new_callee);
22622c1f46dcSZachary Turner 
22632c1f46dcSZachary Turner   return ret_val;
22642c1f46dcSZachary Turner }
22652c1f46dcSZachary Turner 
226663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
2267b9c1b51eSKate Stone     void *baton, StoppointCallbackContext *context, user_id_t break_id,
2268b9c1b51eSKate Stone     user_id_t break_loc_id) {
2269f7e07256SJim Ingham   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
22702c1f46dcSZachary Turner   const char *python_function_name = bp_option_data->script_source.c_str();
22712c1f46dcSZachary Turner 
22722c1f46dcSZachary Turner   if (!context)
22732c1f46dcSZachary Turner     return true;
22742c1f46dcSZachary Turner 
22752c1f46dcSZachary Turner   ExecutionContext exe_ctx(context->exe_ctx_ref);
22762c1f46dcSZachary Turner   Target *target = exe_ctx.GetTargetPtr();
22772c1f46dcSZachary Turner 
22782c1f46dcSZachary Turner   if (!target)
22792c1f46dcSZachary Turner     return true;
22802c1f46dcSZachary Turner 
22812c1f46dcSZachary Turner   Debugger &debugger = target->GetDebugger();
228263dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
2283d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
22842c1f46dcSZachary Turner 
2285d055e3a0SPedro Tammela   if (!python_interpreter)
22862c1f46dcSZachary Turner     return true;
22872c1f46dcSZachary Turner 
2288b9c1b51eSKate Stone   if (python_function_name && python_function_name[0]) {
22892c1f46dcSZachary Turner     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
22902c1f46dcSZachary Turner     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2291b9c1b51eSKate Stone     if (breakpoint_sp) {
2292b9c1b51eSKate Stone       const BreakpointLocationSP bp_loc_sp(
2293b9c1b51eSKate Stone           breakpoint_sp->FindLocationByID(break_loc_id));
22942c1f46dcSZachary Turner 
2295b9c1b51eSKate Stone       if (stop_frame_sp && bp_loc_sp) {
22962c1f46dcSZachary Turner         bool ret_val = true;
22972c1f46dcSZachary Turner         {
2298b9c1b51eSKate Stone           Locker py_lock(python_interpreter, Locker::AcquireLock |
2299b9c1b51eSKate Stone                                                  Locker::InitSession |
2300b9c1b51eSKate Stone                                                  Locker::NoSTDIN);
2301a69bbe02SLawrence D'Anna           Expected<bool> maybe_ret_val =
2302a69bbe02SLawrence D'Anna               LLDBSwigPythonBreakpointCallbackFunction(
2303b9c1b51eSKate Stone                   python_function_name,
2304b9c1b51eSKate Stone                   python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2305a69bbe02SLawrence D'Anna                   bp_loc_sp, bp_option_data->m_extra_args_up.get());
2306a69bbe02SLawrence D'Anna 
2307a69bbe02SLawrence D'Anna           if (!maybe_ret_val) {
2308a69bbe02SLawrence D'Anna 
2309a69bbe02SLawrence D'Anna             llvm::handleAllErrors(
2310a69bbe02SLawrence D'Anna                 maybe_ret_val.takeError(),
2311a69bbe02SLawrence D'Anna                 [&](PythonException &E) {
2312a69bbe02SLawrence D'Anna                   debugger.GetErrorStream() << E.ReadBacktrace();
2313a69bbe02SLawrence D'Anna                 },
2314a69bbe02SLawrence D'Anna                 [&](const llvm::ErrorInfoBase &E) {
2315a69bbe02SLawrence D'Anna                   debugger.GetErrorStream() << E.message();
2316a69bbe02SLawrence D'Anna                 });
2317a69bbe02SLawrence D'Anna 
2318a69bbe02SLawrence D'Anna           } else {
2319a69bbe02SLawrence D'Anna             ret_val = maybe_ret_val.get();
2320a69bbe02SLawrence D'Anna           }
23212c1f46dcSZachary Turner         }
23222c1f46dcSZachary Turner         return ret_val;
23232c1f46dcSZachary Turner       }
23242c1f46dcSZachary Turner     }
23252c1f46dcSZachary Turner   }
23262c1f46dcSZachary Turner   // We currently always true so we stop in case anything goes wrong when
23272c1f46dcSZachary Turner   // trying to call the script function
23282c1f46dcSZachary Turner   return true;
23292c1f46dcSZachary Turner }
23302c1f46dcSZachary Turner 
233163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
2332b9c1b51eSKate Stone     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2333b9c1b51eSKate Stone   WatchpointOptions::CommandData *wp_option_data =
2334b9c1b51eSKate Stone       (WatchpointOptions::CommandData *)baton;
23352c1f46dcSZachary Turner   const char *python_function_name = wp_option_data->script_source.c_str();
23362c1f46dcSZachary Turner 
23372c1f46dcSZachary Turner   if (!context)
23382c1f46dcSZachary Turner     return true;
23392c1f46dcSZachary Turner 
23402c1f46dcSZachary Turner   ExecutionContext exe_ctx(context->exe_ctx_ref);
23412c1f46dcSZachary Turner   Target *target = exe_ctx.GetTargetPtr();
23422c1f46dcSZachary Turner 
23432c1f46dcSZachary Turner   if (!target)
23442c1f46dcSZachary Turner     return true;
23452c1f46dcSZachary Turner 
23462c1f46dcSZachary Turner   Debugger &debugger = target->GetDebugger();
234763dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
2348d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
23492c1f46dcSZachary Turner 
2350d055e3a0SPedro Tammela   if (!python_interpreter)
23512c1f46dcSZachary Turner     return true;
23522c1f46dcSZachary Turner 
2353b9c1b51eSKate Stone   if (python_function_name && python_function_name[0]) {
23542c1f46dcSZachary Turner     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
23552c1f46dcSZachary Turner     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2356b9c1b51eSKate Stone     if (wp_sp) {
2357b9c1b51eSKate Stone       if (stop_frame_sp && wp_sp) {
23582c1f46dcSZachary Turner         bool ret_val = true;
23592c1f46dcSZachary Turner         {
2360b9c1b51eSKate Stone           Locker py_lock(python_interpreter, Locker::AcquireLock |
2361b9c1b51eSKate Stone                                                  Locker::InitSession |
2362b9c1b51eSKate Stone                                                  Locker::NoSTDIN);
236305495c5dSJonas Devlieghere           ret_val = LLDBSwigPythonWatchpointCallbackFunction(
2364b9c1b51eSKate Stone               python_function_name,
2365b9c1b51eSKate Stone               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
23662c1f46dcSZachary Turner               wp_sp);
23672c1f46dcSZachary Turner         }
23682c1f46dcSZachary Turner         return ret_val;
23692c1f46dcSZachary Turner       }
23702c1f46dcSZachary Turner     }
23712c1f46dcSZachary Turner   }
23722c1f46dcSZachary Turner   // We currently always true so we stop in case anything goes wrong when
23732c1f46dcSZachary Turner   // trying to call the script function
23742c1f46dcSZachary Turner   return true;
23752c1f46dcSZachary Turner }
23762c1f46dcSZachary Turner 
237763dd5d25SJonas Devlieghere size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2378b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
23792c1f46dcSZachary Turner   if (!implementor_sp)
23802c1f46dcSZachary Turner     return 0;
23812c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
23822c1f46dcSZachary Turner   if (!generic)
23832c1f46dcSZachary Turner     return 0;
23842c1f46dcSZachary Turner   void *implementor = generic->GetValue();
23852c1f46dcSZachary Turner   if (!implementor)
23862c1f46dcSZachary Turner     return 0;
23872c1f46dcSZachary Turner 
23882c1f46dcSZachary Turner   size_t ret_val = 0;
23892c1f46dcSZachary Turner 
23902c1f46dcSZachary Turner   {
2391b9c1b51eSKate Stone     Locker py_lock(this,
2392b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
239305495c5dSJonas Devlieghere     ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max);
23942c1f46dcSZachary Turner   }
23952c1f46dcSZachary Turner 
23962c1f46dcSZachary Turner   return ret_val;
23972c1f46dcSZachary Turner }
23982c1f46dcSZachary Turner 
239963dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
2400b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
24012c1f46dcSZachary Turner   if (!implementor_sp)
24022c1f46dcSZachary Turner     return lldb::ValueObjectSP();
24032c1f46dcSZachary Turner 
24042c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24052c1f46dcSZachary Turner   if (!generic)
24062c1f46dcSZachary Turner     return lldb::ValueObjectSP();
24072c1f46dcSZachary Turner   void *implementor = generic->GetValue();
24082c1f46dcSZachary Turner   if (!implementor)
24092c1f46dcSZachary Turner     return lldb::ValueObjectSP();
24102c1f46dcSZachary Turner 
24112c1f46dcSZachary Turner   lldb::ValueObjectSP ret_val;
24122c1f46dcSZachary Turner   {
2413b9c1b51eSKate Stone     Locker py_lock(this,
2414b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
241505495c5dSJonas Devlieghere     void *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx);
2416b9c1b51eSKate Stone     if (child_ptr != nullptr && child_ptr != Py_None) {
2417b9c1b51eSKate Stone       lldb::SBValue *sb_value_ptr =
241805495c5dSJonas Devlieghere           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
24192c1f46dcSZachary Turner       if (sb_value_ptr == nullptr)
24202c1f46dcSZachary Turner         Py_XDECREF(child_ptr);
24212c1f46dcSZachary Turner       else
242205495c5dSJonas Devlieghere         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2423b9c1b51eSKate Stone     } else {
24242c1f46dcSZachary Turner       Py_XDECREF(child_ptr);
24252c1f46dcSZachary Turner     }
24262c1f46dcSZachary Turner   }
24272c1f46dcSZachary Turner 
24282c1f46dcSZachary Turner   return ret_val;
24292c1f46dcSZachary Turner }
24302c1f46dcSZachary Turner 
243163dd5d25SJonas Devlieghere int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2432b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
24332c1f46dcSZachary Turner   if (!implementor_sp)
24342c1f46dcSZachary Turner     return UINT32_MAX;
24352c1f46dcSZachary Turner 
24362c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24372c1f46dcSZachary Turner   if (!generic)
24382c1f46dcSZachary Turner     return UINT32_MAX;
24392c1f46dcSZachary Turner   void *implementor = generic->GetValue();
24402c1f46dcSZachary Turner   if (!implementor)
24412c1f46dcSZachary Turner     return UINT32_MAX;
24422c1f46dcSZachary Turner 
24432c1f46dcSZachary Turner   int ret_val = UINT32_MAX;
24442c1f46dcSZachary Turner 
24452c1f46dcSZachary Turner   {
2446b9c1b51eSKate Stone     Locker py_lock(this,
2447b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
244805495c5dSJonas Devlieghere     ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
24492c1f46dcSZachary Turner   }
24502c1f46dcSZachary Turner 
24512c1f46dcSZachary Turner   return ret_val;
24522c1f46dcSZachary Turner }
24532c1f46dcSZachary Turner 
245463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2455b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
24562c1f46dcSZachary Turner   bool ret_val = false;
24572c1f46dcSZachary Turner 
24582c1f46dcSZachary Turner   if (!implementor_sp)
24592c1f46dcSZachary Turner     return ret_val;
24602c1f46dcSZachary Turner 
24612c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24622c1f46dcSZachary Turner   if (!generic)
24632c1f46dcSZachary Turner     return ret_val;
24642c1f46dcSZachary Turner   void *implementor = generic->GetValue();
24652c1f46dcSZachary Turner   if (!implementor)
24662c1f46dcSZachary Turner     return ret_val;
24672c1f46dcSZachary Turner 
24682c1f46dcSZachary Turner   {
2469b9c1b51eSKate Stone     Locker py_lock(this,
2470b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
247105495c5dSJonas Devlieghere     ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor);
24722c1f46dcSZachary Turner   }
24732c1f46dcSZachary Turner 
24742c1f46dcSZachary Turner   return ret_val;
24752c1f46dcSZachary Turner }
24762c1f46dcSZachary Turner 
247763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2478b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
24792c1f46dcSZachary Turner   bool ret_val = false;
24802c1f46dcSZachary Turner 
24812c1f46dcSZachary Turner   if (!implementor_sp)
24822c1f46dcSZachary Turner     return ret_val;
24832c1f46dcSZachary Turner 
24842c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24852c1f46dcSZachary Turner   if (!generic)
24862c1f46dcSZachary Turner     return ret_val;
24872c1f46dcSZachary Turner   void *implementor = generic->GetValue();
24882c1f46dcSZachary Turner   if (!implementor)
24892c1f46dcSZachary Turner     return ret_val;
24902c1f46dcSZachary Turner 
24912c1f46dcSZachary Turner   {
2492b9c1b51eSKate Stone     Locker py_lock(this,
2493b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
249405495c5dSJonas Devlieghere     ret_val =
249505495c5dSJonas Devlieghere         LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor);
24962c1f46dcSZachary Turner   }
24972c1f46dcSZachary Turner 
24982c1f46dcSZachary Turner   return ret_val;
24992c1f46dcSZachary Turner }
25002c1f46dcSZachary Turner 
250163dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
2502b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
25032c1f46dcSZachary Turner   lldb::ValueObjectSP ret_val(nullptr);
25042c1f46dcSZachary Turner 
25052c1f46dcSZachary Turner   if (!implementor_sp)
25062c1f46dcSZachary Turner     return ret_val;
25072c1f46dcSZachary Turner 
25082c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
25092c1f46dcSZachary Turner   if (!generic)
25102c1f46dcSZachary Turner     return ret_val;
25112c1f46dcSZachary Turner   void *implementor = generic->GetValue();
25122c1f46dcSZachary Turner   if (!implementor)
25132c1f46dcSZachary Turner     return ret_val;
25142c1f46dcSZachary Turner 
25152c1f46dcSZachary Turner   {
2516b9c1b51eSKate Stone     Locker py_lock(this,
2517b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
251805495c5dSJonas Devlieghere     void *child_ptr = LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2519b9c1b51eSKate Stone     if (child_ptr != nullptr && child_ptr != Py_None) {
2520b9c1b51eSKate Stone       lldb::SBValue *sb_value_ptr =
252105495c5dSJonas Devlieghere           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
25222c1f46dcSZachary Turner       if (sb_value_ptr == nullptr)
25232c1f46dcSZachary Turner         Py_XDECREF(child_ptr);
25242c1f46dcSZachary Turner       else
252505495c5dSJonas Devlieghere         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2526b9c1b51eSKate Stone     } else {
25272c1f46dcSZachary Turner       Py_XDECREF(child_ptr);
25282c1f46dcSZachary Turner     }
25292c1f46dcSZachary Turner   }
25302c1f46dcSZachary Turner 
25312c1f46dcSZachary Turner   return ret_val;
25322c1f46dcSZachary Turner }
25332c1f46dcSZachary Turner 
253463dd5d25SJonas Devlieghere ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2535b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
2536b9c1b51eSKate Stone   Locker py_lock(this,
2537b9c1b51eSKate Stone                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
25386eec8d6cSEnrico Granata 
25396eec8d6cSEnrico Granata   static char callee_name[] = "get_type_name";
25406eec8d6cSEnrico Granata 
25416eec8d6cSEnrico Granata   ConstString ret_val;
25426eec8d6cSEnrico Granata   bool got_string = false;
25436eec8d6cSEnrico Granata   std::string buffer;
25446eec8d6cSEnrico Granata 
25456eec8d6cSEnrico Granata   if (!implementor_sp)
25466eec8d6cSEnrico Granata     return ret_val;
25476eec8d6cSEnrico Granata 
25486eec8d6cSEnrico Granata   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
25496eec8d6cSEnrico Granata   if (!generic)
25506eec8d6cSEnrico Granata     return ret_val;
2551b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
2552b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
25536eec8d6cSEnrico Granata   if (!implementor.IsAllocated())
25546eec8d6cSEnrico Granata     return ret_val;
25556eec8d6cSEnrico Granata 
2556b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
2557b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
25586eec8d6cSEnrico Granata 
25596eec8d6cSEnrico Granata   if (PyErr_Occurred())
25606eec8d6cSEnrico Granata     PyErr_Clear();
25616eec8d6cSEnrico Granata 
25626eec8d6cSEnrico Granata   if (!pmeth.IsAllocated())
25636eec8d6cSEnrico Granata     return ret_val;
25646eec8d6cSEnrico Granata 
2565b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
25666eec8d6cSEnrico Granata     if (PyErr_Occurred())
25676eec8d6cSEnrico Granata       PyErr_Clear();
25686eec8d6cSEnrico Granata     return ret_val;
25696eec8d6cSEnrico Granata   }
25706eec8d6cSEnrico Granata 
25716eec8d6cSEnrico Granata   if (PyErr_Occurred())
25726eec8d6cSEnrico Granata     PyErr_Clear();
25736eec8d6cSEnrico Granata 
25746eec8d6cSEnrico Granata   // right now we know this function exists and is callable..
2575b9c1b51eSKate Stone   PythonObject py_return(
2576b9c1b51eSKate Stone       PyRefType::Owned,
2577b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
25786eec8d6cSEnrico Granata 
25796eec8d6cSEnrico Granata   // if it fails, print the error but otherwise go on
2580b9c1b51eSKate Stone   if (PyErr_Occurred()) {
25816eec8d6cSEnrico Granata     PyErr_Print();
25826eec8d6cSEnrico Granata     PyErr_Clear();
25836eec8d6cSEnrico Granata   }
25846eec8d6cSEnrico Granata 
2585b9c1b51eSKate Stone   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
25866eec8d6cSEnrico Granata     PythonString py_string(PyRefType::Borrowed, py_return.get());
25876eec8d6cSEnrico Granata     llvm::StringRef return_data(py_string.GetString());
2588b9c1b51eSKate Stone     if (!return_data.empty()) {
25896eec8d6cSEnrico Granata       buffer.assign(return_data.data(), return_data.size());
25906eec8d6cSEnrico Granata       got_string = true;
25916eec8d6cSEnrico Granata     }
25926eec8d6cSEnrico Granata   }
25936eec8d6cSEnrico Granata 
25946eec8d6cSEnrico Granata   if (got_string)
25956eec8d6cSEnrico Granata     ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
25966eec8d6cSEnrico Granata 
25976eec8d6cSEnrico Granata   return ret_val;
25986eec8d6cSEnrico Granata }
25996eec8d6cSEnrico Granata 
260063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
260163dd5d25SJonas Devlieghere     const char *impl_function, Process *process, std::string &output,
260297206d57SZachary Turner     Status &error) {
26032c1f46dcSZachary Turner   bool ret_val;
2604b9c1b51eSKate Stone   if (!process) {
26052c1f46dcSZachary Turner     error.SetErrorString("no process");
26062c1f46dcSZachary Turner     return false;
26072c1f46dcSZachary Turner   }
2608b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
26092c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
26102c1f46dcSZachary Turner     return false;
26112c1f46dcSZachary Turner   }
261205495c5dSJonas Devlieghere 
26132c1f46dcSZachary Turner   {
26142c1f46dcSZachary Turner     ProcessSP process_sp(process->shared_from_this());
2615b9c1b51eSKate Stone     Locker py_lock(this,
2616b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
261705495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordProcess(
2618b9c1b51eSKate Stone         impl_function, m_dictionary_name.c_str(), process_sp, output);
26192c1f46dcSZachary Turner     if (!ret_val)
26202c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
26212c1f46dcSZachary Turner   }
26222c1f46dcSZachary Turner   return ret_val;
26232c1f46dcSZachary Turner }
26242c1f46dcSZachary Turner 
262563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
262663dd5d25SJonas Devlieghere     const char *impl_function, Thread *thread, std::string &output,
262797206d57SZachary Turner     Status &error) {
26282c1f46dcSZachary Turner   bool ret_val;
2629b9c1b51eSKate Stone   if (!thread) {
26302c1f46dcSZachary Turner     error.SetErrorString("no thread");
26312c1f46dcSZachary Turner     return false;
26322c1f46dcSZachary Turner   }
2633b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
26342c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
26352c1f46dcSZachary Turner     return false;
26362c1f46dcSZachary Turner   }
263705495c5dSJonas Devlieghere 
26382c1f46dcSZachary Turner   {
26392c1f46dcSZachary Turner     ThreadSP thread_sp(thread->shared_from_this());
2640b9c1b51eSKate Stone     Locker py_lock(this,
2641b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
264205495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordThread(
2643b9c1b51eSKate Stone         impl_function, m_dictionary_name.c_str(), thread_sp, output);
26442c1f46dcSZachary Turner     if (!ret_val)
26452c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
26462c1f46dcSZachary Turner   }
26472c1f46dcSZachary Turner   return ret_val;
26482c1f46dcSZachary Turner }
26492c1f46dcSZachary Turner 
265063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
265163dd5d25SJonas Devlieghere     const char *impl_function, Target *target, std::string &output,
265297206d57SZachary Turner     Status &error) {
26532c1f46dcSZachary Turner   bool ret_val;
2654b9c1b51eSKate Stone   if (!target) {
26552c1f46dcSZachary Turner     error.SetErrorString("no thread");
26562c1f46dcSZachary Turner     return false;
26572c1f46dcSZachary Turner   }
2658b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
26592c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
26602c1f46dcSZachary Turner     return false;
26612c1f46dcSZachary Turner   }
266205495c5dSJonas Devlieghere 
26632c1f46dcSZachary Turner   {
26642c1f46dcSZachary Turner     TargetSP target_sp(target->shared_from_this());
2665b9c1b51eSKate Stone     Locker py_lock(this,
2666b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
266705495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordTarget(
2668b9c1b51eSKate Stone         impl_function, m_dictionary_name.c_str(), target_sp, output);
26692c1f46dcSZachary Turner     if (!ret_val)
26702c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
26712c1f46dcSZachary Turner   }
26722c1f46dcSZachary Turner   return ret_val;
26732c1f46dcSZachary Turner }
26742c1f46dcSZachary Turner 
267563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
267663dd5d25SJonas Devlieghere     const char *impl_function, StackFrame *frame, std::string &output,
267797206d57SZachary Turner     Status &error) {
26782c1f46dcSZachary Turner   bool ret_val;
2679b9c1b51eSKate Stone   if (!frame) {
26802c1f46dcSZachary Turner     error.SetErrorString("no frame");
26812c1f46dcSZachary Turner     return false;
26822c1f46dcSZachary Turner   }
2683b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
26842c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
26852c1f46dcSZachary Turner     return false;
26862c1f46dcSZachary Turner   }
268705495c5dSJonas Devlieghere 
26882c1f46dcSZachary Turner   {
26892c1f46dcSZachary Turner     StackFrameSP frame_sp(frame->shared_from_this());
2690b9c1b51eSKate Stone     Locker py_lock(this,
2691b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
269205495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordFrame(
2693b9c1b51eSKate Stone         impl_function, m_dictionary_name.c_str(), frame_sp, output);
26942c1f46dcSZachary Turner     if (!ret_val)
26952c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
26962c1f46dcSZachary Turner   }
26972c1f46dcSZachary Turner   return ret_val;
26982c1f46dcSZachary Turner }
26992c1f46dcSZachary Turner 
270063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
270163dd5d25SJonas Devlieghere     const char *impl_function, ValueObject *value, std::string &output,
270297206d57SZachary Turner     Status &error) {
27032c1f46dcSZachary Turner   bool ret_val;
2704b9c1b51eSKate Stone   if (!value) {
27052c1f46dcSZachary Turner     error.SetErrorString("no value");
27062c1f46dcSZachary Turner     return false;
27072c1f46dcSZachary Turner   }
2708b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
27092c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
27102c1f46dcSZachary Turner     return false;
27112c1f46dcSZachary Turner   }
271205495c5dSJonas Devlieghere 
27132c1f46dcSZachary Turner   {
27142c1f46dcSZachary Turner     ValueObjectSP value_sp(value->GetSP());
2715b9c1b51eSKate Stone     Locker py_lock(this,
2716b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
271705495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordValue(
2718b9c1b51eSKate Stone         impl_function, m_dictionary_name.c_str(), value_sp, output);
27192c1f46dcSZachary Turner     if (!ret_val)
27202c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
27212c1f46dcSZachary Turner   }
27222c1f46dcSZachary Turner   return ret_val;
27232c1f46dcSZachary Turner }
27242c1f46dcSZachary Turner 
2725b9c1b51eSKate Stone uint64_t replace_all(std::string &str, const std::string &oldStr,
2726b9c1b51eSKate Stone                      const std::string &newStr) {
27272c1f46dcSZachary Turner   size_t pos = 0;
27282c1f46dcSZachary Turner   uint64_t matches = 0;
2729b9c1b51eSKate Stone   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
27302c1f46dcSZachary Turner     matches++;
27312c1f46dcSZachary Turner     str.replace(pos, oldStr.length(), newStr);
27322c1f46dcSZachary Turner     pos += newStr.length();
27332c1f46dcSZachary Turner   }
27342c1f46dcSZachary Turner   return matches;
27352c1f46dcSZachary Turner }
27362c1f46dcSZachary Turner 
273763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::LoadScriptingModule(
273815625112SJonas Devlieghere     const char *pathname, bool init_session, lldb_private::Status &error,
273900bb397bSJonas Devlieghere     StructuredData::ObjectSP *module_sp, FileSpec extra_search_dir) {
27403b33b416SJonas Devlieghere   namespace fs = llvm::sys::fs;
274100bb397bSJonas Devlieghere   namespace path = llvm::sys::path;
27423b33b416SJonas Devlieghere 
2743b9c1b51eSKate Stone   if (!pathname || !pathname[0]) {
27442c1f46dcSZachary Turner     error.SetErrorString("invalid pathname");
27452c1f46dcSZachary Turner     return false;
27462c1f46dcSZachary Turner   }
27472c1f46dcSZachary Turner 
27488d1fb843SJonas Devlieghere   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
27492c1f46dcSZachary Turner 
2750f9f36097SAdrian McCarthy   // Before executing Python code, lock the GIL.
275120b52c33SJonas Devlieghere   Locker py_lock(this,
275220b52c33SJonas Devlieghere                  Locker::AcquireLock |
27533b33b416SJonas Devlieghere                      (init_session ? Locker::InitSession : 0) | Locker::NoSTDIN,
2754b9c1b51eSKate Stone                  Locker::FreeAcquiredLock |
2755b9c1b51eSKate Stone                      (init_session ? Locker::TearDownSession : 0));
27562c1f46dcSZachary Turner 
275700bb397bSJonas Devlieghere   auto ExtendSysPath = [this](std::string directory) -> llvm::Error {
275800bb397bSJonas Devlieghere     if (directory.empty()) {
275900bb397bSJonas Devlieghere       return llvm::make_error<llvm::StringError>(
276000bb397bSJonas Devlieghere           "invalid directory name", llvm::inconvertibleErrorCode());
276142a9da7bSStefan Granitz     }
276242a9da7bSStefan Granitz 
2763f9f36097SAdrian McCarthy     replace_all(directory, "\\", "\\\\");
27642c1f46dcSZachary Turner     replace_all(directory, "'", "\\'");
27652c1f46dcSZachary Turner 
276600bb397bSJonas Devlieghere     // Make sure that Python has "directory" in the search path.
27672c1f46dcSZachary Turner     StreamString command_stream;
2768b9c1b51eSKate Stone     command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
2769b9c1b51eSKate Stone                           "sys.path.insert(1,'%s');\n\n",
2770b9c1b51eSKate Stone                           directory.c_str(), directory.c_str());
2771b9c1b51eSKate Stone     bool syspath_retval =
2772b9c1b51eSKate Stone         ExecuteMultipleLines(command_stream.GetData(),
2773b9c1b51eSKate Stone                              ScriptInterpreter::ExecuteScriptOptions()
2774b9c1b51eSKate Stone                                  .SetEnableIO(false)
2775b9c1b51eSKate Stone                                  .SetSetLLDBGlobals(false))
2776b9c1b51eSKate Stone             .Success();
2777b9c1b51eSKate Stone     if (!syspath_retval) {
277800bb397bSJonas Devlieghere       return llvm::make_error<llvm::StringError>(
277900bb397bSJonas Devlieghere           "Python sys.path handling failed", llvm::inconvertibleErrorCode());
27802c1f46dcSZachary Turner     }
27812c1f46dcSZachary Turner 
278200bb397bSJonas Devlieghere     return llvm::Error::success();
278300bb397bSJonas Devlieghere   };
278400bb397bSJonas Devlieghere 
278500bb397bSJonas Devlieghere   std::string module_name(pathname);
2786d6e80578SJonas Devlieghere   bool possible_package = false;
278700bb397bSJonas Devlieghere 
278800bb397bSJonas Devlieghere   if (extra_search_dir) {
278900bb397bSJonas Devlieghere     if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
279000bb397bSJonas Devlieghere       error = std::move(e);
279100bb397bSJonas Devlieghere       return false;
279200bb397bSJonas Devlieghere     }
279300bb397bSJonas Devlieghere   } else {
279400bb397bSJonas Devlieghere     FileSpec module_file(pathname);
279500bb397bSJonas Devlieghere     FileSystem::Instance().Resolve(module_file);
279600bb397bSJonas Devlieghere     FileSystem::Instance().Collect(module_file);
279700bb397bSJonas Devlieghere 
279800bb397bSJonas Devlieghere     fs::file_status st;
279900bb397bSJonas Devlieghere     std::error_code ec = status(module_file.GetPath(), st);
280000bb397bSJonas Devlieghere 
280100bb397bSJonas Devlieghere     if (ec || st.type() == fs::file_type::status_error ||
280200bb397bSJonas Devlieghere         st.type() == fs::file_type::type_unknown ||
280300bb397bSJonas Devlieghere         st.type() == fs::file_type::file_not_found) {
280400bb397bSJonas Devlieghere       // if not a valid file of any sort, check if it might be a filename still
280500bb397bSJonas Devlieghere       // dot can't be used but / and \ can, and if either is found, reject
280600bb397bSJonas Devlieghere       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
280700bb397bSJonas Devlieghere         error.SetErrorString("invalid pathname");
280800bb397bSJonas Devlieghere         return false;
280900bb397bSJonas Devlieghere       }
281000bb397bSJonas Devlieghere       // Not a filename, probably a package of some sort, let it go through.
2811d6e80578SJonas Devlieghere       possible_package = true;
281200bb397bSJonas Devlieghere     } else if (is_directory(st) || is_regular_file(st)) {
281300bb397bSJonas Devlieghere       if (module_file.GetDirectory().IsEmpty()) {
281400bb397bSJonas Devlieghere         error.SetErrorString("invalid directory name");
281500bb397bSJonas Devlieghere         return false;
281600bb397bSJonas Devlieghere       }
281700bb397bSJonas Devlieghere       if (llvm::Error e =
281800bb397bSJonas Devlieghere               ExtendSysPath(module_file.GetDirectory().GetCString())) {
281900bb397bSJonas Devlieghere         error = std::move(e);
282000bb397bSJonas Devlieghere         return false;
282100bb397bSJonas Devlieghere       }
282200bb397bSJonas Devlieghere       module_name = module_file.GetFilename().GetCString();
2823b9c1b51eSKate Stone     } else {
28242c1f46dcSZachary Turner       error.SetErrorString("no known way to import this module specification");
28252c1f46dcSZachary Turner       return false;
28262c1f46dcSZachary Turner     }
282700bb397bSJonas Devlieghere   }
28282c1f46dcSZachary Turner 
28291197ee35SJonas Devlieghere   // Strip .py or .pyc extension
283000bb397bSJonas Devlieghere   llvm::StringRef extension = llvm::sys::path::extension(module_name);
28311197ee35SJonas Devlieghere   if (!extension.empty()) {
28321197ee35SJonas Devlieghere     if (extension == ".py")
283300bb397bSJonas Devlieghere       module_name.resize(module_name.length() - 3);
28341197ee35SJonas Devlieghere     else if (extension == ".pyc")
283500bb397bSJonas Devlieghere       module_name.resize(module_name.length() - 4);
28361197ee35SJonas Devlieghere   }
28371197ee35SJonas Devlieghere 
2838d6e80578SJonas Devlieghere   if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2839d6e80578SJonas Devlieghere     error.SetErrorStringWithFormat(
2840d6e80578SJonas Devlieghere         "Python does not allow dots in module names: %s", module_name.c_str());
2841d6e80578SJonas Devlieghere     return false;
2842d6e80578SJonas Devlieghere   }
2843d6e80578SJonas Devlieghere 
2844d6e80578SJonas Devlieghere   if (module_name.find('-') != llvm::StringRef::npos) {
2845d6e80578SJonas Devlieghere     error.SetErrorStringWithFormat(
2846d6e80578SJonas Devlieghere         "Python discourages dashes in module names: %s", module_name.c_str());
2847d6e80578SJonas Devlieghere     return false;
2848d6e80578SJonas Devlieghere   }
2849d6e80578SJonas Devlieghere 
28502c1f46dcSZachary Turner   // check if the module is already import-ed
285100bb397bSJonas Devlieghere   StreamString command_stream;
28522c1f46dcSZachary Turner   command_stream.Clear();
285300bb397bSJonas Devlieghere   command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
28542c1f46dcSZachary Turner   bool does_contain = false;
285505097246SAdrian Prantl   // this call will succeed if the module was ever imported in any Debugger
285605097246SAdrian Prantl   // in the lifetime of the process in which this LLDB framework is living
2857612384f6SJonas Devlieghere   const bool was_imported_globally =
2858b9c1b51eSKate Stone       (ExecuteOneLineWithReturn(
2859b9c1b51eSKate Stone            command_stream.GetData(),
286063dd5d25SJonas Devlieghere            ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain,
2861b9c1b51eSKate Stone            ScriptInterpreter::ExecuteScriptOptions()
2862b9c1b51eSKate Stone                .SetEnableIO(false)
2863b9c1b51eSKate Stone                .SetSetLLDBGlobals(false)) &&
2864b9c1b51eSKate Stone        does_contain);
2865612384f6SJonas Devlieghere   const bool was_imported_locally =
2866612384f6SJonas Devlieghere       GetSessionDictionary()
286700bb397bSJonas Devlieghere           .GetItemForKey(PythonString(module_name))
2868b9c1b51eSKate Stone           .IsAllocated();
28692c1f46dcSZachary Turner 
28702c1f46dcSZachary Turner   // now actually do the import
28712c1f46dcSZachary Turner   command_stream.Clear();
28722c1f46dcSZachary Turner 
2873612384f6SJonas Devlieghere   if (was_imported_globally || was_imported_locally) {
28742c1f46dcSZachary Turner     if (!was_imported_locally)
287500bb397bSJonas Devlieghere       command_stream.Printf("import %s ; reload_module(%s)",
287600bb397bSJonas Devlieghere                             module_name.c_str(), module_name.c_str());
28772c1f46dcSZachary Turner     else
287800bb397bSJonas Devlieghere       command_stream.Printf("reload_module(%s)", module_name.c_str());
2879b9c1b51eSKate Stone   } else
288000bb397bSJonas Devlieghere     command_stream.Printf("import %s", module_name.c_str());
28812c1f46dcSZachary Turner 
2882b9c1b51eSKate Stone   error = ExecuteMultipleLines(command_stream.GetData(),
2883b9c1b51eSKate Stone                                ScriptInterpreter::ExecuteScriptOptions()
2884b9c1b51eSKate Stone                                    .SetEnableIO(false)
2885b9c1b51eSKate Stone                                    .SetSetLLDBGlobals(false));
28862c1f46dcSZachary Turner   if (error.Fail())
28872c1f46dcSZachary Turner     return false;
28882c1f46dcSZachary Turner 
28892c1f46dcSZachary Turner   // if we are here, everything worked
28902c1f46dcSZachary Turner   // call __lldb_init_module(debugger,dict)
289100bb397bSJonas Devlieghere   if (!LLDBSwigPythonCallModuleInit(module_name.c_str(),
289200bb397bSJonas Devlieghere                                     m_dictionary_name.c_str(), debugger_sp)) {
28932c1f46dcSZachary Turner     error.SetErrorString("calling __lldb_init_module failed");
28942c1f46dcSZachary Turner     return false;
28952c1f46dcSZachary Turner   }
28962c1f46dcSZachary Turner 
2897b9c1b51eSKate Stone   if (module_sp) {
28982c1f46dcSZachary Turner     // everything went just great, now set the module object
28992c1f46dcSZachary Turner     command_stream.Clear();
290000bb397bSJonas Devlieghere     command_stream.Printf("%s", module_name.c_str());
29012c1f46dcSZachary Turner     void *module_pyobj = nullptr;
2902b9c1b51eSKate Stone     if (ExecuteOneLineWithReturn(
2903b9c1b51eSKate Stone             command_stream.GetData(),
29043b33b416SJonas Devlieghere             ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj) &&
2905b9c1b51eSKate Stone         module_pyobj)
2906796ac80bSJonas Devlieghere       *module_sp = std::make_shared<StructuredPythonObject>(module_pyobj);
29072c1f46dcSZachary Turner   }
29082c1f46dcSZachary Turner 
29092c1f46dcSZachary Turner   return true;
29102c1f46dcSZachary Turner }
29112c1f46dcSZachary Turner 
291263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
29132c1f46dcSZachary Turner   if (!word || !word[0])
29142c1f46dcSZachary Turner     return false;
29152c1f46dcSZachary Turner 
29162c1f46dcSZachary Turner   llvm::StringRef word_sr(word);
29172c1f46dcSZachary Turner 
291805097246SAdrian Prantl   // filter out a few characters that would just confuse us and that are
291905097246SAdrian Prantl   // clearly not keyword material anyway
292010b113e8SJonas Devlieghere   if (word_sr.find('"') != llvm::StringRef::npos ||
292110b113e8SJonas Devlieghere       word_sr.find('\'') != llvm::StringRef::npos)
29222c1f46dcSZachary Turner     return false;
29232c1f46dcSZachary Turner 
29242c1f46dcSZachary Turner   StreamString command_stream;
29252c1f46dcSZachary Turner   command_stream.Printf("keyword.iskeyword('%s')", word);
29262c1f46dcSZachary Turner   bool result;
29272c1f46dcSZachary Turner   ExecuteScriptOptions options;
29282c1f46dcSZachary Turner   options.SetEnableIO(false);
29292c1f46dcSZachary Turner   options.SetMaskoutErrors(true);
29302c1f46dcSZachary Turner   options.SetSetLLDBGlobals(false);
2931b9c1b51eSKate Stone   if (ExecuteOneLineWithReturn(command_stream.GetData(),
2932b9c1b51eSKate Stone                                ScriptInterpreter::eScriptReturnTypeBool,
2933b9c1b51eSKate Stone                                &result, options))
29342c1f46dcSZachary Turner     return result;
29352c1f46dcSZachary Turner   return false;
29362c1f46dcSZachary Turner }
29372c1f46dcSZachary Turner 
293863dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2939b9c1b51eSKate Stone     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2940b9c1b51eSKate Stone     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2941b9c1b51eSKate Stone       m_old_asynch(debugger_sp->GetAsyncExecution()) {
29422c1f46dcSZachary Turner   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
29432c1f46dcSZachary Turner     m_debugger_sp->SetAsyncExecution(false);
29442c1f46dcSZachary Turner   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
29452c1f46dcSZachary Turner     m_debugger_sp->SetAsyncExecution(true);
29462c1f46dcSZachary Turner }
29472c1f46dcSZachary Turner 
294863dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
29492c1f46dcSZachary Turner   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
29502c1f46dcSZachary Turner     m_debugger_sp->SetAsyncExecution(m_old_asynch);
29512c1f46dcSZachary Turner }
29522c1f46dcSZachary Turner 
295363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
29544d51a902SRaphael Isemann     const char *impl_function, llvm::StringRef args,
29552c1f46dcSZachary Turner     ScriptedCommandSynchronicity synchronicity,
295697206d57SZachary Turner     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2957b9c1b51eSKate Stone     const lldb_private::ExecutionContext &exe_ctx) {
2958b9c1b51eSKate Stone   if (!impl_function) {
29592c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
29602c1f46dcSZachary Turner     return false;
29612c1f46dcSZachary Turner   }
29622c1f46dcSZachary Turner 
29638d1fb843SJonas Devlieghere   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
29642c1f46dcSZachary Turner   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
29652c1f46dcSZachary Turner 
2966b9c1b51eSKate Stone   if (!debugger_sp.get()) {
29672c1f46dcSZachary Turner     error.SetErrorString("invalid Debugger pointer");
29682c1f46dcSZachary Turner     return false;
29692c1f46dcSZachary Turner   }
29702c1f46dcSZachary Turner 
29712c1f46dcSZachary Turner   bool ret_val = false;
29722c1f46dcSZachary Turner 
29732c1f46dcSZachary Turner   std::string err_msg;
29742c1f46dcSZachary Turner 
29752c1f46dcSZachary Turner   {
29762c1f46dcSZachary Turner     Locker py_lock(this,
2977b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession |
2978b9c1b51eSKate Stone                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
29792c1f46dcSZachary Turner                    Locker::FreeLock | Locker::TearDownSession);
29802c1f46dcSZachary Turner 
2981b9c1b51eSKate Stone     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
29822c1f46dcSZachary Turner 
29834d51a902SRaphael Isemann     std::string args_str = args.str();
298405495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCallCommand(
298505495c5dSJonas Devlieghere         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
298605495c5dSJonas Devlieghere         cmd_retobj, exe_ctx_ref_sp);
29872c1f46dcSZachary Turner   }
29882c1f46dcSZachary Turner 
29892c1f46dcSZachary Turner   if (!ret_val)
29902c1f46dcSZachary Turner     error.SetErrorString("unable to execute script function");
29912c1f46dcSZachary Turner   else
29922c1f46dcSZachary Turner     error.Clear();
29932c1f46dcSZachary Turner 
29942c1f46dcSZachary Turner   return ret_val;
29952c1f46dcSZachary Turner }
29962c1f46dcSZachary Turner 
299763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
29984d51a902SRaphael Isemann     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
29992c1f46dcSZachary Turner     ScriptedCommandSynchronicity synchronicity,
300097206d57SZachary Turner     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
3001b9c1b51eSKate Stone     const lldb_private::ExecutionContext &exe_ctx) {
3002b9c1b51eSKate Stone   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
30032c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
30042c1f46dcSZachary Turner     return false;
30052c1f46dcSZachary Turner   }
30062c1f46dcSZachary Turner 
30078d1fb843SJonas Devlieghere   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
30082c1f46dcSZachary Turner   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
30092c1f46dcSZachary Turner 
3010b9c1b51eSKate Stone   if (!debugger_sp.get()) {
30112c1f46dcSZachary Turner     error.SetErrorString("invalid Debugger pointer");
30122c1f46dcSZachary Turner     return false;
30132c1f46dcSZachary Turner   }
30142c1f46dcSZachary Turner 
30152c1f46dcSZachary Turner   bool ret_val = false;
30162c1f46dcSZachary Turner 
30172c1f46dcSZachary Turner   std::string err_msg;
30182c1f46dcSZachary Turner 
30192c1f46dcSZachary Turner   {
30202c1f46dcSZachary Turner     Locker py_lock(this,
3021b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession |
3022b9c1b51eSKate Stone                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
30232c1f46dcSZachary Turner                    Locker::FreeLock | Locker::TearDownSession);
30242c1f46dcSZachary Turner 
3025b9c1b51eSKate Stone     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
30262c1f46dcSZachary Turner 
30274d51a902SRaphael Isemann     std::string args_str = args.str();
302805495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCallCommandObject(impl_obj_sp->GetValue(),
302905495c5dSJonas Devlieghere                                               debugger_sp, args_str.c_str(),
303005495c5dSJonas Devlieghere                                               cmd_retobj, exe_ctx_ref_sp);
30312c1f46dcSZachary Turner   }
30322c1f46dcSZachary Turner 
30332c1f46dcSZachary Turner   if (!ret_val)
30342c1f46dcSZachary Turner     error.SetErrorString("unable to execute script function");
30352c1f46dcSZachary Turner   else
30362c1f46dcSZachary Turner     error.Clear();
30372c1f46dcSZachary Turner 
30382c1f46dcSZachary Turner   return ret_val;
30392c1f46dcSZachary Turner }
30402c1f46dcSZachary Turner 
304193571c3cSJonas Devlieghere /// In Python, a special attribute __doc__ contains the docstring for an object
304293571c3cSJonas Devlieghere /// (function, method, class, ...) if any is defined Otherwise, the attribute's
304393571c3cSJonas Devlieghere /// value is None.
304463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
3045b9c1b51eSKate Stone                                                           std::string &dest) {
30462c1f46dcSZachary Turner   dest.clear();
304793571c3cSJonas Devlieghere 
30482c1f46dcSZachary Turner   if (!item || !*item)
30492c1f46dcSZachary Turner     return false;
305093571c3cSJonas Devlieghere 
30512c1f46dcSZachary Turner   std::string command(item);
30522c1f46dcSZachary Turner   command += ".__doc__";
30532c1f46dcSZachary Turner 
305493571c3cSJonas Devlieghere   // Python is going to point this to valid data if ExecuteOneLineWithReturn
305593571c3cSJonas Devlieghere   // returns successfully.
305693571c3cSJonas Devlieghere   char *result_ptr = nullptr;
30572c1f46dcSZachary Turner 
3058b9c1b51eSKate Stone   if (ExecuteOneLineWithReturn(
305993571c3cSJonas Devlieghere           command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
30602c1f46dcSZachary Turner           &result_ptr,
3061b9c1b51eSKate Stone           ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false))) {
30622c1f46dcSZachary Turner     if (result_ptr)
30632c1f46dcSZachary Turner       dest.assign(result_ptr);
30642c1f46dcSZachary Turner     return true;
30652c1f46dcSZachary Turner   }
306693571c3cSJonas Devlieghere 
306793571c3cSJonas Devlieghere   StreamString str_stream;
306893571c3cSJonas Devlieghere   str_stream << "Function " << item
306993571c3cSJonas Devlieghere              << " was not found. Containing module might be missing.";
307093571c3cSJonas Devlieghere   dest = std::string(str_stream.GetString());
307193571c3cSJonas Devlieghere 
307293571c3cSJonas Devlieghere   return false;
30732c1f46dcSZachary Turner }
30742c1f46dcSZachary Turner 
307563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
3076b9c1b51eSKate Stone     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
30772c1f46dcSZachary Turner   dest.clear();
30782c1f46dcSZachary Turner 
3079b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
30802c1f46dcSZachary Turner 
30812c1f46dcSZachary Turner   static char callee_name[] = "get_short_help";
30822c1f46dcSZachary Turner 
30832c1f46dcSZachary Turner   if (!cmd_obj_sp)
30842c1f46dcSZachary Turner     return false;
30852c1f46dcSZachary Turner 
3086b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
3087b9c1b51eSKate Stone                            (PyObject *)cmd_obj_sp->GetValue());
30882c1f46dcSZachary Turner 
3089f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
30902c1f46dcSZachary Turner     return false;
30912c1f46dcSZachary Turner 
3092b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
3093b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
30942c1f46dcSZachary Turner 
30952c1f46dcSZachary Turner   if (PyErr_Occurred())
30962c1f46dcSZachary Turner     PyErr_Clear();
30972c1f46dcSZachary Turner 
3098f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
30992c1f46dcSZachary Turner     return false;
31002c1f46dcSZachary Turner 
3101b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
31022c1f46dcSZachary Turner     if (PyErr_Occurred())
31032c1f46dcSZachary Turner       PyErr_Clear();
31042c1f46dcSZachary Turner     return false;
31052c1f46dcSZachary Turner   }
31062c1f46dcSZachary Turner 
31072c1f46dcSZachary Turner   if (PyErr_Occurred())
31082c1f46dcSZachary Turner     PyErr_Clear();
31092c1f46dcSZachary Turner 
311093571c3cSJonas Devlieghere   // Right now we know this function exists and is callable.
3111b9c1b51eSKate Stone   PythonObject py_return(
3112b9c1b51eSKate Stone       PyRefType::Owned,
3113b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
31142c1f46dcSZachary Turner 
311593571c3cSJonas Devlieghere   // If it fails, print the error but otherwise go on.
3116b9c1b51eSKate Stone   if (PyErr_Occurred()) {
31172c1f46dcSZachary Turner     PyErr_Print();
31182c1f46dcSZachary Turner     PyErr_Clear();
31192c1f46dcSZachary Turner   }
31202c1f46dcSZachary Turner 
3121b9c1b51eSKate Stone   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3122f8b22f8fSZachary Turner     PythonString py_string(PyRefType::Borrowed, py_return.get());
312322c8efcdSZachary Turner     llvm::StringRef return_data(py_string.GetString());
312422c8efcdSZachary Turner     dest.assign(return_data.data(), return_data.size());
312593571c3cSJonas Devlieghere     return true;
31262c1f46dcSZachary Turner   }
312793571c3cSJonas Devlieghere 
312893571c3cSJonas Devlieghere   return false;
31292c1f46dcSZachary Turner }
31302c1f46dcSZachary Turner 
313163dd5d25SJonas Devlieghere uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
3132b9c1b51eSKate Stone     StructuredData::GenericSP cmd_obj_sp) {
31332c1f46dcSZachary Turner   uint32_t result = 0;
31342c1f46dcSZachary Turner 
3135b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
31362c1f46dcSZachary Turner 
31372c1f46dcSZachary Turner   static char callee_name[] = "get_flags";
31382c1f46dcSZachary Turner 
31392c1f46dcSZachary Turner   if (!cmd_obj_sp)
31402c1f46dcSZachary Turner     return result;
31412c1f46dcSZachary Turner 
3142b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
3143b9c1b51eSKate Stone                            (PyObject *)cmd_obj_sp->GetValue());
31442c1f46dcSZachary Turner 
3145f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
31462c1f46dcSZachary Turner     return result;
31472c1f46dcSZachary Turner 
3148b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
3149b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
31502c1f46dcSZachary Turner 
31512c1f46dcSZachary Turner   if (PyErr_Occurred())
31522c1f46dcSZachary Turner     PyErr_Clear();
31532c1f46dcSZachary Turner 
3154f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
31552c1f46dcSZachary Turner     return result;
31562c1f46dcSZachary Turner 
3157b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
31582c1f46dcSZachary Turner     if (PyErr_Occurred())
31592c1f46dcSZachary Turner       PyErr_Clear();
31602c1f46dcSZachary Turner     return result;
31612c1f46dcSZachary Turner   }
31622c1f46dcSZachary Turner 
31632c1f46dcSZachary Turner   if (PyErr_Occurred())
31642c1f46dcSZachary Turner     PyErr_Clear();
31652c1f46dcSZachary Turner 
316652712d3fSLawrence D'Anna   long long py_return = unwrapOrSetPythonException(
316752712d3fSLawrence D'Anna       As<long long>(implementor.CallMethod(callee_name)));
31682c1f46dcSZachary Turner 
31692c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
3170b9c1b51eSKate Stone   if (PyErr_Occurred()) {
31712c1f46dcSZachary Turner     PyErr_Print();
31722c1f46dcSZachary Turner     PyErr_Clear();
317352712d3fSLawrence D'Anna   } else {
317452712d3fSLawrence D'Anna     result = py_return;
31752c1f46dcSZachary Turner   }
31762c1f46dcSZachary Turner 
31772c1f46dcSZachary Turner   return result;
31782c1f46dcSZachary Turner }
31792c1f46dcSZachary Turner 
318063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3181b9c1b51eSKate Stone     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
31822c1f46dcSZachary Turner   bool got_string = false;
31832c1f46dcSZachary Turner   dest.clear();
31842c1f46dcSZachary Turner 
3185b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
31862c1f46dcSZachary Turner 
31872c1f46dcSZachary Turner   static char callee_name[] = "get_long_help";
31882c1f46dcSZachary Turner 
31892c1f46dcSZachary Turner   if (!cmd_obj_sp)
31902c1f46dcSZachary Turner     return false;
31912c1f46dcSZachary Turner 
3192b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
3193b9c1b51eSKate Stone                            (PyObject *)cmd_obj_sp->GetValue());
31942c1f46dcSZachary Turner 
3195f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
31962c1f46dcSZachary Turner     return false;
31972c1f46dcSZachary Turner 
3198b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
3199b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
32002c1f46dcSZachary Turner 
32012c1f46dcSZachary Turner   if (PyErr_Occurred())
32022c1f46dcSZachary Turner     PyErr_Clear();
32032c1f46dcSZachary Turner 
3204f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
32052c1f46dcSZachary Turner     return false;
32062c1f46dcSZachary Turner 
3207b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
32082c1f46dcSZachary Turner     if (PyErr_Occurred())
32092c1f46dcSZachary Turner       PyErr_Clear();
32102c1f46dcSZachary Turner 
32112c1f46dcSZachary Turner     return false;
32122c1f46dcSZachary Turner   }
32132c1f46dcSZachary Turner 
32142c1f46dcSZachary Turner   if (PyErr_Occurred())
32152c1f46dcSZachary Turner     PyErr_Clear();
32162c1f46dcSZachary Turner 
32172c1f46dcSZachary Turner   // right now we know this function exists and is callable..
3218b9c1b51eSKate Stone   PythonObject py_return(
3219b9c1b51eSKate Stone       PyRefType::Owned,
3220b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
32212c1f46dcSZachary Turner 
32222c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
3223b9c1b51eSKate Stone   if (PyErr_Occurred()) {
32242c1f46dcSZachary Turner     PyErr_Print();
32252c1f46dcSZachary Turner     PyErr_Clear();
32262c1f46dcSZachary Turner   }
32272c1f46dcSZachary Turner 
3228b9c1b51eSKate Stone   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3229f8b22f8fSZachary Turner     PythonString str(PyRefType::Borrowed, py_return.get());
323022c8efcdSZachary Turner     llvm::StringRef str_data(str.GetString());
323122c8efcdSZachary Turner     dest.assign(str_data.data(), str_data.size());
32322c1f46dcSZachary Turner     got_string = true;
32332c1f46dcSZachary Turner   }
32342c1f46dcSZachary Turner 
32352c1f46dcSZachary Turner   return got_string;
32362c1f46dcSZachary Turner }
32372c1f46dcSZachary Turner 
32382c1f46dcSZachary Turner std::unique_ptr<ScriptInterpreterLocker>
323963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3240b9c1b51eSKate Stone   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3241b9c1b51eSKate Stone       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
32422c1f46dcSZachary Turner       Locker::FreeLock | Locker::TearDownSession));
32432c1f46dcSZachary Turner   return py_lock;
32442c1f46dcSZachary Turner }
32452c1f46dcSZachary Turner 
324663dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::InitializePrivate() {
324715d1b4e2SEnrico Granata   if (g_initialized)
324815d1b4e2SEnrico Granata     return;
324915d1b4e2SEnrico Granata 
32502c1f46dcSZachary Turner   g_initialized = true;
32512c1f46dcSZachary Turner 
32525c1c8443SJonas Devlieghere   LLDB_SCOPED_TIMER();
32532c1f46dcSZachary Turner 
3254b9c1b51eSKate Stone   // RAII-based initialization which correctly handles multiple-initialization,
325505097246SAdrian Prantl   // version- specific differences among Python 2 and Python 3, and saving and
325605097246SAdrian Prantl   // restoring various other pieces of state that can get mucked with during
325705097246SAdrian Prantl   // initialization.
3258079fe48aSZachary Turner   InitializePythonRAII initialize_guard;
32592c1f46dcSZachary Turner 
326005495c5dSJonas Devlieghere   LLDBSwigPyInit();
32612c1f46dcSZachary Turner 
3262b9c1b51eSKate Stone   // Update the path python uses to search for modules to include the current
3263b9c1b51eSKate Stone   // directory.
32642c1f46dcSZachary Turner 
32652c1f46dcSZachary Turner   PyRun_SimpleString("import sys");
32662c1f46dcSZachary Turner   AddToSysPath(AddLocation::End, ".");
32672c1f46dcSZachary Turner 
3268b9c1b51eSKate Stone   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
326905097246SAdrian Prantl   // that use a backslash as the path separator, this will result in executing
327005097246SAdrian Prantl   // python code containing paths with unescaped backslashes.  But Python also
327105097246SAdrian Prantl   // accepts forward slashes, so to make life easier we just use that.
32722df331b0SPavel Labath   if (FileSpec file_spec = GetPythonDir())
32732c1f46dcSZachary Turner     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
327460f028ffSPavel Labath   if (FileSpec file_spec = HostInfo::GetShlibDir())
32752c1f46dcSZachary Turner     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
32762c1f46dcSZachary Turner 
3277b9c1b51eSKate Stone   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3278b9c1b51eSKate Stone                      "lldb.embedded_interpreter; from "
3279b9c1b51eSKate Stone                      "lldb.embedded_interpreter import run_python_interpreter; "
3280b9c1b51eSKate Stone                      "from lldb.embedded_interpreter import run_one_line");
32812c1f46dcSZachary Turner }
32822c1f46dcSZachary Turner 
328363dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3284b9c1b51eSKate Stone                                                std::string path) {
32852c1f46dcSZachary Turner   std::string path_copy;
32862c1f46dcSZachary Turner 
32872c1f46dcSZachary Turner   std::string statement;
3288b9c1b51eSKate Stone   if (location == AddLocation::Beginning) {
32892c1f46dcSZachary Turner     statement.assign("sys.path.insert(0,\"");
32902c1f46dcSZachary Turner     statement.append(path);
32912c1f46dcSZachary Turner     statement.append("\")");
3292b9c1b51eSKate Stone   } else {
32932c1f46dcSZachary Turner     statement.assign("sys.path.append(\"");
32942c1f46dcSZachary Turner     statement.append(path);
32952c1f46dcSZachary Turner     statement.append("\")");
32962c1f46dcSZachary Turner   }
32972c1f46dcSZachary Turner   PyRun_SimpleString(statement.c_str());
32982c1f46dcSZachary Turner }
32992c1f46dcSZachary Turner 
3300bcadb5a3SPavel Labath // We are intentionally NOT calling Py_Finalize here (this would be the logical
3301bcadb5a3SPavel Labath // place to call it).  Calling Py_Finalize here causes test suite runs to seg
3302bcadb5a3SPavel Labath // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
3303bcadb5a3SPavel Labath // be called 'at_exit'.  When the test suite Python harness finishes up, it
3304bcadb5a3SPavel Labath // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3305bcadb5a3SPavel Labath // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3306bcadb5a3SPavel Labath // which calls ScriptInterpreter::Terminate, which calls
330763dd5d25SJonas Devlieghere // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
330863dd5d25SJonas Devlieghere // end up with Py_Finalize being called from within Py_Finalize, which results
330963dd5d25SJonas Devlieghere // in a seg fault. Since this function only gets called when lldb is shutting
331063dd5d25SJonas Devlieghere // down and going away anyway, the fact that we don't actually call Py_Finalize
3311bcadb5a3SPavel Labath // should not cause any problems (everything should shut down/go away anyway
3312bcadb5a3SPavel Labath // when the process exits).
3313bcadb5a3SPavel Labath //
331463dd5d25SJonas Devlieghere // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3315d68983e3SPavel Labath 
33164e26cf2cSJonas Devlieghere #endif
3317