180814287SRaphael Isemann //===-- ScriptInterpreterPython.cpp ---------------------------------------===//
22c1f46dcSZachary Turner //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
62c1f46dcSZachary Turner //
72c1f46dcSZachary Turner //===----------------------------------------------------------------------===//
82c1f46dcSZachary Turner 
959998b7bSJonas Devlieghere #include "lldb/Host/Config.h"
10d055e3a0SPedro Tammela #include "lldb/lldb-enumerations.h"
11d68983e3SPavel Labath 
124e26cf2cSJonas Devlieghere #if LLDB_ENABLE_PYTHON
13d68983e3SPavel Labath 
1441de9a97SKate Stone // LLDB Python header must be included first
152c1f46dcSZachary Turner #include "lldb-python.h"
1641de9a97SKate Stone 
172c1f46dcSZachary Turner #include "PythonDataObjects.h"
189357b5d0Sserge-sans-paille #include "PythonReadline.h"
191f6a57c1SMed Ismail Bennani #include "SWIGPythonBridge.h"
2063dd5d25SJonas Devlieghere #include "ScriptInterpreterPythonImpl.h"
211f6a57c1SMed Ismail Bennani #include "ScriptedProcessPythonInterface.h"
221f6a57c1SMed Ismail Bennani 
231f6a57c1SMed Ismail Bennani #include "lldb/API/SBError.h"
2441ae8e74SKuba Mracek #include "lldb/API/SBFrame.h"
2563dd5d25SJonas Devlieghere #include "lldb/API/SBValue.h"
262c1f46dcSZachary Turner #include "lldb/Breakpoint/StoppointCallbackContext.h"
272c1f46dcSZachary Turner #include "lldb/Breakpoint/WatchpointOptions.h"
282c1f46dcSZachary Turner #include "lldb/Core/Communication.h"
292c1f46dcSZachary Turner #include "lldb/Core/Debugger.h"
302c1f46dcSZachary Turner #include "lldb/Core/PluginManager.h"
312c1f46dcSZachary Turner #include "lldb/Core/ValueObject.h"
322c1f46dcSZachary Turner #include "lldb/DataFormatters/TypeSummary.h"
334eff2d31SZachary Turner #include "lldb/Host/FileSystem.h"
342c1f46dcSZachary Turner #include "lldb/Host/HostInfo.h"
352c1f46dcSZachary Turner #include "lldb/Host/Pipe.h"
362c1f46dcSZachary Turner #include "lldb/Interpreter/CommandInterpreter.h"
372c1f46dcSZachary Turner #include "lldb/Interpreter/CommandReturnObject.h"
382c1f46dcSZachary Turner #include "lldb/Target/Thread.h"
392c1f46dcSZachary Turner #include "lldb/Target/ThreadPlan.h"
405861234eSJonas Devlieghere #include "lldb/Utility/ReproducerInstrumentation.h"
4138d0632eSPavel Labath #include "lldb/Utility/Timer.h"
4222c8efcdSZachary Turner #include "llvm/ADT/STLExtras.h"
43b9c1b51eSKate Stone #include "llvm/ADT/StringRef.h"
44d79273c9SJonas Devlieghere #include "llvm/Support/Error.h"
457d86ee5aSZachary Turner #include "llvm/Support/FileSystem.h"
462fce1137SLawrence D'Anna #include "llvm/Support/FormatAdapters.h"
472c1f46dcSZachary Turner 
4876e47d48SRaphael Isemann #include <cstdio>
4976e47d48SRaphael Isemann #include <cstdlib>
509a6c7572SJonas Devlieghere #include <memory>
519a6c7572SJonas Devlieghere #include <mutex>
529a6c7572SJonas Devlieghere #include <string>
539a6c7572SJonas Devlieghere 
542c1f46dcSZachary Turner using namespace lldb;
552c1f46dcSZachary Turner using namespace lldb_private;
56722b6189SLawrence D'Anna using namespace lldb_private::python;
5704edd189SLawrence D'Anna using llvm::Expected;
582c1f46dcSZachary Turner 
59bba9ba8dSJonas Devlieghere LLDB_PLUGIN_DEFINE(ScriptInterpreterPython)
60fbb4d1e4SJonas Devlieghere 
61b01b1087SJonas Devlieghere // Defined in the SWIG source file
62b01b1087SJonas Devlieghere #if PY_MAJOR_VERSION >= 3
63b01b1087SJonas Devlieghere extern "C" PyObject *PyInit__lldb(void);
64b01b1087SJonas Devlieghere 
65b01b1087SJonas Devlieghere #define LLDBSwigPyInit PyInit__lldb
66b01b1087SJonas Devlieghere 
67b01b1087SJonas Devlieghere #else
68b01b1087SJonas Devlieghere extern "C" void init_lldb(void);
69b01b1087SJonas Devlieghere 
70b01b1087SJonas Devlieghere #define LLDBSwigPyInit init_lldb
71b01b1087SJonas Devlieghere #endif
72b01b1087SJonas Devlieghere 
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:
2399494c510SJonas Devlieghere   InitializePythonRAII() {
240079fe48aSZachary Turner     InitializePythonHome();
241079fe48aSZachary Turner 
2429357b5d0Sserge-sans-paille #ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
2439357b5d0Sserge-sans-paille     // Python's readline is incompatible with libedit being linked into lldb.
2449357b5d0Sserge-sans-paille     // Provide a patched version local to the embedded interpreter.
2459357b5d0Sserge-sans-paille     bool ReadlinePatched = false;
2469357b5d0Sserge-sans-paille     for (auto *p = PyImport_Inittab; p->name != NULL; p++) {
2479357b5d0Sserge-sans-paille       if (strcmp(p->name, "readline") == 0) {
2489357b5d0Sserge-sans-paille         p->initfunc = initlldb_readline;
2499357b5d0Sserge-sans-paille         break;
2509357b5d0Sserge-sans-paille       }
2519357b5d0Sserge-sans-paille     }
2529357b5d0Sserge-sans-paille     if (!ReadlinePatched) {
2539357b5d0Sserge-sans-paille       PyImport_AppendInittab("readline", initlldb_readline);
2549357b5d0Sserge-sans-paille       ReadlinePatched = true;
2559357b5d0Sserge-sans-paille     }
2569357b5d0Sserge-sans-paille #endif
2579357b5d0Sserge-sans-paille 
25874587a0eSVadim Chugunov     // Register _lldb as a built-in module.
25905495c5dSJonas Devlieghere     PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
26074587a0eSVadim Chugunov 
261079fe48aSZachary Turner // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
262079fe48aSZachary Turner // calling `Py_Initialize` and `PyEval_InitThreads`.  < 3.2 requires that you
263079fe48aSZachary Turner // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
264079fe48aSZachary Turner #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
265079fe48aSZachary Turner     Py_InitializeEx(0);
266079fe48aSZachary Turner     InitializeThreadsPrivate();
267079fe48aSZachary Turner #else
268079fe48aSZachary Turner     InitializeThreadsPrivate();
269079fe48aSZachary Turner     Py_InitializeEx(0);
270079fe48aSZachary Turner #endif
271079fe48aSZachary Turner   }
272079fe48aSZachary Turner 
273b9c1b51eSKate Stone   ~InitializePythonRAII() {
274b9c1b51eSKate Stone     if (m_was_already_initialized) {
2753b7e1981SPavel Labath       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
2763b7e1981SPavel Labath       LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
2771b6700efSTatyana Krasnukha                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
278079fe48aSZachary Turner       PyGILState_Release(m_gil_state);
279b9c1b51eSKate Stone     } else {
280079fe48aSZachary Turner       // We initialized the threads in this function, just unlock the GIL.
281079fe48aSZachary Turner       PyEval_SaveThread();
282079fe48aSZachary Turner     }
283079fe48aSZachary Turner   }
284079fe48aSZachary Turner 
285079fe48aSZachary Turner private:
286b9c1b51eSKate Stone   void InitializePythonHome() {
2873ec3f62fSHaibo Huang #if LLDB_EMBED_PYTHON_HOME
2883ec3f62fSHaibo Huang #if PY_MAJOR_VERSION >= 3
2893ec3f62fSHaibo Huang     typedef wchar_t* str_type;
2903ec3f62fSHaibo Huang #else
2913ec3f62fSHaibo Huang     typedef char* str_type;
2923ec3f62fSHaibo Huang #endif
2933ec3f62fSHaibo Huang     static str_type g_python_home = []() -> str_type {
2943ec3f62fSHaibo Huang       const char *lldb_python_home = LLDB_PYTHON_HOME;
2953ec3f62fSHaibo Huang       const char *absolute_python_home = nullptr;
2963ec3f62fSHaibo Huang       llvm::SmallString<64> path;
2973ec3f62fSHaibo Huang       if (llvm::sys::path::is_absolute(lldb_python_home)) {
2983ec3f62fSHaibo Huang         absolute_python_home = lldb_python_home;
2993ec3f62fSHaibo Huang       } else {
3003ec3f62fSHaibo Huang         FileSpec spec = HostInfo::GetShlibDir();
3013ec3f62fSHaibo Huang         if (!spec)
3023ec3f62fSHaibo Huang           return nullptr;
3033ec3f62fSHaibo Huang         spec.GetPath(path);
3043ec3f62fSHaibo Huang         llvm::sys::path::append(path, lldb_python_home);
3053ec3f62fSHaibo Huang         absolute_python_home = path.c_str();
3063ec3f62fSHaibo Huang       }
30722c8efcdSZachary Turner #if PY_MAJOR_VERSION >= 3
30822c8efcdSZachary Turner       size_t size = 0;
3093ec3f62fSHaibo Huang       return Py_DecodeLocale(absolute_python_home, &size);
31022c8efcdSZachary Turner #else
3113ec3f62fSHaibo Huang       return strdup(absolute_python_home);
31222c8efcdSZachary Turner #endif
3133ec3f62fSHaibo Huang     }();
3143ec3f62fSHaibo Huang     if (g_python_home != nullptr) {
315079fe48aSZachary Turner       Py_SetPythonHome(g_python_home);
3163ec3f62fSHaibo Huang     }
317386f00dbSDavide Italiano #else
318386f00dbSDavide Italiano #if defined(__APPLE__) && PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION == 7
31963dd5d25SJonas Devlieghere     // For Darwin, the only Python version supported is the one shipped in the
32063dd5d25SJonas Devlieghere     // OS OS and linked with lldb. Other installation of Python may have higher
3214f9cb260SDavide Italiano     // priorities in the path, overriding PYTHONHOME and causing
3224f9cb260SDavide Italiano     // problems/incompatibilities. In order to avoid confusion, always hardcode
3234f9cb260SDavide Italiano     // the PythonHome to be right, as it's not going to change.
32463dd5d25SJonas Devlieghere     static char path[] =
32563dd5d25SJonas Devlieghere         "/System/Library/Frameworks/Python.framework/Versions/2.7";
3264f9cb260SDavide Italiano     Py_SetPythonHome(path);
327386f00dbSDavide Italiano #endif
328386f00dbSDavide Italiano #endif
32922c8efcdSZachary Turner   }
33022c8efcdSZachary Turner 
331b9c1b51eSKate Stone   void InitializeThreadsPrivate() {
3321b6700efSTatyana Krasnukha // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself,
3331b6700efSTatyana Krasnukha // so there is no way to determine whether the embedded interpreter
3341b6700efSTatyana Krasnukha // was already initialized by some external code. `PyEval_ThreadsInitialized`
3351b6700efSTatyana Krasnukha // would always return `true` and `PyGILState_Ensure/Release` flow would be
3361b6700efSTatyana Krasnukha // executed instead of unlocking GIL with `PyEval_SaveThread`. When
3371b6700efSTatyana Krasnukha // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock.
3381b6700efSTatyana Krasnukha #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3)
3391b6700efSTatyana Krasnukha     // The only case we should go further and acquire the GIL: it is unlocked.
3401b6700efSTatyana Krasnukha     if (PyGILState_Check())
3411b6700efSTatyana Krasnukha       return;
3421b6700efSTatyana Krasnukha #endif
3431b6700efSTatyana Krasnukha 
344b9c1b51eSKate Stone     if (PyEval_ThreadsInitialized()) {
3453b7e1981SPavel Labath       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
346079fe48aSZachary Turner 
347079fe48aSZachary Turner       m_was_already_initialized = true;
348079fe48aSZachary Turner       m_gil_state = PyGILState_Ensure();
3493b7e1981SPavel Labath       LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n",
350079fe48aSZachary Turner                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
351079fe48aSZachary Turner       return;
352079fe48aSZachary Turner     }
353079fe48aSZachary Turner 
354079fe48aSZachary Turner     // InitThreads acquires the GIL if it hasn't been called before.
355079fe48aSZachary Turner     PyEval_InitThreads();
356079fe48aSZachary Turner   }
357079fe48aSZachary Turner 
3589494c510SJonas Devlieghere   PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
3599494c510SJonas Devlieghere   bool m_was_already_initialized = false;
360079fe48aSZachary Turner };
36163dd5d25SJonas Devlieghere } // namespace
3622c1f46dcSZachary Turner 
3632df331b0SPavel Labath void ScriptInterpreterPython::ComputePythonDirForApple(
3642df331b0SPavel Labath     llvm::SmallVectorImpl<char> &path) {
3652df331b0SPavel Labath   auto style = llvm::sys::path::Style::posix;
3662df331b0SPavel Labath 
3672df331b0SPavel Labath   llvm::StringRef path_ref(path.begin(), path.size());
3682df331b0SPavel Labath   auto rbegin = llvm::sys::path::rbegin(path_ref, style);
3692df331b0SPavel Labath   auto rend = llvm::sys::path::rend(path_ref);
3702df331b0SPavel Labath   auto framework = std::find(rbegin, rend, "LLDB.framework");
3712df331b0SPavel Labath   if (framework == rend) {
37261f471a7SHaibo Huang     ComputePythonDir(path);
3732df331b0SPavel Labath     return;
3742df331b0SPavel Labath   }
3752df331b0SPavel Labath   path.resize(framework - rend);
3762df331b0SPavel Labath   llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
3772df331b0SPavel Labath }
3782df331b0SPavel Labath 
37961f471a7SHaibo Huang void ScriptInterpreterPython::ComputePythonDir(
3802df331b0SPavel Labath     llvm::SmallVectorImpl<char> &path) {
3812df331b0SPavel Labath   // Build the path by backing out of the lib dir, then building with whatever
3822df331b0SPavel Labath   // the real python interpreter uses.  (e.g. lib for most, lib64 on RHEL
38361f471a7SHaibo Huang   // x86_64, or bin on Windows).
38461f471a7SHaibo Huang   llvm::sys::path::remove_filename(path);
38561f471a7SHaibo Huang   llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
3860016b450SHaibo Huang 
3870016b450SHaibo Huang #if defined(_WIN32)
3880016b450SHaibo Huang   // This will be injected directly through FileSpec.GetDirectory().SetString(),
3890016b450SHaibo Huang   // so we need to normalize manually.
3900016b450SHaibo Huang   std::replace(path.begin(), path.end(), '\\', '/');
3910016b450SHaibo Huang #endif
3922df331b0SPavel Labath }
3932df331b0SPavel Labath 
3942df331b0SPavel Labath FileSpec ScriptInterpreterPython::GetPythonDir() {
3952df331b0SPavel Labath   static FileSpec g_spec = []() {
3962df331b0SPavel Labath     FileSpec spec = HostInfo::GetShlibDir();
3972df331b0SPavel Labath     if (!spec)
3982df331b0SPavel Labath       return FileSpec();
3992df331b0SPavel Labath     llvm::SmallString<64> path;
4002df331b0SPavel Labath     spec.GetPath(path);
4012df331b0SPavel Labath 
4022df331b0SPavel Labath #if defined(__APPLE__)
4032df331b0SPavel Labath     ComputePythonDirForApple(path);
4042df331b0SPavel Labath #else
40561f471a7SHaibo Huang     ComputePythonDir(path);
4062df331b0SPavel Labath #endif
4072df331b0SPavel Labath     spec.GetDirectory().SetString(path);
4082df331b0SPavel Labath     return spec;
4092df331b0SPavel Labath   }();
4102df331b0SPavel Labath   return g_spec;
4112df331b0SPavel Labath }
4122df331b0SPavel Labath 
413*bbef51ebSLawrence D'Anna StructuredData::DictionarySP ScriptInterpreterPython::GetInterpreterInfo() {
414*bbef51ebSLawrence D'Anna   GIL gil;
415*bbef51ebSLawrence D'Anna   FileSpec python_dir_spec = GetPythonDir();
416*bbef51ebSLawrence D'Anna   if (!python_dir_spec)
417*bbef51ebSLawrence D'Anna     return nullptr;
418*bbef51ebSLawrence D'Anna   PythonString python_dir(python_dir_spec.GetPath());
419*bbef51ebSLawrence D'Anna   PythonDictionary info(PyInitialValue::Empty);
420*bbef51ebSLawrence D'Anna   llvm::Error error = info.SetItem("lldb-pythonpath", python_dir);
421*bbef51ebSLawrence D'Anna   if (error)
422*bbef51ebSLawrence D'Anna     return nullptr;
423*bbef51ebSLawrence D'Anna   static const char script[] = R"(
424*bbef51ebSLawrence D'Anna def main(info):
425*bbef51ebSLawrence D'Anna   import sys
426*bbef51ebSLawrence D'Anna   import os
427*bbef51ebSLawrence D'Anna   name = 'python' + str(sys.version_info.major)
428*bbef51ebSLawrence D'Anna   info.update({
429*bbef51ebSLawrence D'Anna     "language": "python",
430*bbef51ebSLawrence D'Anna     "prefix": sys.prefix,
431*bbef51ebSLawrence D'Anna     "executable": os.path.join(sys.prefix, "bin", name),
432*bbef51ebSLawrence D'Anna   })
433*bbef51ebSLawrence D'Anna   return info
434*bbef51ebSLawrence D'Anna )";
435*bbef51ebSLawrence D'Anna   PythonScript get_info(script);
436*bbef51ebSLawrence D'Anna   auto info_json = unwrapIgnoringErrors(As<PythonDictionary>(get_info(info)));
437*bbef51ebSLawrence D'Anna   if (!info_json)
438*bbef51ebSLawrence D'Anna     return nullptr;
439*bbef51ebSLawrence D'Anna   return info_json.CreateStructuredDictionary();
440*bbef51ebSLawrence D'Anna }
441*bbef51ebSLawrence D'Anna 
442004a264fSPavel Labath void ScriptInterpreterPython::SharedLibraryDirectoryHelper(
443004a264fSPavel Labath     FileSpec &this_file) {
444004a264fSPavel Labath   // When we're loaded from python, this_file will point to the file inside the
445004a264fSPavel Labath   // python package directory. Replace it with the one in the lib directory.
446004a264fSPavel Labath #ifdef _WIN32
447004a264fSPavel Labath   // On windows, we need to manually back out of the python tree, and go into
448004a264fSPavel Labath   // the bin directory. This is pretty much the inverse of what ComputePythonDir
449004a264fSPavel Labath   // does.
450004a264fSPavel Labath   if (this_file.GetFileNameExtension() == ConstString(".pyd")) {
451004a264fSPavel Labath     this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd
452004a264fSPavel Labath     this_file.RemoveLastPathComponent(); // lldb
4532e826088SPavel Labath     llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
4542e826088SPavel Labath     for (auto it = llvm::sys::path::begin(libdir),
4552e826088SPavel Labath               end = llvm::sys::path::end(libdir);
456004a264fSPavel Labath          it != end; ++it)
457004a264fSPavel Labath       this_file.RemoveLastPathComponent();
458004a264fSPavel Labath     this_file.AppendPathComponent("bin");
459004a264fSPavel Labath     this_file.AppendPathComponent("liblldb.dll");
460004a264fSPavel Labath   }
461004a264fSPavel Labath #else
462004a264fSPavel Labath   // The python file is a symlink, so we can find the real library by resolving
463004a264fSPavel Labath   // it. We can do this unconditionally.
464004a264fSPavel Labath   FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
465004a264fSPavel Labath #endif
466004a264fSPavel Labath }
467004a264fSPavel Labath 
4685f4980f0SPavel Labath llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() {
46963dd5d25SJonas Devlieghere   return "Embedded Python interpreter";
47063dd5d25SJonas Devlieghere }
47163dd5d25SJonas Devlieghere 
47263dd5d25SJonas Devlieghere void ScriptInterpreterPython::Initialize() {
47363dd5d25SJonas Devlieghere   static llvm::once_flag g_once_flag;
47463dd5d25SJonas Devlieghere 
47563dd5d25SJonas Devlieghere   llvm::call_once(g_once_flag, []() {
47663dd5d25SJonas Devlieghere     PluginManager::RegisterPlugin(GetPluginNameStatic(),
47763dd5d25SJonas Devlieghere                                   GetPluginDescriptionStatic(),
47863dd5d25SJonas Devlieghere                                   lldb::eScriptLanguagePython,
47963dd5d25SJonas Devlieghere                                   ScriptInterpreterPythonImpl::CreateInstance);
48063dd5d25SJonas Devlieghere   });
48163dd5d25SJonas Devlieghere }
48263dd5d25SJonas Devlieghere 
48363dd5d25SJonas Devlieghere void ScriptInterpreterPython::Terminate() {}
48463dd5d25SJonas Devlieghere 
48563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::Locker(
48663dd5d25SJonas Devlieghere     ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
487b07823f3SLawrence D'Anna     uint16_t on_leave, FileSP in, FileSP out, FileSP err)
48863dd5d25SJonas Devlieghere     : ScriptInterpreterLocker(),
48963dd5d25SJonas Devlieghere       m_teardown_session((on_leave & TearDownSession) == TearDownSession),
49063dd5d25SJonas Devlieghere       m_python_interpreter(py_interpreter) {
4915861234eSJonas Devlieghere   repro::Recorder::PrivateThread();
49263dd5d25SJonas Devlieghere   DoAcquireLock();
49363dd5d25SJonas Devlieghere   if ((on_entry & InitSession) == InitSession) {
49463dd5d25SJonas Devlieghere     if (!DoInitSession(on_entry, in, out, err)) {
49563dd5d25SJonas Devlieghere       // Don't teardown the session if we didn't init it.
49663dd5d25SJonas Devlieghere       m_teardown_session = false;
49763dd5d25SJonas Devlieghere     }
49863dd5d25SJonas Devlieghere   }
49963dd5d25SJonas Devlieghere }
50063dd5d25SJonas Devlieghere 
50163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
50263dd5d25SJonas Devlieghere   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
50363dd5d25SJonas Devlieghere   m_GILState = PyGILState_Ensure();
50463dd5d25SJonas Devlieghere   LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked",
50563dd5d25SJonas Devlieghere             m_GILState == PyGILState_UNLOCKED ? "un" : "");
50663dd5d25SJonas Devlieghere 
50763dd5d25SJonas Devlieghere   // we need to save the thread state when we first start the command because
50863dd5d25SJonas Devlieghere   // we might decide to interrupt it while some action is taking place outside
50963dd5d25SJonas Devlieghere   // of Python (e.g. printing to screen, waiting for the network, ...) in that
51063dd5d25SJonas Devlieghere   // case, _PyThreadState_Current will be NULL - and we would be unable to set
51163dd5d25SJonas Devlieghere   // the asynchronous exception - not a desirable situation
51263dd5d25SJonas Devlieghere   m_python_interpreter->SetThreadState(PyThreadState_Get());
51363dd5d25SJonas Devlieghere   m_python_interpreter->IncrementLockCount();
51463dd5d25SJonas Devlieghere   return true;
51563dd5d25SJonas Devlieghere }
51663dd5d25SJonas Devlieghere 
51763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
518b07823f3SLawrence D'Anna                                                         FileSP in, FileSP out,
519b07823f3SLawrence D'Anna                                                         FileSP err) {
52063dd5d25SJonas Devlieghere   if (!m_python_interpreter)
52163dd5d25SJonas Devlieghere     return false;
52263dd5d25SJonas Devlieghere   return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
52363dd5d25SJonas Devlieghere }
52463dd5d25SJonas Devlieghere 
52563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
52663dd5d25SJonas Devlieghere   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
52763dd5d25SJonas Devlieghere   LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
52863dd5d25SJonas Devlieghere             m_GILState == PyGILState_UNLOCKED ? "un" : "");
52963dd5d25SJonas Devlieghere   PyGILState_Release(m_GILState);
53063dd5d25SJonas Devlieghere   m_python_interpreter->DecrementLockCount();
53163dd5d25SJonas Devlieghere   return true;
53263dd5d25SJonas Devlieghere }
53363dd5d25SJonas Devlieghere 
53463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
53563dd5d25SJonas Devlieghere   if (!m_python_interpreter)
53663dd5d25SJonas Devlieghere     return false;
53763dd5d25SJonas Devlieghere   m_python_interpreter->LeaveSession();
53863dd5d25SJonas Devlieghere   return true;
53963dd5d25SJonas Devlieghere }
54063dd5d25SJonas Devlieghere 
54163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::~Locker() {
54263dd5d25SJonas Devlieghere   if (m_teardown_session)
54363dd5d25SJonas Devlieghere     DoTearDownSession();
54463dd5d25SJonas Devlieghere   DoFreeLock();
54563dd5d25SJonas Devlieghere }
54663dd5d25SJonas Devlieghere 
5478d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger)
5488d1fb843SJonas Devlieghere     : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
54963dd5d25SJonas Devlieghere       m_saved_stderr(), m_main_module(),
55063dd5d25SJonas Devlieghere       m_session_dict(PyInitialValue::Invalid),
55163dd5d25SJonas Devlieghere       m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(),
55263dd5d25SJonas Devlieghere       m_run_one_line_str_global(),
5538d1fb843SJonas Devlieghere       m_dictionary_name(m_debugger.GetInstanceName().AsCString()),
554ea1752a7SJonas Devlieghere       m_active_io_handler(eIOHandlerNone), m_session_is_active(false),
55564ec505dSJonas Devlieghere       m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
556ea1752a7SJonas Devlieghere       m_command_thread_state(nullptr) {
55763dd5d25SJonas Devlieghere   InitializePrivate();
55863dd5d25SJonas Devlieghere 
5591f6a57c1SMed Ismail Bennani   m_scripted_process_interface_up =
5601f6a57c1SMed Ismail Bennani       std::make_unique<ScriptedProcessPythonInterface>(*this);
5611f6a57c1SMed Ismail Bennani 
56263dd5d25SJonas Devlieghere   m_dictionary_name.append("_dict");
56363dd5d25SJonas Devlieghere   StreamString run_string;
56463dd5d25SJonas Devlieghere   run_string.Printf("%s = dict()", m_dictionary_name.c_str());
56563dd5d25SJonas Devlieghere 
56663dd5d25SJonas Devlieghere   Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock);
56763dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
56863dd5d25SJonas Devlieghere 
56963dd5d25SJonas Devlieghere   run_string.Clear();
57063dd5d25SJonas Devlieghere   run_string.Printf(
57163dd5d25SJonas Devlieghere       "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
57263dd5d25SJonas Devlieghere       m_dictionary_name.c_str());
57363dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
57463dd5d25SJonas Devlieghere 
57563dd5d25SJonas Devlieghere   // Reloading modules requires a different syntax in Python 2 and Python 3.
57663dd5d25SJonas Devlieghere   // This provides a consistent syntax no matter what version of Python.
57763dd5d25SJonas Devlieghere   run_string.Clear();
57863dd5d25SJonas Devlieghere   run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')",
57963dd5d25SJonas Devlieghere                     m_dictionary_name.c_str());
58063dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
58163dd5d25SJonas Devlieghere 
58263dd5d25SJonas Devlieghere   // WARNING: temporary code that loads Cocoa formatters - this should be done
58363dd5d25SJonas Devlieghere   // on a per-platform basis rather than loading the whole set and letting the
58463dd5d25SJonas Devlieghere   // individual formatter classes exploit APIs to check whether they can/cannot
58563dd5d25SJonas Devlieghere   // do their task
58663dd5d25SJonas Devlieghere   run_string.Clear();
58763dd5d25SJonas Devlieghere   run_string.Printf(
58863dd5d25SJonas Devlieghere       "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')",
58963dd5d25SJonas Devlieghere       m_dictionary_name.c_str());
59063dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
59163dd5d25SJonas Devlieghere   run_string.Clear();
59263dd5d25SJonas Devlieghere 
59363dd5d25SJonas Devlieghere   run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
59463dd5d25SJonas Devlieghere                     "lldb.embedded_interpreter import run_python_interpreter; "
59563dd5d25SJonas Devlieghere                     "from lldb.embedded_interpreter import run_one_line')",
59663dd5d25SJonas Devlieghere                     m_dictionary_name.c_str());
59763dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
59863dd5d25SJonas Devlieghere   run_string.Clear();
59963dd5d25SJonas Devlieghere 
60063dd5d25SJonas Devlieghere   run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
60163dd5d25SJonas Devlieghere                     "; pydoc.pager = pydoc.plainpager')",
6028d1fb843SJonas Devlieghere                     m_dictionary_name.c_str(), m_debugger.GetID());
60363dd5d25SJonas Devlieghere   PyRun_SimpleString(run_string.GetData());
60463dd5d25SJonas Devlieghere }
60563dd5d25SJonas Devlieghere 
60663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
60763dd5d25SJonas Devlieghere   // the session dictionary may hold objects with complex state which means
60863dd5d25SJonas Devlieghere   // that they may need to be torn down with some level of smarts and that, in
60963dd5d25SJonas Devlieghere   // turn, requires a valid thread state force Python to procure itself such a
61063dd5d25SJonas Devlieghere   // thread state, nuke the session dictionary and then release it for others
61163dd5d25SJonas Devlieghere   // to use and proceed with the rest of the shutdown
61263dd5d25SJonas Devlieghere   auto gil_state = PyGILState_Ensure();
61363dd5d25SJonas Devlieghere   m_session_dict.Reset();
61463dd5d25SJonas Devlieghere   PyGILState_Release(gil_state);
61563dd5d25SJonas Devlieghere }
61663dd5d25SJonas Devlieghere 
61763dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler,
61863dd5d25SJonas Devlieghere                                                      bool interactive) {
6192c1f46dcSZachary Turner   const char *instructions = nullptr;
6202c1f46dcSZachary Turner 
621b9c1b51eSKate Stone   switch (m_active_io_handler) {
6222c1f46dcSZachary Turner   case eIOHandlerNone:
6232c1f46dcSZachary Turner     break;
6242c1f46dcSZachary Turner   case eIOHandlerBreakpoint:
6252c1f46dcSZachary Turner     instructions = R"(Enter your Python command(s). Type 'DONE' to end.
6262c1f46dcSZachary Turner def function (frame, bp_loc, internal_dict):
6272c1f46dcSZachary Turner     """frame: the lldb.SBFrame for the location at which you stopped
6282c1f46dcSZachary Turner        bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
6292c1f46dcSZachary Turner        internal_dict: an LLDB support object not to be used"""
6302c1f46dcSZachary Turner )";
6312c1f46dcSZachary Turner     break;
6322c1f46dcSZachary Turner   case eIOHandlerWatchpoint:
6332c1f46dcSZachary Turner     instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
6342c1f46dcSZachary Turner     break;
6352c1f46dcSZachary Turner   }
6362c1f46dcSZachary Turner 
637b9c1b51eSKate Stone   if (instructions) {
6387ca15ba7SLawrence D'Anna     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
6390affb582SDave Lee     if (output_sp && interactive) {
6402c1f46dcSZachary Turner       output_sp->PutCString(instructions);
6412c1f46dcSZachary Turner       output_sp->Flush();
6422c1f46dcSZachary Turner     }
6432c1f46dcSZachary Turner   }
6442c1f46dcSZachary Turner }
6452c1f46dcSZachary Turner 
64663dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler,
647b9c1b51eSKate Stone                                                          std::string &data) {
6482c1f46dcSZachary Turner   io_handler.SetIsDone(true);
6498d1fb843SJonas Devlieghere   bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
6502c1f46dcSZachary Turner 
651b9c1b51eSKate Stone   switch (m_active_io_handler) {
6522c1f46dcSZachary Turner   case eIOHandlerNone:
6532c1f46dcSZachary Turner     break;
654b9c1b51eSKate Stone   case eIOHandlerBreakpoint: {
655cfb96d84SJim Ingham     std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
656cfb96d84SJim Ingham         (std::vector<std::reference_wrapper<BreakpointOptions>> *)
657cfb96d84SJim Ingham             io_handler.GetUserData();
658cfb96d84SJim Ingham     for (BreakpointOptions &bp_options : *bp_options_vec) {
6592c1f46dcSZachary Turner 
660a8f3ae7cSJonas Devlieghere       auto data_up = std::make_unique<CommandDataPython>();
661d5b44036SJonas Devlieghere       if (!data_up)
6624e4fbe82SZachary Turner         break;
663d5b44036SJonas Devlieghere       data_up->user_source.SplitIntoLines(data);
6642c1f46dcSZachary Turner 
665738af7a6SJim Ingham       StructuredData::ObjectSP empty_args_sp;
666d5b44036SJonas Devlieghere       if (GenerateBreakpointCommandCallbackData(data_up->user_source,
667738af7a6SJim Ingham                                                 data_up->script_source,
668738af7a6SJim Ingham                                                 false)
669b9c1b51eSKate Stone               .Success()) {
6704e4fbe82SZachary Turner         auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
671d5b44036SJonas Devlieghere             std::move(data_up));
672cfb96d84SJim Ingham         bp_options.SetCallback(
67363dd5d25SJonas Devlieghere             ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
674b9c1b51eSKate Stone       } else if (!batch_mode) {
6757ca15ba7SLawrence D'Anna         StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
676b9c1b51eSKate Stone         if (error_sp) {
6772c1f46dcSZachary Turner           error_sp->Printf("Warning: No command attached to breakpoint.\n");
6782c1f46dcSZachary Turner           error_sp->Flush();
6792c1f46dcSZachary Turner         }
6802c1f46dcSZachary Turner       }
6812c1f46dcSZachary Turner     }
6822c1f46dcSZachary Turner     m_active_io_handler = eIOHandlerNone;
683b9c1b51eSKate Stone   } break;
684b9c1b51eSKate Stone   case eIOHandlerWatchpoint: {
685b9c1b51eSKate Stone     WatchpointOptions *wp_options =
686b9c1b51eSKate Stone         (WatchpointOptions *)io_handler.GetUserData();
687a8f3ae7cSJonas Devlieghere     auto data_up = std::make_unique<WatchpointOptions::CommandData>();
688d5b44036SJonas Devlieghere     data_up->user_source.SplitIntoLines(data);
6892c1f46dcSZachary Turner 
690d5b44036SJonas Devlieghere     if (GenerateWatchpointCommandCallbackData(data_up->user_source,
691d5b44036SJonas Devlieghere                                               data_up->script_source)) {
6924e4fbe82SZachary Turner       auto baton_sp =
693d5b44036SJonas Devlieghere           std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
694b9c1b51eSKate Stone       wp_options->SetCallback(
69563dd5d25SJonas Devlieghere           ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
696b9c1b51eSKate Stone     } else if (!batch_mode) {
6977ca15ba7SLawrence D'Anna       StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
698b9c1b51eSKate Stone       if (error_sp) {
6992c1f46dcSZachary Turner         error_sp->Printf("Warning: No command attached to breakpoint.\n");
7002c1f46dcSZachary Turner         error_sp->Flush();
7012c1f46dcSZachary Turner       }
7022c1f46dcSZachary Turner     }
7032c1f46dcSZachary Turner     m_active_io_handler = eIOHandlerNone;
704b9c1b51eSKate Stone   } break;
7052c1f46dcSZachary Turner   }
7062c1f46dcSZachary Turner }
7072c1f46dcSZachary Turner 
70863dd5d25SJonas Devlieghere lldb::ScriptInterpreterSP
7098d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) {
7108d1fb843SJonas Devlieghere   return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
71163dd5d25SJonas Devlieghere }
7122c1f46dcSZachary Turner 
71363dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::LeaveSession() {
7142c1f46dcSZachary Turner   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
7152c1f46dcSZachary Turner   if (log)
71663dd5d25SJonas Devlieghere     log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
7172c1f46dcSZachary Turner 
71820b52c33SJonas Devlieghere   // Unset the LLDB global variables.
71920b52c33SJonas Devlieghere   PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
72020b52c33SJonas Devlieghere                      "= None; lldb.thread = None; lldb.frame = None");
72120b52c33SJonas Devlieghere 
72205097246SAdrian Prantl   // checking that we have a valid thread state - since we use our own
72305097246SAdrian Prantl   // threading and locking in some (rare) cases during cleanup Python may end
72405097246SAdrian Prantl   // up believing we have no thread state and PyImport_AddModule will crash if
72505097246SAdrian Prantl   // that is the case - since that seems to only happen when destroying the
72605097246SAdrian Prantl   // SBDebugger, we can make do without clearing up stdout and stderr
7272c1f46dcSZachary Turner 
7282c1f46dcSZachary Turner   // rdar://problem/11292882
729b9c1b51eSKate Stone   // When the current thread state is NULL, PyThreadState_Get() issues a fatal
730b9c1b51eSKate Stone   // error.
731b9c1b51eSKate Stone   if (PyThreadState_GetDict()) {
7322c1f46dcSZachary Turner     PythonDictionary &sys_module_dict = GetSysModuleDictionary();
733b9c1b51eSKate Stone     if (sys_module_dict.IsValid()) {
734b9c1b51eSKate Stone       if (m_saved_stdin.IsValid()) {
735f8b22f8fSZachary Turner         sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
7362c1f46dcSZachary Turner         m_saved_stdin.Reset();
7372c1f46dcSZachary Turner       }
738b9c1b51eSKate Stone       if (m_saved_stdout.IsValid()) {
739f8b22f8fSZachary Turner         sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
7402c1f46dcSZachary Turner         m_saved_stdout.Reset();
7412c1f46dcSZachary Turner       }
742b9c1b51eSKate Stone       if (m_saved_stderr.IsValid()) {
743f8b22f8fSZachary Turner         sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
7442c1f46dcSZachary Turner         m_saved_stderr.Reset();
7452c1f46dcSZachary Turner       }
7462c1f46dcSZachary Turner     }
7472c1f46dcSZachary Turner   }
7482c1f46dcSZachary Turner 
7492c1f46dcSZachary Turner   m_session_is_active = false;
7502c1f46dcSZachary Turner }
7512c1f46dcSZachary Turner 
752b07823f3SLawrence D'Anna bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp,
753b07823f3SLawrence D'Anna                                                const char *py_name,
754b07823f3SLawrence D'Anna                                                PythonObject &save_file,
755b9c1b51eSKate Stone                                                const char *mode) {
756b07823f3SLawrence D'Anna   if (!file_sp || !*file_sp) {
757b07823f3SLawrence D'Anna     save_file.Reset();
758b07823f3SLawrence D'Anna     return false;
759b07823f3SLawrence D'Anna   }
760b07823f3SLawrence D'Anna   File &file = *file_sp;
761b07823f3SLawrence D'Anna 
762a31baf08SGreg Clayton   // Flush the file before giving it to python to avoid interleaved output.
763a31baf08SGreg Clayton   file.Flush();
764a31baf08SGreg Clayton 
765a31baf08SGreg Clayton   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
766a31baf08SGreg Clayton 
7670f783599SLawrence D'Anna   auto new_file = PythonFile::FromFile(file, mode);
7680f783599SLawrence D'Anna   if (!new_file) {
7690f783599SLawrence D'Anna     llvm::consumeError(new_file.takeError());
7700f783599SLawrence D'Anna     return false;
7710f783599SLawrence D'Anna   }
7720f783599SLawrence D'Anna 
773b07823f3SLawrence D'Anna   save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
774a31baf08SGreg Clayton 
7750f783599SLawrence D'Anna   sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
776a31baf08SGreg Clayton   return true;
777a31baf08SGreg Clayton }
778a31baf08SGreg Clayton 
77963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
780b07823f3SLawrence D'Anna                                                FileSP in_sp, FileSP out_sp,
781b07823f3SLawrence D'Anna                                                FileSP err_sp) {
782b9c1b51eSKate Stone   // If we have already entered the session, without having officially 'left'
78305097246SAdrian Prantl   // it, then there is no need to 'enter' it again.
7842c1f46dcSZachary Turner   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
785b9c1b51eSKate Stone   if (m_session_is_active) {
78663e5fb76SJonas Devlieghere     LLDB_LOGF(
78763e5fb76SJonas Devlieghere         log,
78863dd5d25SJonas Devlieghere         "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
789b9c1b51eSKate Stone         ") session is already active, returning without doing anything",
790b9c1b51eSKate Stone         on_entry_flags);
7912c1f46dcSZachary Turner     return false;
7922c1f46dcSZachary Turner   }
7932c1f46dcSZachary Turner 
79463e5fb76SJonas Devlieghere   LLDB_LOGF(
79563e5fb76SJonas Devlieghere       log,
79663e5fb76SJonas Devlieghere       "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
797b9c1b51eSKate Stone       on_entry_flags);
7982c1f46dcSZachary Turner 
7992c1f46dcSZachary Turner   m_session_is_active = true;
8002c1f46dcSZachary Turner 
8012c1f46dcSZachary Turner   StreamString run_string;
8022c1f46dcSZachary Turner 
803b9c1b51eSKate Stone   if (on_entry_flags & Locker::InitGlobals) {
804b9c1b51eSKate Stone     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
8058d1fb843SJonas Devlieghere                       m_dictionary_name.c_str(), m_debugger.GetID());
806b9c1b51eSKate Stone     run_string.Printf(
807b9c1b51eSKate Stone         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
8088d1fb843SJonas Devlieghere         m_debugger.GetID());
8092c1f46dcSZachary Turner     run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
8102c1f46dcSZachary Turner     run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
8112c1f46dcSZachary Turner     run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
8122c1f46dcSZachary Turner     run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
8132c1f46dcSZachary Turner     run_string.PutCString("')");
814b9c1b51eSKate Stone   } else {
81505097246SAdrian Prantl     // If we aren't initing the globals, we should still always set the
81605097246SAdrian Prantl     // debugger (since that is always unique.)
817b9c1b51eSKate Stone     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
8188d1fb843SJonas Devlieghere                       m_dictionary_name.c_str(), m_debugger.GetID());
819b9c1b51eSKate Stone     run_string.Printf(
820b9c1b51eSKate Stone         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
8218d1fb843SJonas Devlieghere         m_debugger.GetID());
8222c1f46dcSZachary Turner     run_string.PutCString("')");
8232c1f46dcSZachary Turner   }
8242c1f46dcSZachary Turner 
8252c1f46dcSZachary Turner   PyRun_SimpleString(run_string.GetData());
8262c1f46dcSZachary Turner   run_string.Clear();
8272c1f46dcSZachary Turner 
8282c1f46dcSZachary Turner   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
829b9c1b51eSKate Stone   if (sys_module_dict.IsValid()) {
830b07823f3SLawrence D'Anna     lldb::FileSP top_in_sp;
831b07823f3SLawrence D'Anna     lldb::StreamFileSP top_out_sp, top_err_sp;
832b07823f3SLawrence D'Anna     if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
833b07823f3SLawrence D'Anna       m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
834b07823f3SLawrence D'Anna                                                  top_err_sp);
8352c1f46dcSZachary Turner 
836b9c1b51eSKate Stone     if (on_entry_flags & Locker::NoSTDIN) {
8372c1f46dcSZachary Turner       m_saved_stdin.Reset();
838b9c1b51eSKate Stone     } else {
839b07823f3SLawrence D'Anna       if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
840b07823f3SLawrence D'Anna         if (top_in_sp)
841b07823f3SLawrence D'Anna           SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
8422c1f46dcSZachary Turner       }
843a31baf08SGreg Clayton     }
844a31baf08SGreg Clayton 
845b07823f3SLawrence D'Anna     if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
846b07823f3SLawrence D'Anna       if (top_out_sp)
847b07823f3SLawrence D'Anna         SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w");
848a31baf08SGreg Clayton     }
849a31baf08SGreg Clayton 
850b07823f3SLawrence D'Anna     if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
851b07823f3SLawrence D'Anna       if (top_err_sp)
852b07823f3SLawrence D'Anna         SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w");
853a31baf08SGreg Clayton     }
8542c1f46dcSZachary Turner   }
8552c1f46dcSZachary Turner 
8562c1f46dcSZachary Turner   if (PyErr_Occurred())
8572c1f46dcSZachary Turner     PyErr_Clear();
8582c1f46dcSZachary Turner 
8592c1f46dcSZachary Turner   return true;
8602c1f46dcSZachary Turner }
8612c1f46dcSZachary Turner 
86204edd189SLawrence D'Anna PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
863f8b22f8fSZachary Turner   if (!m_main_module.IsValid())
86404edd189SLawrence D'Anna     m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__"));
8652c1f46dcSZachary Turner   return m_main_module;
8662c1f46dcSZachary Turner }
8672c1f46dcSZachary Turner 
86863dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
869f8b22f8fSZachary Turner   if (m_session_dict.IsValid())
870f8b22f8fSZachary Turner     return m_session_dict;
871f8b22f8fSZachary Turner 
8722c1f46dcSZachary Turner   PythonObject &main_module = GetMainModule();
873f8b22f8fSZachary Turner   if (!main_module.IsValid())
874f8b22f8fSZachary Turner     return m_session_dict;
875f8b22f8fSZachary Turner 
876b9c1b51eSKate Stone   PythonDictionary main_dict(PyRefType::Borrowed,
877b9c1b51eSKate Stone                              PyModule_GetDict(main_module.get()));
878f8b22f8fSZachary Turner   if (!main_dict.IsValid())
879f8b22f8fSZachary Turner     return m_session_dict;
880f8b22f8fSZachary Turner 
881722b6189SLawrence D'Anna   m_session_dict = unwrapIgnoringErrors(
882722b6189SLawrence D'Anna       As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
8832c1f46dcSZachary Turner   return m_session_dict;
8842c1f46dcSZachary Turner }
8852c1f46dcSZachary Turner 
88663dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
887f8b22f8fSZachary Turner   if (m_sys_module_dict.IsValid())
888f8b22f8fSZachary Turner     return m_sys_module_dict;
889722b6189SLawrence D'Anna   PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys"));
890722b6189SLawrence D'Anna   m_sys_module_dict = sys_module.GetDictionary();
8912c1f46dcSZachary Turner   return m_sys_module_dict;
8922c1f46dcSZachary Turner }
8932c1f46dcSZachary Turner 
894a69bbe02SLawrence D'Anna llvm::Expected<unsigned>
895a69bbe02SLawrence D'Anna ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
896a69bbe02SLawrence D'Anna     const llvm::StringRef &callable_name) {
897738af7a6SJim Ingham   if (callable_name.empty()) {
898738af7a6SJim Ingham     return llvm::createStringError(
899738af7a6SJim Ingham         llvm::inconvertibleErrorCode(),
900738af7a6SJim Ingham         "called with empty callable name.");
901738af7a6SJim Ingham   }
902738af7a6SJim Ingham   Locker py_lock(this, Locker::AcquireLock |
903738af7a6SJim Ingham                  Locker::InitSession |
904738af7a6SJim Ingham                  Locker::NoSTDIN);
905738af7a6SJim Ingham   auto dict = PythonModule::MainModule()
906738af7a6SJim Ingham       .ResolveName<PythonDictionary>(m_dictionary_name);
907a69bbe02SLawrence D'Anna   auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
908a69bbe02SLawrence D'Anna       callable_name, dict);
909738af7a6SJim Ingham   if (!pfunc.IsAllocated()) {
910738af7a6SJim Ingham     return llvm::createStringError(
911738af7a6SJim Ingham         llvm::inconvertibleErrorCode(),
912738af7a6SJim Ingham         "can't find callable: %s", callable_name.str().c_str());
913738af7a6SJim Ingham   }
914adbf64ccSLawrence D'Anna   llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
915adbf64ccSLawrence D'Anna   if (!arg_info)
916adbf64ccSLawrence D'Anna     return arg_info.takeError();
917adbf64ccSLawrence D'Anna   return arg_info.get().max_positional_args;
918738af7a6SJim Ingham }
919738af7a6SJim Ingham 
920b9c1b51eSKate Stone static std::string GenerateUniqueName(const char *base_name_wanted,
9212c1f46dcSZachary Turner                                       uint32_t &functions_counter,
922b9c1b51eSKate Stone                                       const void *name_token = nullptr) {
9232c1f46dcSZachary Turner   StreamString sstr;
9242c1f46dcSZachary Turner 
9252c1f46dcSZachary Turner   if (!base_name_wanted)
9262c1f46dcSZachary Turner     return std::string();
9272c1f46dcSZachary Turner 
9282c1f46dcSZachary Turner   if (!name_token)
9292c1f46dcSZachary Turner     sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
9302c1f46dcSZachary Turner   else
9312c1f46dcSZachary Turner     sstr.Printf("%s_%p", base_name_wanted, name_token);
9322c1f46dcSZachary Turner 
933adcd0268SBenjamin Kramer   return std::string(sstr.GetString());
9342c1f46dcSZachary Turner }
9352c1f46dcSZachary Turner 
93663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
937f8b22f8fSZachary Turner   if (m_run_one_line_function.IsValid())
938f8b22f8fSZachary Turner     return true;
939f8b22f8fSZachary Turner 
940b9c1b51eSKate Stone   PythonObject module(PyRefType::Borrowed,
941b9c1b51eSKate Stone                       PyImport_AddModule("lldb.embedded_interpreter"));
942f8b22f8fSZachary Turner   if (!module.IsValid())
943f8b22f8fSZachary Turner     return false;
944f8b22f8fSZachary Turner 
945b9c1b51eSKate Stone   PythonDictionary module_dict(PyRefType::Borrowed,
946b9c1b51eSKate Stone                                PyModule_GetDict(module.get()));
947f8b22f8fSZachary Turner   if (!module_dict.IsValid())
948f8b22f8fSZachary Turner     return false;
949f8b22f8fSZachary Turner 
950b9c1b51eSKate Stone   m_run_one_line_function =
951b9c1b51eSKate Stone       module_dict.GetItemForKey(PythonString("run_one_line"));
952b9c1b51eSKate Stone   m_run_one_line_str_global =
953b9c1b51eSKate Stone       module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
954f8b22f8fSZachary Turner   return m_run_one_line_function.IsValid();
9552c1f46dcSZachary Turner }
9562c1f46dcSZachary Turner 
95763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLine(
9584d51a902SRaphael Isemann     llvm::StringRef command, CommandReturnObject *result,
959b9c1b51eSKate Stone     const ExecuteScriptOptions &options) {
960d6c062bcSRaphael Isemann   std::string command_str = command.str();
961d6c062bcSRaphael Isemann 
9622c1f46dcSZachary Turner   if (!m_valid_session)
9632c1f46dcSZachary Turner     return false;
9642c1f46dcSZachary Turner 
9654d51a902SRaphael Isemann   if (!command.empty()) {
966b9c1b51eSKate Stone     // We want to call run_one_line, passing in the dictionary and the command
96705097246SAdrian Prantl     // string.  We cannot do this through PyRun_SimpleString here because the
96805097246SAdrian Prantl     // command string may contain escaped characters, and putting it inside
969b9c1b51eSKate Stone     // another string to pass to PyRun_SimpleString messes up the escaping.  So
97005097246SAdrian Prantl     // we use the following more complicated method to pass the command string
97105097246SAdrian Prantl     // directly down to Python.
972d79273c9SJonas Devlieghere     llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
97384228365SJonas Devlieghere         io_redirect_or_error = ScriptInterpreterIORedirect::Create(
97484228365SJonas Devlieghere             options.GetEnableIO(), m_debugger, result);
975d79273c9SJonas Devlieghere     if (!io_redirect_or_error) {
976d79273c9SJonas Devlieghere       if (result)
977d79273c9SJonas Devlieghere         result->AppendErrorWithFormatv(
978d79273c9SJonas Devlieghere             "failed to redirect I/O: {0}\n",
979d79273c9SJonas Devlieghere             llvm::fmt_consume(io_redirect_or_error.takeError()));
980d79273c9SJonas Devlieghere       else
981d79273c9SJonas Devlieghere         llvm::consumeError(io_redirect_or_error.takeError());
9822fce1137SLawrence D'Anna       return false;
9832fce1137SLawrence D'Anna     }
984d79273c9SJonas Devlieghere 
985d79273c9SJonas Devlieghere     ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
9862c1f46dcSZachary Turner 
98732064024SZachary Turner     bool success = false;
98832064024SZachary Turner     {
98905097246SAdrian Prantl       // WARNING!  It's imperative that this RAII scope be as tight as
99005097246SAdrian Prantl       // possible. In particular, the scope must end *before* we try to join
99105097246SAdrian Prantl       // the read thread.  The reason for this is that a pre-requisite for
99205097246SAdrian Prantl       // joining the read thread is that we close the write handle (to break
99305097246SAdrian Prantl       // the pipe and cause it to wake up and exit).  But acquiring the GIL as
99405097246SAdrian Prantl       // below will redirect Python's stdio to use this same handle.  If we
99505097246SAdrian Prantl       // close the handle while Python is still using it, bad things will
99605097246SAdrian Prantl       // happen.
997b9c1b51eSKate Stone       Locker locker(
998b9c1b51eSKate Stone           this,
99963dd5d25SJonas Devlieghere           Locker::AcquireLock | Locker::InitSession |
100063dd5d25SJonas Devlieghere               (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
10012c1f46dcSZachary Turner               ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
1002d79273c9SJonas Devlieghere           Locker::FreeAcquiredLock | Locker::TearDownSession,
1003d79273c9SJonas Devlieghere           io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1004d79273c9SJonas Devlieghere           io_redirect.GetErrorFile());
10052c1f46dcSZachary Turner 
10062c1f46dcSZachary Turner       // Find the correct script interpreter dictionary in the main module.
10072c1f46dcSZachary Turner       PythonDictionary &session_dict = GetSessionDictionary();
1008b9c1b51eSKate Stone       if (session_dict.IsValid()) {
1009b9c1b51eSKate Stone         if (GetEmbeddedInterpreterModuleObjects()) {
1010b9c1b51eSKate Stone           if (PyCallable_Check(m_run_one_line_function.get())) {
1011b9c1b51eSKate Stone             PythonObject pargs(
1012b9c1b51eSKate Stone                 PyRefType::Owned,
1013d6c062bcSRaphael Isemann                 Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
1014b9c1b51eSKate Stone             if (pargs.IsValid()) {
1015b9c1b51eSKate Stone               PythonObject return_value(
1016b9c1b51eSKate Stone                   PyRefType::Owned,
1017b9c1b51eSKate Stone                   PyObject_CallObject(m_run_one_line_function.get(),
1018b9c1b51eSKate Stone                                       pargs.get()));
1019f8b22f8fSZachary Turner               if (return_value.IsValid())
10202c1f46dcSZachary Turner                 success = true;
1021b9c1b51eSKate Stone               else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
10222c1f46dcSZachary Turner                 PyErr_Print();
10232c1f46dcSZachary Turner                 PyErr_Clear();
10242c1f46dcSZachary Turner               }
10252c1f46dcSZachary Turner             }
10262c1f46dcSZachary Turner           }
10272c1f46dcSZachary Turner         }
10282c1f46dcSZachary Turner       }
10292c1f46dcSZachary Turner 
1030d79273c9SJonas Devlieghere       io_redirect.Flush();
10312c1f46dcSZachary Turner     }
10322c1f46dcSZachary Turner 
10332c1f46dcSZachary Turner     if (success)
10342c1f46dcSZachary Turner       return true;
10352c1f46dcSZachary Turner 
10362c1f46dcSZachary Turner     // The one-liner failed.  Append the error message.
10374d51a902SRaphael Isemann     if (result) {
1038b9c1b51eSKate Stone       result->AppendErrorWithFormat(
10394d51a902SRaphael Isemann           "python failed attempting to evaluate '%s'\n", command_str.c_str());
10404d51a902SRaphael Isemann     }
10412c1f46dcSZachary Turner     return false;
10422c1f46dcSZachary Turner   }
10432c1f46dcSZachary Turner 
10442c1f46dcSZachary Turner   if (result)
10452c1f46dcSZachary Turner     result->AppendError("empty command passed to python\n");
10462c1f46dcSZachary Turner   return false;
10472c1f46dcSZachary Turner }
10482c1f46dcSZachary Turner 
104963dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
10505c1c8443SJonas Devlieghere   LLDB_SCOPED_TIMER();
10512c1f46dcSZachary Turner 
10528d1fb843SJonas Devlieghere   Debugger &debugger = m_debugger;
10532c1f46dcSZachary Turner 
1054b9c1b51eSKate Stone   // At the moment, the only time the debugger does not have an input file
105505097246SAdrian Prantl   // handle is when this is called directly from Python, in which case it is
105605097246SAdrian Prantl   // both dangerous and unnecessary (not to mention confusing) to try to embed
105705097246SAdrian Prantl   // a running interpreter loop inside the already running Python interpreter
105805097246SAdrian Prantl   // loop, so we won't do it.
10592c1f46dcSZachary Turner 
10607ca15ba7SLawrence D'Anna   if (!debugger.GetInputFile().IsValid())
10612c1f46dcSZachary Turner     return;
10622c1f46dcSZachary Turner 
10632c1f46dcSZachary Turner   IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
1064b9c1b51eSKate Stone   if (io_handler_sp) {
10657ce2de2cSJonas Devlieghere     debugger.RunIOHandlerAsync(io_handler_sp);
10662c1f46dcSZachary Turner   }
10672c1f46dcSZachary Turner }
10682c1f46dcSZachary Turner 
106963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Interrupt() {
10702c1f46dcSZachary Turner   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
10712c1f46dcSZachary Turner 
1072b9c1b51eSKate Stone   if (IsExecutingPython()) {
1073b1cf558dSEnrico Granata     PyThreadState *state = PyThreadState_GET();
10742c1f46dcSZachary Turner     if (!state)
10752c1f46dcSZachary Turner       state = GetThreadState();
1076b9c1b51eSKate Stone     if (state) {
10772c1f46dcSZachary Turner       long tid = state->thread_id;
107822c8efcdSZachary Turner       PyThreadState_Swap(state);
10792c1f46dcSZachary Turner       int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
108063e5fb76SJonas Devlieghere       LLDB_LOGF(log,
108163e5fb76SJonas Devlieghere                 "ScriptInterpreterPythonImpl::Interrupt() sending "
1082b9c1b51eSKate Stone                 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
1083b9c1b51eSKate Stone                 tid, num_threads);
10842c1f46dcSZachary Turner       return true;
10852c1f46dcSZachary Turner     }
10862c1f46dcSZachary Turner   }
108763e5fb76SJonas Devlieghere   LLDB_LOGF(log,
108863dd5d25SJonas Devlieghere             "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
1089b9c1b51eSKate Stone             "can't interrupt");
10902c1f46dcSZachary Turner   return false;
10912c1f46dcSZachary Turner }
109204edd189SLawrence D'Anna 
109363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
10944d51a902SRaphael Isemann     llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
1095b9c1b51eSKate Stone     void *ret_value, const ExecuteScriptOptions &options) {
10962c1f46dcSZachary Turner 
1097f9517353SJonas Devlieghere   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1098f9517353SJonas Devlieghere       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1099f9517353SJonas Devlieghere           options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1100f9517353SJonas Devlieghere 
1101f9517353SJonas Devlieghere   if (!io_redirect_or_error) {
1102f9517353SJonas Devlieghere     llvm::consumeError(io_redirect_or_error.takeError());
1103f9517353SJonas Devlieghere     return false;
1104f9517353SJonas Devlieghere   }
1105f9517353SJonas Devlieghere 
1106f9517353SJonas Devlieghere   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1107f9517353SJonas Devlieghere 
110863dd5d25SJonas Devlieghere   Locker locker(this,
110963dd5d25SJonas Devlieghere                 Locker::AcquireLock | Locker::InitSession |
111063dd5d25SJonas Devlieghere                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1111b9c1b51eSKate Stone                     Locker::NoSTDIN,
1112f9517353SJonas Devlieghere                 Locker::FreeAcquiredLock | Locker::TearDownSession,
1113f9517353SJonas Devlieghere                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1114f9517353SJonas Devlieghere                 io_redirect.GetErrorFile());
11152c1f46dcSZachary Turner 
111604edd189SLawrence D'Anna   PythonModule &main_module = GetMainModule();
111704edd189SLawrence D'Anna   PythonDictionary globals = main_module.GetDictionary();
11182c1f46dcSZachary Turner 
11192c1f46dcSZachary Turner   PythonDictionary locals = GetSessionDictionary();
112004edd189SLawrence D'Anna   if (!locals.IsValid())
1121722b6189SLawrence D'Anna     locals = unwrapIgnoringErrors(
1122722b6189SLawrence D'Anna         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1123f8b22f8fSZachary Turner   if (!locals.IsValid())
11242c1f46dcSZachary Turner     locals = globals;
11252c1f46dcSZachary Turner 
112604edd189SLawrence D'Anna   Expected<PythonObject> maybe_py_return =
112704edd189SLawrence D'Anna       runStringOneLine(in_string, globals, locals);
11282c1f46dcSZachary Turner 
112904edd189SLawrence D'Anna   if (!maybe_py_return) {
113004edd189SLawrence D'Anna     llvm::handleAllErrors(
113104edd189SLawrence D'Anna         maybe_py_return.takeError(),
113204edd189SLawrence D'Anna         [&](PythonException &E) {
113304edd189SLawrence D'Anna           E.Restore();
113404edd189SLawrence D'Anna           if (options.GetMaskoutErrors()) {
113504edd189SLawrence D'Anna             if (E.Matches(PyExc_SyntaxError)) {
113604edd189SLawrence D'Anna               PyErr_Print();
11372c1f46dcSZachary Turner             }
113804edd189SLawrence D'Anna             PyErr_Clear();
113904edd189SLawrence D'Anna           }
114004edd189SLawrence D'Anna         },
114104edd189SLawrence D'Anna         [](const llvm::ErrorInfoBase &E) {});
114204edd189SLawrence D'Anna     return false;
11432c1f46dcSZachary Turner   }
11442c1f46dcSZachary Turner 
114504edd189SLawrence D'Anna   PythonObject py_return = std::move(maybe_py_return.get());
114604edd189SLawrence D'Anna   assert(py_return.IsValid());
114704edd189SLawrence D'Anna 
1148b9c1b51eSKate Stone   switch (return_type) {
11492c1f46dcSZachary Turner   case eScriptReturnTypeCharPtr: // "char *"
11502c1f46dcSZachary Turner   {
11512c1f46dcSZachary Turner     const char format[3] = "s#";
115204edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
11532c1f46dcSZachary Turner   }
1154b9c1b51eSKate Stone   case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
1155b9c1b51eSKate Stone                                        // Py_None
11562c1f46dcSZachary Turner   {
11572c1f46dcSZachary Turner     const char format[3] = "z";
115804edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
11592c1f46dcSZachary Turner   }
1160b9c1b51eSKate Stone   case eScriptReturnTypeBool: {
11612c1f46dcSZachary Turner     const char format[2] = "b";
116204edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
11632c1f46dcSZachary Turner   }
1164b9c1b51eSKate Stone   case eScriptReturnTypeShortInt: {
11652c1f46dcSZachary Turner     const char format[2] = "h";
116604edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (short *)ret_value);
11672c1f46dcSZachary Turner   }
1168b9c1b51eSKate Stone   case eScriptReturnTypeShortIntUnsigned: {
11692c1f46dcSZachary Turner     const char format[2] = "H";
117004edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
11712c1f46dcSZachary Turner   }
1172b9c1b51eSKate Stone   case eScriptReturnTypeInt: {
11732c1f46dcSZachary Turner     const char format[2] = "i";
117404edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (int *)ret_value);
11752c1f46dcSZachary Turner   }
1176b9c1b51eSKate Stone   case eScriptReturnTypeIntUnsigned: {
11772c1f46dcSZachary Turner     const char format[2] = "I";
117804edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
11792c1f46dcSZachary Turner   }
1180b9c1b51eSKate Stone   case eScriptReturnTypeLongInt: {
11812c1f46dcSZachary Turner     const char format[2] = "l";
118204edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (long *)ret_value);
11832c1f46dcSZachary Turner   }
1184b9c1b51eSKate Stone   case eScriptReturnTypeLongIntUnsigned: {
11852c1f46dcSZachary Turner     const char format[2] = "k";
118604edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
11872c1f46dcSZachary Turner   }
1188b9c1b51eSKate Stone   case eScriptReturnTypeLongLong: {
11892c1f46dcSZachary Turner     const char format[2] = "L";
119004edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
11912c1f46dcSZachary Turner   }
1192b9c1b51eSKate Stone   case eScriptReturnTypeLongLongUnsigned: {
11932c1f46dcSZachary Turner     const char format[2] = "K";
119404edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format,
119504edd189SLawrence D'Anna                        (unsigned long long *)ret_value);
11962c1f46dcSZachary Turner   }
1197b9c1b51eSKate Stone   case eScriptReturnTypeFloat: {
11982c1f46dcSZachary Turner     const char format[2] = "f";
119904edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (float *)ret_value);
12002c1f46dcSZachary Turner   }
1201b9c1b51eSKate Stone   case eScriptReturnTypeDouble: {
12022c1f46dcSZachary Turner     const char format[2] = "d";
120304edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (double *)ret_value);
12042c1f46dcSZachary Turner   }
1205b9c1b51eSKate Stone   case eScriptReturnTypeChar: {
12062c1f46dcSZachary Turner     const char format[2] = "c";
120704edd189SLawrence D'Anna     return PyArg_Parse(py_return.get(), format, (char *)ret_value);
12082c1f46dcSZachary Turner   }
1209b9c1b51eSKate Stone   case eScriptReturnTypeOpaqueObject: {
121004edd189SLawrence D'Anna     *((PyObject **)ret_value) = py_return.release();
121104edd189SLawrence D'Anna     return true;
12122c1f46dcSZachary Turner   }
12132c1f46dcSZachary Turner   }
12141dfb1a85SPavel Labath   llvm_unreachable("Fully covered switch!");
12152c1f46dcSZachary Turner }
12162c1f46dcSZachary Turner 
121763dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1218b9c1b51eSKate Stone     const char *in_string, const ExecuteScriptOptions &options) {
121904edd189SLawrence D'Anna 
122004edd189SLawrence D'Anna   if (in_string == nullptr)
122104edd189SLawrence D'Anna     return Status();
12222c1f46dcSZachary Turner 
1223f9517353SJonas Devlieghere   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1224f9517353SJonas Devlieghere       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1225f9517353SJonas Devlieghere           options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1226f9517353SJonas Devlieghere 
1227f9517353SJonas Devlieghere   if (!io_redirect_or_error)
1228f9517353SJonas Devlieghere     return Status(io_redirect_or_error.takeError());
1229f9517353SJonas Devlieghere 
1230f9517353SJonas Devlieghere   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1231f9517353SJonas Devlieghere 
123263dd5d25SJonas Devlieghere   Locker locker(this,
123363dd5d25SJonas Devlieghere                 Locker::AcquireLock | Locker::InitSession |
123463dd5d25SJonas Devlieghere                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1235b9c1b51eSKate Stone                     Locker::NoSTDIN,
1236f9517353SJonas Devlieghere                 Locker::FreeAcquiredLock | Locker::TearDownSession,
1237f9517353SJonas Devlieghere                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1238f9517353SJonas Devlieghere                 io_redirect.GetErrorFile());
12392c1f46dcSZachary Turner 
124004edd189SLawrence D'Anna   PythonModule &main_module = GetMainModule();
124104edd189SLawrence D'Anna   PythonDictionary globals = main_module.GetDictionary();
12422c1f46dcSZachary Turner 
12432c1f46dcSZachary Turner   PythonDictionary locals = GetSessionDictionary();
1244f8b22f8fSZachary Turner   if (!locals.IsValid())
1245722b6189SLawrence D'Anna     locals = unwrapIgnoringErrors(
1246722b6189SLawrence D'Anna         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1247f8b22f8fSZachary Turner   if (!locals.IsValid())
12482c1f46dcSZachary Turner     locals = globals;
12492c1f46dcSZachary Turner 
125004edd189SLawrence D'Anna   Expected<PythonObject> return_value =
125104edd189SLawrence D'Anna       runStringMultiLine(in_string, globals, locals);
12522c1f46dcSZachary Turner 
125304edd189SLawrence D'Anna   if (!return_value) {
125404edd189SLawrence D'Anna     llvm::Error error =
125504edd189SLawrence D'Anna         llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
125604edd189SLawrence D'Anna           llvm::Error error = llvm::createStringError(
125704edd189SLawrence D'Anna               llvm::inconvertibleErrorCode(), E.ReadBacktrace());
125804edd189SLawrence D'Anna           if (!options.GetMaskoutErrors())
125904edd189SLawrence D'Anna             E.Restore();
12602c1f46dcSZachary Turner           return error;
126104edd189SLawrence D'Anna         });
126204edd189SLawrence D'Anna     return Status(std::move(error));
126304edd189SLawrence D'Anna   }
126404edd189SLawrence D'Anna 
126504edd189SLawrence D'Anna   return Status();
12662c1f46dcSZachary Turner }
12672c1f46dcSZachary Turner 
126863dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1269cfb96d84SJim Ingham     std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1270b9c1b51eSKate Stone     CommandReturnObject &result) {
12712c1f46dcSZachary Turner   m_active_io_handler = eIOHandlerBreakpoint;
12728d1fb843SJonas Devlieghere   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1273a6faf851SJonas Devlieghere       "    ", *this, &bp_options_vec);
12742c1f46dcSZachary Turner }
12752c1f46dcSZachary Turner 
127663dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1277b9c1b51eSKate Stone     WatchpointOptions *wp_options, CommandReturnObject &result) {
12782c1f46dcSZachary Turner   m_active_io_handler = eIOHandlerWatchpoint;
12798d1fb843SJonas Devlieghere   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1280a6faf851SJonas Devlieghere       "    ", *this, wp_options);
12812c1f46dcSZachary Turner }
12822c1f46dcSZachary Turner 
1283738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1284cfb96d84SJim Ingham     BreakpointOptions &bp_options, const char *function_name,
1285738af7a6SJim Ingham     StructuredData::ObjectSP extra_args_sp) {
1286738af7a6SJim Ingham   Status error;
12872c1f46dcSZachary Turner   // For now just cons up a oneliner that calls the provided function.
12882c1f46dcSZachary Turner   std::string oneliner("return ");
12892c1f46dcSZachary Turner   oneliner += function_name;
1290738af7a6SJim Ingham 
1291a69bbe02SLawrence D'Anna   llvm::Expected<unsigned> maybe_args =
1292a69bbe02SLawrence D'Anna       GetMaxPositionalArgumentsForCallable(function_name);
1293738af7a6SJim Ingham   if (!maybe_args) {
1294a69bbe02SLawrence D'Anna     error.SetErrorStringWithFormat(
1295a69bbe02SLawrence D'Anna         "could not get num args: %s",
1296738af7a6SJim Ingham         llvm::toString(maybe_args.takeError()).c_str());
1297738af7a6SJim Ingham     return error;
1298738af7a6SJim Ingham   }
1299a69bbe02SLawrence D'Anna   size_t max_args = *maybe_args;
1300738af7a6SJim Ingham 
1301738af7a6SJim Ingham   bool uses_extra_args = false;
1302a69bbe02SLawrence D'Anna   if (max_args >= 4) {
1303738af7a6SJim Ingham     uses_extra_args = true;
1304738af7a6SJim Ingham     oneliner += "(frame, bp_loc, extra_args, internal_dict)";
1305a69bbe02SLawrence D'Anna   } else if (max_args >= 3) {
1306738af7a6SJim Ingham     if (extra_args_sp) {
1307738af7a6SJim Ingham       error.SetErrorString("cannot pass extra_args to a three argument callback"
1308738af7a6SJim Ingham                           );
1309738af7a6SJim Ingham       return error;
1310738af7a6SJim Ingham     }
1311738af7a6SJim Ingham     uses_extra_args = false;
13122c1f46dcSZachary Turner     oneliner += "(frame, bp_loc, internal_dict)";
1313738af7a6SJim Ingham   } else {
1314738af7a6SJim Ingham     error.SetErrorStringWithFormat("expected 3 or 4 argument "
1315a69bbe02SLawrence D'Anna                                    "function, %s can only take %zu",
1316a69bbe02SLawrence D'Anna                                    function_name, max_args);
1317738af7a6SJim Ingham     return error;
1318738af7a6SJim Ingham   }
1319738af7a6SJim Ingham 
1320738af7a6SJim Ingham   SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp,
1321738af7a6SJim Ingham                                uses_extra_args);
1322738af7a6SJim Ingham   return error;
13232c1f46dcSZachary Turner }
13242c1f46dcSZachary Turner 
132563dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1326cfb96d84SJim Ingham     BreakpointOptions &bp_options,
1327f7e07256SJim Ingham     std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
132897206d57SZachary Turner   Status error;
1329f7e07256SJim Ingham   error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1330738af7a6SJim Ingham                                                 cmd_data_up->script_source,
1331738af7a6SJim Ingham                                                 false);
1332f7e07256SJim Ingham   if (error.Fail()) {
1333f7e07256SJim Ingham     return error;
1334f7e07256SJim Ingham   }
1335f7e07256SJim Ingham   auto baton_sp =
1336f7e07256SJim Ingham       std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1337cfb96d84SJim Ingham   bp_options.SetCallback(
133863dd5d25SJonas Devlieghere       ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1339f7e07256SJim Ingham   return error;
1340f7e07256SJim Ingham }
1341f7e07256SJim Ingham 
134263dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1343cfb96d84SJim Ingham     BreakpointOptions &bp_options, const char *command_body_text) {
1344738af7a6SJim Ingham   return SetBreakpointCommandCallback(bp_options, command_body_text, {},false);
1345738af7a6SJim Ingham }
13462c1f46dcSZachary Turner 
1347738af7a6SJim Ingham // Set a Python one-liner as the callback for the breakpoint.
1348738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1349cfb96d84SJim Ingham     BreakpointOptions &bp_options, const char *command_body_text,
1350cfb96d84SJim Ingham     StructuredData::ObjectSP extra_args_sp, bool uses_extra_args) {
1351738af7a6SJim Ingham   auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1352b9c1b51eSKate Stone   // Split the command_body_text into lines, and pass that to
135305097246SAdrian Prantl   // GenerateBreakpointCommandCallbackData.  That will wrap the body in an
135405097246SAdrian Prantl   // auto-generated function, and return the function name in script_source.
135505097246SAdrian Prantl   // That is what the callback will actually invoke.
13562c1f46dcSZachary Turner 
1357d5b44036SJonas Devlieghere   data_up->user_source.SplitIntoLines(command_body_text);
1358d5b44036SJonas Devlieghere   Status error = GenerateBreakpointCommandCallbackData(data_up->user_source,
1359738af7a6SJim Ingham                                                        data_up->script_source,
1360738af7a6SJim Ingham                                                        uses_extra_args);
1361b9c1b51eSKate Stone   if (error.Success()) {
13624e4fbe82SZachary Turner     auto baton_sp =
1363d5b44036SJonas Devlieghere         std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1364cfb96d84SJim Ingham     bp_options.SetCallback(
136563dd5d25SJonas Devlieghere         ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
13662c1f46dcSZachary Turner     return error;
136793571c3cSJonas Devlieghere   }
13682c1f46dcSZachary Turner   return error;
13692c1f46dcSZachary Turner }
13702c1f46dcSZachary Turner 
13712c1f46dcSZachary Turner // Set a Python one-liner as the callback for the watchpoint.
137263dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1373b9c1b51eSKate Stone     WatchpointOptions *wp_options, const char *oneliner) {
1374a8f3ae7cSJonas Devlieghere   auto data_up = std::make_unique<WatchpointOptions::CommandData>();
13752c1f46dcSZachary Turner 
13762c1f46dcSZachary Turner   // It's necessary to set both user_source and script_source to the oneliner.
1377b9c1b51eSKate Stone   // The former is used to generate callback description (as in watchpoint
137805097246SAdrian Prantl   // command list) while the latter is used for Python to interpret during the
137905097246SAdrian Prantl   // actual callback.
13802c1f46dcSZachary Turner 
1381d5b44036SJonas Devlieghere   data_up->user_source.AppendString(oneliner);
1382d5b44036SJonas Devlieghere   data_up->script_source.assign(oneliner);
13832c1f46dcSZachary Turner 
1384d5b44036SJonas Devlieghere   if (GenerateWatchpointCommandCallbackData(data_up->user_source,
1385d5b44036SJonas Devlieghere                                             data_up->script_source)) {
13864e4fbe82SZachary Turner     auto baton_sp =
1387d5b44036SJonas Devlieghere         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
138863dd5d25SJonas Devlieghere     wp_options->SetCallback(
138963dd5d25SJonas Devlieghere         ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
13902c1f46dcSZachary Turner   }
13912c1f46dcSZachary Turner 
13922c1f46dcSZachary Turner   return;
13932c1f46dcSZachary Turner }
13942c1f46dcSZachary Turner 
139563dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1396b9c1b51eSKate Stone     StringList &function_def) {
13972c1f46dcSZachary Turner   // Convert StringList to one long, newline delimited, const char *.
13982c1f46dcSZachary Turner   std::string function_def_string(function_def.CopyList());
13992c1f46dcSZachary Turner 
140097206d57SZachary Turner   Status error = ExecuteMultipleLines(
1401b9c1b51eSKate Stone       function_def_string.c_str(),
1402fd2433e1SJonas Devlieghere       ExecuteScriptOptions().SetEnableIO(false));
14032c1f46dcSZachary Turner   return error;
14042c1f46dcSZachary Turner }
14052c1f46dcSZachary Turner 
140663dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature,
1407b9c1b51eSKate Stone                                                      const StringList &input) {
140897206d57SZachary Turner   Status error;
14092c1f46dcSZachary Turner   int num_lines = input.GetSize();
1410b9c1b51eSKate Stone   if (num_lines == 0) {
14112c1f46dcSZachary Turner     error.SetErrorString("No input data.");
14122c1f46dcSZachary Turner     return error;
14132c1f46dcSZachary Turner   }
14142c1f46dcSZachary Turner 
1415b9c1b51eSKate Stone   if (!signature || *signature == 0) {
14162c1f46dcSZachary Turner     error.SetErrorString("No output function name.");
14172c1f46dcSZachary Turner     return error;
14182c1f46dcSZachary Turner   }
14192c1f46dcSZachary Turner 
14202c1f46dcSZachary Turner   StreamString sstr;
14212c1f46dcSZachary Turner   StringList auto_generated_function;
14222c1f46dcSZachary Turner   auto_generated_function.AppendString(signature);
1423b9c1b51eSKate Stone   auto_generated_function.AppendString(
1424b9c1b51eSKate Stone       "     global_dict = globals()"); // Grab the global dictionary
1425b9c1b51eSKate Stone   auto_generated_function.AppendString(
1426b9c1b51eSKate Stone       "     new_keys = internal_dict.keys()"); // Make a list of keys in the
1427b9c1b51eSKate Stone                                                // session dict
1428b9c1b51eSKate Stone   auto_generated_function.AppendString(
1429b9c1b51eSKate Stone       "     old_keys = global_dict.keys()"); // Save list of keys in global dict
1430b9c1b51eSKate Stone   auto_generated_function.AppendString(
1431b9c1b51eSKate Stone       "     global_dict.update (internal_dict)"); // Add the session dictionary
1432b9c1b51eSKate Stone                                                   // to the
14332c1f46dcSZachary Turner   // global dictionary.
14342c1f46dcSZachary Turner 
14352c1f46dcSZachary Turner   // Wrap everything up inside the function, increasing the indentation.
14362c1f46dcSZachary Turner 
14372c1f46dcSZachary Turner   auto_generated_function.AppendString("     if True:");
1438b9c1b51eSKate Stone   for (int i = 0; i < num_lines; ++i) {
14392c1f46dcSZachary Turner     sstr.Clear();
14402c1f46dcSZachary Turner     sstr.Printf("       %s", input.GetStringAtIndex(i));
14412c1f46dcSZachary Turner     auto_generated_function.AppendString(sstr.GetData());
14422c1f46dcSZachary Turner   }
1443b9c1b51eSKate Stone   auto_generated_function.AppendString(
1444b9c1b51eSKate Stone       "     for key in new_keys:"); // Iterate over all the keys from session
1445b9c1b51eSKate Stone                                     // dict
1446b9c1b51eSKate Stone   auto_generated_function.AppendString(
1447b9c1b51eSKate Stone       "         internal_dict[key] = global_dict[key]"); // Update session dict
1448b9c1b51eSKate Stone                                                          // values
1449b9c1b51eSKate Stone   auto_generated_function.AppendString(
1450b9c1b51eSKate Stone       "         if key not in old_keys:"); // If key was not originally in
1451b9c1b51eSKate Stone                                            // global dict
1452b9c1b51eSKate Stone   auto_generated_function.AppendString(
1453b9c1b51eSKate Stone       "             del global_dict[key]"); //  ...then remove key/value from
1454b9c1b51eSKate Stone                                             //  global dict
14552c1f46dcSZachary Turner 
14562c1f46dcSZachary Turner   // Verify that the results are valid Python.
14572c1f46dcSZachary Turner 
14582c1f46dcSZachary Turner   error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
14592c1f46dcSZachary Turner 
14602c1f46dcSZachary Turner   return error;
14612c1f46dcSZachary Turner }
14622c1f46dcSZachary Turner 
146363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1464b9c1b51eSKate Stone     StringList &user_input, std::string &output, const void *name_token) {
14652c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
14662c1f46dcSZachary Turner   user_input.RemoveBlankLines();
14672c1f46dcSZachary Turner   StreamString sstr;
14682c1f46dcSZachary Turner 
14692c1f46dcSZachary Turner   // Check to see if we have any data; if not, just return.
14702c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
14712c1f46dcSZachary Turner     return false;
14722c1f46dcSZachary Turner 
1473b9c1b51eSKate Stone   // Take what the user wrote, wrap it all up inside one big auto-generated
147405097246SAdrian Prantl   // Python function, passing in the ValueObject as parameter to the function.
14752c1f46dcSZachary Turner 
1476b9c1b51eSKate Stone   std::string auto_generated_function_name(
1477b9c1b51eSKate Stone       GenerateUniqueName("lldb_autogen_python_type_print_func",
1478b9c1b51eSKate Stone                          num_created_functions, name_token));
1479b9c1b51eSKate Stone   sstr.Printf("def %s (valobj, internal_dict):",
1480b9c1b51eSKate Stone               auto_generated_function_name.c_str());
14812c1f46dcSZachary Turner 
14822c1f46dcSZachary Turner   if (!GenerateFunction(sstr.GetData(), user_input).Success())
14832c1f46dcSZachary Turner     return false;
14842c1f46dcSZachary Turner 
14852c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
14862c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
14872c1f46dcSZachary Turner   return true;
14882c1f46dcSZachary Turner }
14892c1f46dcSZachary Turner 
149063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1491b9c1b51eSKate Stone     StringList &user_input, std::string &output) {
14922c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
14932c1f46dcSZachary Turner   user_input.RemoveBlankLines();
14942c1f46dcSZachary Turner   StreamString sstr;
14952c1f46dcSZachary Turner 
14962c1f46dcSZachary Turner   // Check to see if we have any data; if not, just return.
14972c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
14982c1f46dcSZachary Turner     return false;
14992c1f46dcSZachary Turner 
1500b9c1b51eSKate Stone   std::string auto_generated_function_name(GenerateUniqueName(
1501b9c1b51eSKate Stone       "lldb_autogen_python_cmd_alias_func", num_created_functions));
15022c1f46dcSZachary Turner 
1503b9c1b51eSKate Stone   sstr.Printf("def %s (debugger, args, result, internal_dict):",
1504b9c1b51eSKate Stone               auto_generated_function_name.c_str());
15052c1f46dcSZachary Turner 
15062c1f46dcSZachary Turner   if (!GenerateFunction(sstr.GetData(), user_input).Success())
15072c1f46dcSZachary Turner     return false;
15082c1f46dcSZachary Turner 
15092c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
15102c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
15112c1f46dcSZachary Turner   return true;
15122c1f46dcSZachary Turner }
15132c1f46dcSZachary Turner 
151463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
151563dd5d25SJonas Devlieghere     StringList &user_input, std::string &output, const void *name_token) {
15162c1f46dcSZachary Turner   static uint32_t num_created_classes = 0;
15172c1f46dcSZachary Turner   user_input.RemoveBlankLines();
15182c1f46dcSZachary Turner   int num_lines = user_input.GetSize();
15192c1f46dcSZachary Turner   StreamString sstr;
15202c1f46dcSZachary Turner 
15212c1f46dcSZachary Turner   // Check to see if we have any data; if not, just return.
15222c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
15232c1f46dcSZachary Turner     return false;
15242c1f46dcSZachary Turner 
15252c1f46dcSZachary Turner   // Wrap all user input into a Python class
15262c1f46dcSZachary Turner 
1527b9c1b51eSKate Stone   std::string auto_generated_class_name(GenerateUniqueName(
1528b9c1b51eSKate Stone       "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
15292c1f46dcSZachary Turner 
15302c1f46dcSZachary Turner   StringList auto_generated_class;
15312c1f46dcSZachary Turner 
15322c1f46dcSZachary Turner   // Create the function name & definition string.
15332c1f46dcSZachary Turner 
15342c1f46dcSZachary Turner   sstr.Printf("class %s:", auto_generated_class_name.c_str());
1535c156427dSZachary Turner   auto_generated_class.AppendString(sstr.GetString());
15362c1f46dcSZachary Turner 
153705097246SAdrian Prantl   // Wrap everything up inside the class, increasing the indentation. we don't
153805097246SAdrian Prantl   // need to play any fancy indentation tricks here because there is no
15392c1f46dcSZachary Turner   // surrounding code whose indentation we need to honor
1540b9c1b51eSKate Stone   for (int i = 0; i < num_lines; ++i) {
15412c1f46dcSZachary Turner     sstr.Clear();
15422c1f46dcSZachary Turner     sstr.Printf("     %s", user_input.GetStringAtIndex(i));
1543c156427dSZachary Turner     auto_generated_class.AppendString(sstr.GetString());
15442c1f46dcSZachary Turner   }
15452c1f46dcSZachary Turner 
154605097246SAdrian Prantl   // Verify that the results are valid Python. (even though the method is
154705097246SAdrian Prantl   // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
15482c1f46dcSZachary Turner   // (TODO: rename that method to ExportDefinitionToInterpreter)
15492c1f46dcSZachary Turner   if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
15502c1f46dcSZachary Turner     return false;
15512c1f46dcSZachary Turner 
15522c1f46dcSZachary Turner   // Store the name of the auto-generated class
15532c1f46dcSZachary Turner 
15542c1f46dcSZachary Turner   output.assign(auto_generated_class_name);
15552c1f46dcSZachary Turner   return true;
15562c1f46dcSZachary Turner }
15572c1f46dcSZachary Turner 
155863dd5d25SJonas Devlieghere StructuredData::GenericSP
155963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
156041ae8e74SKuba Mracek   if (class_name == nullptr || class_name[0] == '\0')
156141ae8e74SKuba Mracek     return StructuredData::GenericSP();
156241ae8e74SKuba Mracek 
156341ae8e74SKuba Mracek   void *ret_val;
156441ae8e74SKuba Mracek 
156541ae8e74SKuba Mracek   {
156641ae8e74SKuba Mracek     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
156741ae8e74SKuba Mracek                    Locker::FreeLock);
156805495c5dSJonas Devlieghere     ret_val = LLDBSWIGPython_CreateFrameRecognizer(class_name,
156905495c5dSJonas Devlieghere                                                    m_dictionary_name.c_str());
157041ae8e74SKuba Mracek   }
157141ae8e74SKuba Mracek 
157241ae8e74SKuba Mracek   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
157341ae8e74SKuba Mracek }
157441ae8e74SKuba Mracek 
157563dd5d25SJonas Devlieghere lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
157641ae8e74SKuba Mracek     const StructuredData::ObjectSP &os_plugin_object_sp,
157741ae8e74SKuba Mracek     lldb::StackFrameSP frame_sp) {
157841ae8e74SKuba Mracek   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
157941ae8e74SKuba Mracek 
158063dd5d25SJonas Devlieghere   if (!os_plugin_object_sp)
158163dd5d25SJonas Devlieghere     return ValueObjectListSP();
158241ae8e74SKuba Mracek 
158341ae8e74SKuba Mracek   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
158463dd5d25SJonas Devlieghere   if (!generic)
158563dd5d25SJonas Devlieghere     return nullptr;
158641ae8e74SKuba Mracek 
158741ae8e74SKuba Mracek   PythonObject implementor(PyRefType::Borrowed,
158841ae8e74SKuba Mracek                            (PyObject *)generic->GetValue());
158941ae8e74SKuba Mracek 
159063dd5d25SJonas Devlieghere   if (!implementor.IsAllocated())
159163dd5d25SJonas Devlieghere     return ValueObjectListSP();
159241ae8e74SKuba Mracek 
159305495c5dSJonas Devlieghere   PythonObject py_return(PyRefType::Owned,
159405495c5dSJonas Devlieghere                          (PyObject *)LLDBSwigPython_GetRecognizedArguments(
159505495c5dSJonas Devlieghere                              implementor.get(), frame_sp));
159641ae8e74SKuba Mracek 
159741ae8e74SKuba Mracek   // if it fails, print the error but otherwise go on
159841ae8e74SKuba Mracek   if (PyErr_Occurred()) {
159941ae8e74SKuba Mracek     PyErr_Print();
160041ae8e74SKuba Mracek     PyErr_Clear();
160141ae8e74SKuba Mracek   }
160241ae8e74SKuba Mracek   if (py_return.get()) {
160341ae8e74SKuba Mracek     PythonList result_list(PyRefType::Borrowed, py_return.get());
160441ae8e74SKuba Mracek     ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
16058f81aed1SDavid Bolvansky     for (size_t i = 0; i < result_list.GetSize(); i++) {
160641ae8e74SKuba Mracek       PyObject *item = result_list.GetItemAtIndex(i).get();
160741ae8e74SKuba Mracek       lldb::SBValue *sb_value_ptr =
160805495c5dSJonas Devlieghere           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
160905495c5dSJonas Devlieghere       auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
161063dd5d25SJonas Devlieghere       if (valobj_sp)
161163dd5d25SJonas Devlieghere         result->Append(valobj_sp);
161241ae8e74SKuba Mracek     }
161341ae8e74SKuba Mracek     return result;
161441ae8e74SKuba Mracek   }
161541ae8e74SKuba Mracek   return ValueObjectListSP();
161641ae8e74SKuba Mracek }
161741ae8e74SKuba Mracek 
161863dd5d25SJonas Devlieghere StructuredData::GenericSP
161963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject(
1620b9c1b51eSKate Stone     const char *class_name, lldb::ProcessSP process_sp) {
16212c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
16222c1f46dcSZachary Turner     return StructuredData::GenericSP();
16232c1f46dcSZachary Turner 
16242c1f46dcSZachary Turner   if (!process_sp)
16252c1f46dcSZachary Turner     return StructuredData::GenericSP();
16262c1f46dcSZachary Turner 
16272c1f46dcSZachary Turner   void *ret_val;
16282c1f46dcSZachary Turner 
16292c1f46dcSZachary Turner   {
1630b9c1b51eSKate Stone     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
16312c1f46dcSZachary Turner                    Locker::FreeLock);
163205495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonCreateOSPlugin(
163305495c5dSJonas Devlieghere         class_name, m_dictionary_name.c_str(), process_sp);
16342c1f46dcSZachary Turner   }
16352c1f46dcSZachary Turner 
16362c1f46dcSZachary Turner   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
16372c1f46dcSZachary Turner }
16382c1f46dcSZachary Turner 
163963dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo(
1640b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp) {
1641b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
16422c1f46dcSZachary Turner 
16432c1f46dcSZachary Turner   static char callee_name[] = "get_register_info";
16442c1f46dcSZachary Turner 
16452c1f46dcSZachary Turner   if (!os_plugin_object_sp)
16462c1f46dcSZachary Turner     return StructuredData::DictionarySP();
16472c1f46dcSZachary Turner 
16482c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
16492c1f46dcSZachary Turner   if (!generic)
16502c1f46dcSZachary Turner     return nullptr;
16512c1f46dcSZachary Turner 
1652b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1653b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
16542c1f46dcSZachary Turner 
1655f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
16562c1f46dcSZachary Turner     return StructuredData::DictionarySP();
16572c1f46dcSZachary Turner 
1658b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1659b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
16602c1f46dcSZachary Turner 
16612c1f46dcSZachary Turner   if (PyErr_Occurred())
16622c1f46dcSZachary Turner     PyErr_Clear();
16632c1f46dcSZachary Turner 
1664f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
16652c1f46dcSZachary Turner     return StructuredData::DictionarySP();
16662c1f46dcSZachary Turner 
1667b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
16682c1f46dcSZachary Turner     if (PyErr_Occurred())
16692c1f46dcSZachary Turner       PyErr_Clear();
16702c1f46dcSZachary Turner 
16712c1f46dcSZachary Turner     return StructuredData::DictionarySP();
16722c1f46dcSZachary Turner   }
16732c1f46dcSZachary Turner 
16742c1f46dcSZachary Turner   if (PyErr_Occurred())
16752c1f46dcSZachary Turner     PyErr_Clear();
16762c1f46dcSZachary Turner 
16772c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1678b9c1b51eSKate Stone   PythonObject py_return(
1679b9c1b51eSKate Stone       PyRefType::Owned,
1680b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
16812c1f46dcSZachary Turner 
16822c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1683b9c1b51eSKate Stone   if (PyErr_Occurred()) {
16842c1f46dcSZachary Turner     PyErr_Print();
16852c1f46dcSZachary Turner     PyErr_Clear();
16862c1f46dcSZachary Turner   }
1687b9c1b51eSKate Stone   if (py_return.get()) {
1688f8b22f8fSZachary Turner     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
16892c1f46dcSZachary Turner     return result_dict.CreateStructuredDictionary();
16902c1f46dcSZachary Turner   }
169158b794aeSGreg Clayton   return StructuredData::DictionarySP();
169258b794aeSGreg Clayton }
16932c1f46dcSZachary Turner 
169463dd5d25SJonas Devlieghere StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo(
1695b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp) {
1696b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
16972c1f46dcSZachary Turner 
16982c1f46dcSZachary Turner   static char callee_name[] = "get_thread_info";
16992c1f46dcSZachary Turner 
17002c1f46dcSZachary Turner   if (!os_plugin_object_sp)
17012c1f46dcSZachary Turner     return StructuredData::ArraySP();
17022c1f46dcSZachary Turner 
17032c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
17042c1f46dcSZachary Turner   if (!generic)
17052c1f46dcSZachary Turner     return nullptr;
17062c1f46dcSZachary Turner 
1707b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1708b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
1709f8b22f8fSZachary Turner 
1710f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
17112c1f46dcSZachary Turner     return StructuredData::ArraySP();
17122c1f46dcSZachary Turner 
1713b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1714b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
17152c1f46dcSZachary Turner 
17162c1f46dcSZachary Turner   if (PyErr_Occurred())
17172c1f46dcSZachary Turner     PyErr_Clear();
17182c1f46dcSZachary Turner 
1719f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
17202c1f46dcSZachary Turner     return StructuredData::ArraySP();
17212c1f46dcSZachary Turner 
1722b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
17232c1f46dcSZachary Turner     if (PyErr_Occurred())
17242c1f46dcSZachary Turner       PyErr_Clear();
17252c1f46dcSZachary Turner 
17262c1f46dcSZachary Turner     return StructuredData::ArraySP();
17272c1f46dcSZachary Turner   }
17282c1f46dcSZachary Turner 
17292c1f46dcSZachary Turner   if (PyErr_Occurred())
17302c1f46dcSZachary Turner     PyErr_Clear();
17312c1f46dcSZachary Turner 
17322c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1733b9c1b51eSKate Stone   PythonObject py_return(
1734b9c1b51eSKate Stone       PyRefType::Owned,
1735b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
17362c1f46dcSZachary Turner 
17372c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1738b9c1b51eSKate Stone   if (PyErr_Occurred()) {
17392c1f46dcSZachary Turner     PyErr_Print();
17402c1f46dcSZachary Turner     PyErr_Clear();
17412c1f46dcSZachary Turner   }
17422c1f46dcSZachary Turner 
1743b9c1b51eSKate Stone   if (py_return.get()) {
1744f8b22f8fSZachary Turner     PythonList result_list(PyRefType::Borrowed, py_return.get());
1745f8b22f8fSZachary Turner     return result_list.CreateStructuredArray();
17462c1f46dcSZachary Turner   }
174758b794aeSGreg Clayton   return StructuredData::ArraySP();
174858b794aeSGreg Clayton }
17492c1f46dcSZachary Turner 
175063dd5d25SJonas Devlieghere StructuredData::StringSP
175163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData(
1752b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
1753b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
17542c1f46dcSZachary Turner 
17552c1f46dcSZachary Turner   static char callee_name[] = "get_register_data";
1756b9c1b51eSKate Stone   static char *param_format =
1757b9c1b51eSKate Stone       const_cast<char *>(GetPythonValueFormatString(tid));
17582c1f46dcSZachary Turner 
17592c1f46dcSZachary Turner   if (!os_plugin_object_sp)
17602c1f46dcSZachary Turner     return StructuredData::StringSP();
17612c1f46dcSZachary Turner 
17622c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
17632c1f46dcSZachary Turner   if (!generic)
17642c1f46dcSZachary Turner     return nullptr;
1765b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1766b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
17672c1f46dcSZachary Turner 
1768f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
17692c1f46dcSZachary Turner     return StructuredData::StringSP();
17702c1f46dcSZachary Turner 
1771b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1772b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
17732c1f46dcSZachary Turner 
17742c1f46dcSZachary Turner   if (PyErr_Occurred())
17752c1f46dcSZachary Turner     PyErr_Clear();
17762c1f46dcSZachary Turner 
1777f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
17782c1f46dcSZachary Turner     return StructuredData::StringSP();
17792c1f46dcSZachary Turner 
1780b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
17812c1f46dcSZachary Turner     if (PyErr_Occurred())
17822c1f46dcSZachary Turner       PyErr_Clear();
17832c1f46dcSZachary Turner     return StructuredData::StringSP();
17842c1f46dcSZachary Turner   }
17852c1f46dcSZachary Turner 
17862c1f46dcSZachary Turner   if (PyErr_Occurred())
17872c1f46dcSZachary Turner     PyErr_Clear();
17882c1f46dcSZachary Turner 
17892c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1790b9c1b51eSKate Stone   PythonObject py_return(
1791b9c1b51eSKate Stone       PyRefType::Owned,
1792b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, param_format, tid));
17932c1f46dcSZachary Turner 
17942c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1795b9c1b51eSKate Stone   if (PyErr_Occurred()) {
17962c1f46dcSZachary Turner     PyErr_Print();
17972c1f46dcSZachary Turner     PyErr_Clear();
17982c1f46dcSZachary Turner   }
1799f8b22f8fSZachary Turner 
1800b9c1b51eSKate Stone   if (py_return.get()) {
18017a76845cSZachary Turner     PythonBytes result(PyRefType::Borrowed, py_return.get());
18027a76845cSZachary Turner     return result.CreateStructuredString();
18032c1f46dcSZachary Turner   }
180458b794aeSGreg Clayton   return StructuredData::StringSP();
180558b794aeSGreg Clayton }
18062c1f46dcSZachary Turner 
180763dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread(
1808b9c1b51eSKate Stone     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
1809b9c1b51eSKate Stone     lldb::addr_t context) {
1810b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
18112c1f46dcSZachary Turner 
18122c1f46dcSZachary Turner   static char callee_name[] = "create_thread";
18132c1f46dcSZachary Turner   std::string param_format;
18142c1f46dcSZachary Turner   param_format += GetPythonValueFormatString(tid);
18152c1f46dcSZachary Turner   param_format += GetPythonValueFormatString(context);
18162c1f46dcSZachary Turner 
18172c1f46dcSZachary Turner   if (!os_plugin_object_sp)
18182c1f46dcSZachary Turner     return StructuredData::DictionarySP();
18192c1f46dcSZachary Turner 
18202c1f46dcSZachary Turner   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
18212c1f46dcSZachary Turner   if (!generic)
18222c1f46dcSZachary Turner     return nullptr;
18232c1f46dcSZachary Turner 
1824b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
1825b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
1826f8b22f8fSZachary Turner 
1827f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
18282c1f46dcSZachary Turner     return StructuredData::DictionarySP();
18292c1f46dcSZachary Turner 
1830b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
1831b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
18322c1f46dcSZachary Turner 
18332c1f46dcSZachary Turner   if (PyErr_Occurred())
18342c1f46dcSZachary Turner     PyErr_Clear();
18352c1f46dcSZachary Turner 
1836f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
18372c1f46dcSZachary Turner     return StructuredData::DictionarySP();
18382c1f46dcSZachary Turner 
1839b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
18402c1f46dcSZachary Turner     if (PyErr_Occurred())
18412c1f46dcSZachary Turner       PyErr_Clear();
18422c1f46dcSZachary Turner     return StructuredData::DictionarySP();
18432c1f46dcSZachary Turner   }
18442c1f46dcSZachary Turner 
18452c1f46dcSZachary Turner   if (PyErr_Occurred())
18462c1f46dcSZachary Turner     PyErr_Clear();
18472c1f46dcSZachary Turner 
18482c1f46dcSZachary Turner   // right now we know this function exists and is callable..
1849b9c1b51eSKate Stone   PythonObject py_return(PyRefType::Owned,
1850b9c1b51eSKate Stone                          PyObject_CallMethod(implementor.get(), callee_name,
1851b9c1b51eSKate Stone                                              &param_format[0], tid, context));
18522c1f46dcSZachary Turner 
18532c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
1854b9c1b51eSKate Stone   if (PyErr_Occurred()) {
18552c1f46dcSZachary Turner     PyErr_Print();
18562c1f46dcSZachary Turner     PyErr_Clear();
18572c1f46dcSZachary Turner   }
18582c1f46dcSZachary Turner 
1859b9c1b51eSKate Stone   if (py_return.get()) {
1860f8b22f8fSZachary Turner     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
18612c1f46dcSZachary Turner     return result_dict.CreateStructuredDictionary();
18622c1f46dcSZachary Turner   }
186358b794aeSGreg Clayton   return StructuredData::DictionarySP();
186458b794aeSGreg Clayton }
18652c1f46dcSZachary Turner 
186663dd5d25SJonas Devlieghere StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan(
186727a14f19SJim Ingham     const char *class_name, StructuredDataImpl *args_data,
1868a69bbe02SLawrence D'Anna     std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) {
18692c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
18702c1f46dcSZachary Turner     return StructuredData::ObjectSP();
18712c1f46dcSZachary Turner 
18722c1f46dcSZachary Turner   if (!thread_plan_sp.get())
187393c98346SJim Ingham     return {};
18742c1f46dcSZachary Turner 
18752c1f46dcSZachary Turner   Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
187663dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
1877d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
18782c1f46dcSZachary Turner 
1879d055e3a0SPedro Tammela   if (!python_interpreter)
188093c98346SJim Ingham     return {};
18812c1f46dcSZachary Turner 
18822c1f46dcSZachary Turner   void *ret_val;
18832c1f46dcSZachary Turner 
18842c1f46dcSZachary Turner   {
1885b9c1b51eSKate Stone     Locker py_lock(this,
1886b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
188705495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateScriptedThreadPlan(
1888b9c1b51eSKate Stone         class_name, python_interpreter->m_dictionary_name.c_str(),
188927a14f19SJim Ingham         args_data, error_str, thread_plan_sp);
189093c98346SJim Ingham     if (!ret_val)
189193c98346SJim Ingham       return {};
18922c1f46dcSZachary Turner   }
18932c1f46dcSZachary Turner 
18942c1f46dcSZachary Turner   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
18952c1f46dcSZachary Turner }
18962c1f46dcSZachary Turner 
189763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop(
1898b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
18992c1f46dcSZachary Turner   bool explains_stop = true;
19002c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
19012c1f46dcSZachary Turner   if (implementor_sp)
19022c1f46dcSZachary Turner     generic = implementor_sp->GetAsGeneric();
1903b9c1b51eSKate Stone   if (generic) {
1904b9c1b51eSKate Stone     Locker py_lock(this,
1905b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
190605495c5dSJonas Devlieghere     explains_stop = LLDBSWIGPythonCallThreadPlan(
1907b9c1b51eSKate Stone         generic->GetValue(), "explains_stop", event, script_error);
19082c1f46dcSZachary Turner     if (script_error)
19092c1f46dcSZachary Turner       return true;
19102c1f46dcSZachary Turner   }
19112c1f46dcSZachary Turner   return explains_stop;
19122c1f46dcSZachary Turner }
19132c1f46dcSZachary Turner 
191463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop(
1915b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
19162c1f46dcSZachary Turner   bool should_stop = true;
19172c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
19182c1f46dcSZachary Turner   if (implementor_sp)
19192c1f46dcSZachary Turner     generic = implementor_sp->GetAsGeneric();
1920b9c1b51eSKate Stone   if (generic) {
1921b9c1b51eSKate Stone     Locker py_lock(this,
1922b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
192305495c5dSJonas Devlieghere     should_stop = LLDBSWIGPythonCallThreadPlan(
192405495c5dSJonas Devlieghere         generic->GetValue(), "should_stop", event, script_error);
19252c1f46dcSZachary Turner     if (script_error)
19262c1f46dcSZachary Turner       return true;
19272c1f46dcSZachary Turner   }
19282c1f46dcSZachary Turner   return should_stop;
19292c1f46dcSZachary Turner }
19302c1f46dcSZachary Turner 
193163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale(
1932b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1933c915a7d2SJim Ingham   bool is_stale = true;
1934c915a7d2SJim Ingham   StructuredData::Generic *generic = nullptr;
1935c915a7d2SJim Ingham   if (implementor_sp)
1936c915a7d2SJim Ingham     generic = implementor_sp->GetAsGeneric();
1937b9c1b51eSKate Stone   if (generic) {
1938b9c1b51eSKate Stone     Locker py_lock(this,
1939b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
194005495c5dSJonas Devlieghere     is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale",
194105495c5dSJonas Devlieghere                                             nullptr, script_error);
1942c915a7d2SJim Ingham     if (script_error)
1943c915a7d2SJim Ingham       return true;
1944c915a7d2SJim Ingham   }
1945c915a7d2SJim Ingham   return is_stale;
1946c915a7d2SJim Ingham }
1947c915a7d2SJim Ingham 
194863dd5d25SJonas Devlieghere lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState(
1949b9c1b51eSKate Stone     StructuredData::ObjectSP implementor_sp, bool &script_error) {
19502c1f46dcSZachary Turner   bool should_step = false;
19512c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
19522c1f46dcSZachary Turner   if (implementor_sp)
19532c1f46dcSZachary Turner     generic = implementor_sp->GetAsGeneric();
1954b9c1b51eSKate Stone   if (generic) {
1955b9c1b51eSKate Stone     Locker py_lock(this,
1956b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
195705495c5dSJonas Devlieghere     should_step = LLDBSWIGPythonCallThreadPlan(
1958248a1305SKonrad Kleine         generic->GetValue(), "should_step", nullptr, script_error);
19592c1f46dcSZachary Turner     if (script_error)
19602c1f46dcSZachary Turner       should_step = true;
19612c1f46dcSZachary Turner   }
19622c1f46dcSZachary Turner   if (should_step)
19632c1f46dcSZachary Turner     return lldb::eStateStepping;
19642c1f46dcSZachary Turner   return lldb::eStateRunning;
19652c1f46dcSZachary Turner }
19662c1f46dcSZachary Turner 
19673815e702SJim Ingham StructuredData::GenericSP
196863dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
196963dd5d25SJonas Devlieghere     const char *class_name, StructuredDataImpl *args_data,
19703815e702SJim Ingham     lldb::BreakpointSP &bkpt_sp) {
19713815e702SJim Ingham 
19723815e702SJim Ingham   if (class_name == nullptr || class_name[0] == '\0')
19733815e702SJim Ingham     return StructuredData::GenericSP();
19743815e702SJim Ingham 
19753815e702SJim Ingham   if (!bkpt_sp.get())
19763815e702SJim Ingham     return StructuredData::GenericSP();
19773815e702SJim Ingham 
19783815e702SJim Ingham   Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
197963dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
1980d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
19813815e702SJim Ingham 
1982d055e3a0SPedro Tammela   if (!python_interpreter)
19833815e702SJim Ingham     return StructuredData::GenericSP();
19843815e702SJim Ingham 
19853815e702SJim Ingham   void *ret_val;
19863815e702SJim Ingham 
19873815e702SJim Ingham   {
19883815e702SJim Ingham     Locker py_lock(this,
19893815e702SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19903815e702SJim Ingham 
199105495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver(
199205495c5dSJonas Devlieghere         class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
199305495c5dSJonas Devlieghere         bkpt_sp);
19943815e702SJim Ingham   }
19953815e702SJim Ingham 
19963815e702SJim Ingham   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
19973815e702SJim Ingham }
19983815e702SJim Ingham 
199963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
200063dd5d25SJonas Devlieghere     StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
20013815e702SJim Ingham   bool should_continue = false;
20023815e702SJim Ingham 
20033815e702SJim Ingham   if (implementor_sp) {
20043815e702SJim Ingham     Locker py_lock(this,
20053815e702SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
200605495c5dSJonas Devlieghere     should_continue = LLDBSwigPythonCallBreakpointResolver(
200705495c5dSJonas Devlieghere         implementor_sp->GetValue(), "__callback__", sym_ctx);
20083815e702SJim Ingham     if (PyErr_Occurred()) {
20093815e702SJim Ingham       PyErr_Print();
20103815e702SJim Ingham       PyErr_Clear();
20113815e702SJim Ingham     }
20123815e702SJim Ingham   }
20133815e702SJim Ingham   return should_continue;
20143815e702SJim Ingham }
20153815e702SJim Ingham 
20163815e702SJim Ingham lldb::SearchDepth
201763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
20183815e702SJim Ingham     StructuredData::GenericSP implementor_sp) {
20193815e702SJim Ingham   int depth_as_int = lldb::eSearchDepthModule;
20203815e702SJim Ingham   if (implementor_sp) {
20213815e702SJim Ingham     Locker py_lock(this,
20223815e702SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
202305495c5dSJonas Devlieghere     depth_as_int = LLDBSwigPythonCallBreakpointResolver(
202405495c5dSJonas Devlieghere         implementor_sp->GetValue(), "__get_depth__", nullptr);
20253815e702SJim Ingham     if (PyErr_Occurred()) {
20263815e702SJim Ingham       PyErr_Print();
20273815e702SJim Ingham       PyErr_Clear();
20283815e702SJim Ingham     }
20293815e702SJim Ingham   }
20303815e702SJim Ingham   if (depth_as_int == lldb::eSearchDepthInvalid)
20313815e702SJim Ingham     return lldb::eSearchDepthModule;
20323815e702SJim Ingham 
20333815e702SJim Ingham   if (depth_as_int <= lldb::kLastSearchDepthKind)
20343815e702SJim Ingham     return (lldb::SearchDepth)depth_as_int;
20353815e702SJim Ingham   return lldb::eSearchDepthModule;
20363815e702SJim Ingham }
20373815e702SJim Ingham 
20381b1d9815SJim Ingham StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
20391b1d9815SJim Ingham     TargetSP target_sp, const char *class_name, StructuredDataImpl *args_data,
20401b1d9815SJim Ingham     Status &error) {
20411b1d9815SJim Ingham 
20421b1d9815SJim Ingham   if (!target_sp) {
20431b1d9815SJim Ingham     error.SetErrorString("No target for scripted stop-hook.");
20441b1d9815SJim Ingham     return StructuredData::GenericSP();
20451b1d9815SJim Ingham   }
20461b1d9815SJim Ingham 
20471b1d9815SJim Ingham   if (class_name == nullptr || class_name[0] == '\0') {
20481b1d9815SJim Ingham     error.SetErrorString("No class name for scripted stop-hook.");
20491b1d9815SJim Ingham     return StructuredData::GenericSP();
20501b1d9815SJim Ingham   }
20511b1d9815SJim Ingham 
20521b1d9815SJim Ingham   ScriptInterpreterPythonImpl *python_interpreter =
2053d055e3a0SPedro Tammela       GetPythonInterpreter(m_debugger);
20541b1d9815SJim Ingham 
2055d055e3a0SPedro Tammela   if (!python_interpreter) {
20561b1d9815SJim Ingham     error.SetErrorString("No script interpreter for scripted stop-hook.");
20571b1d9815SJim Ingham     return StructuredData::GenericSP();
20581b1d9815SJim Ingham   }
20591b1d9815SJim Ingham 
20601b1d9815SJim Ingham   void *ret_val;
20611b1d9815SJim Ingham 
20621b1d9815SJim Ingham   {
20631b1d9815SJim Ingham     Locker py_lock(this,
20641b1d9815SJim Ingham                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
20651b1d9815SJim Ingham 
20661b1d9815SJim Ingham     ret_val = LLDBSwigPythonCreateScriptedStopHook(
20671b1d9815SJim Ingham         target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
20681b1d9815SJim Ingham         args_data, error);
20691b1d9815SJim Ingham   }
20701b1d9815SJim Ingham 
20711b1d9815SJim Ingham   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
20721b1d9815SJim Ingham }
20731b1d9815SJim Ingham 
20741b1d9815SJim Ingham bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
20751b1d9815SJim Ingham     StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
20761b1d9815SJim Ingham     lldb::StreamSP stream_sp) {
20771b1d9815SJim Ingham   assert(implementor_sp &&
20781b1d9815SJim Ingham          "can't call a stop hook with an invalid implementor");
20791b1d9815SJim Ingham   assert(stream_sp && "can't call a stop hook with an invalid stream");
20801b1d9815SJim Ingham 
20811b1d9815SJim Ingham   Locker py_lock(this,
20821b1d9815SJim Ingham                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
20831b1d9815SJim Ingham 
20841b1d9815SJim Ingham   lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
20851b1d9815SJim Ingham 
20861b1d9815SJim Ingham   bool ret_val = LLDBSwigPythonStopHookCallHandleStop(
20871b1d9815SJim Ingham       implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
20881b1d9815SJim Ingham   return ret_val;
20891b1d9815SJim Ingham }
20901b1d9815SJim Ingham 
20912c1f46dcSZachary Turner StructuredData::ObjectSP
209263dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
209397206d57SZachary Turner                                               lldb_private::Status &error) {
2094dbd7fabaSJonas Devlieghere   if (!FileSystem::Instance().Exists(file_spec)) {
20952c1f46dcSZachary Turner     error.SetErrorString("no such file");
20962c1f46dcSZachary Turner     return StructuredData::ObjectSP();
20972c1f46dcSZachary Turner   }
20982c1f46dcSZachary Turner 
20992c1f46dcSZachary Turner   StructuredData::ObjectSP module_sp;
21002c1f46dcSZachary Turner 
2101f9517353SJonas Devlieghere   LoadScriptOptions load_script_options =
2102f9517353SJonas Devlieghere       LoadScriptOptions().SetInitSession(true).SetSilent(false);
2103f9517353SJonas Devlieghere   if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
2104f9517353SJonas Devlieghere                           error, &module_sp))
21052c1f46dcSZachary Turner     return module_sp;
21062c1f46dcSZachary Turner 
21072c1f46dcSZachary Turner   return StructuredData::ObjectSP();
21082c1f46dcSZachary Turner }
21092c1f46dcSZachary Turner 
211063dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
2111b9c1b51eSKate Stone     StructuredData::ObjectSP plugin_module_sp, Target *target,
211297206d57SZachary Turner     const char *setting_name, lldb_private::Status &error) {
211305495c5dSJonas Devlieghere   if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
21142c1f46dcSZachary Turner     return StructuredData::DictionarySP();
21152c1f46dcSZachary Turner   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
21162c1f46dcSZachary Turner   if (!generic)
21172c1f46dcSZachary Turner     return StructuredData::DictionarySP();
21182c1f46dcSZachary Turner 
2119b9c1b51eSKate Stone   Locker py_lock(this,
2120b9c1b51eSKate Stone                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
21212c1f46dcSZachary Turner   TargetSP target_sp(target->shared_from_this());
21222c1f46dcSZachary Turner 
212304edd189SLawrence D'Anna   auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting(
212404edd189SLawrence D'Anna       generic->GetValue(), setting_name, target_sp);
212504edd189SLawrence D'Anna 
212604edd189SLawrence D'Anna   if (!setting)
212704edd189SLawrence D'Anna     return StructuredData::DictionarySP();
212804edd189SLawrence D'Anna 
212904edd189SLawrence D'Anna   PythonDictionary py_dict =
213004edd189SLawrence D'Anna       unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
213104edd189SLawrence D'Anna 
213204edd189SLawrence D'Anna   if (!py_dict)
213304edd189SLawrence D'Anna     return StructuredData::DictionarySP();
213404edd189SLawrence D'Anna 
21352c1f46dcSZachary Turner   return py_dict.CreateStructuredDictionary();
21362c1f46dcSZachary Turner }
21372c1f46dcSZachary Turner 
21382c1f46dcSZachary Turner StructuredData::ObjectSP
213963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
2140b9c1b51eSKate Stone     const char *class_name, lldb::ValueObjectSP valobj) {
21412c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
21422c1f46dcSZachary Turner     return StructuredData::ObjectSP();
21432c1f46dcSZachary Turner 
21442c1f46dcSZachary Turner   if (!valobj.get())
21452c1f46dcSZachary Turner     return StructuredData::ObjectSP();
21462c1f46dcSZachary Turner 
21472c1f46dcSZachary Turner   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
21482c1f46dcSZachary Turner   Target *target = exe_ctx.GetTargetPtr();
21492c1f46dcSZachary Turner 
21502c1f46dcSZachary Turner   if (!target)
21512c1f46dcSZachary Turner     return StructuredData::ObjectSP();
21522c1f46dcSZachary Turner 
21532c1f46dcSZachary Turner   Debugger &debugger = target->GetDebugger();
215463dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
2155d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
21562c1f46dcSZachary Turner 
2157d055e3a0SPedro Tammela   if (!python_interpreter)
21582c1f46dcSZachary Turner     return StructuredData::ObjectSP();
21592c1f46dcSZachary Turner 
21602c1f46dcSZachary Turner   void *ret_val = nullptr;
21612c1f46dcSZachary Turner 
21622c1f46dcSZachary Turner   {
2163b9c1b51eSKate Stone     Locker py_lock(this,
2164b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
216505495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateSyntheticProvider(
2166b9c1b51eSKate Stone         class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
21672c1f46dcSZachary Turner   }
21682c1f46dcSZachary Turner 
21692c1f46dcSZachary Turner   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
21702c1f46dcSZachary Turner }
21712c1f46dcSZachary Turner 
21722c1f46dcSZachary Turner StructuredData::GenericSP
217363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
21748d1fb843SJonas Devlieghere   DebuggerSP debugger_sp(m_debugger.shared_from_this());
21752c1f46dcSZachary Turner 
21762c1f46dcSZachary Turner   if (class_name == nullptr || class_name[0] == '\0')
21772c1f46dcSZachary Turner     return StructuredData::GenericSP();
21782c1f46dcSZachary Turner 
21792c1f46dcSZachary Turner   if (!debugger_sp.get())
21802c1f46dcSZachary Turner     return StructuredData::GenericSP();
21812c1f46dcSZachary Turner 
21822c1f46dcSZachary Turner   void *ret_val;
21832c1f46dcSZachary Turner 
21842c1f46dcSZachary Turner   {
2185b9c1b51eSKate Stone     Locker py_lock(this,
2186b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
218705495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCreateCommandObject(
218805495c5dSJonas Devlieghere         class_name, m_dictionary_name.c_str(), debugger_sp);
21892c1f46dcSZachary Turner   }
21902c1f46dcSZachary Turner 
21912c1f46dcSZachary Turner   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
21922c1f46dcSZachary Turner }
21932c1f46dcSZachary Turner 
219463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
2195b9c1b51eSKate Stone     const char *oneliner, std::string &output, const void *name_token) {
21962c1f46dcSZachary Turner   StringList input;
21972c1f46dcSZachary Turner   input.SplitIntoLines(oneliner, strlen(oneliner));
21982c1f46dcSZachary Turner   return GenerateTypeScriptFunction(input, output, name_token);
21992c1f46dcSZachary Turner }
22002c1f46dcSZachary Turner 
220163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
220263dd5d25SJonas Devlieghere     const char *oneliner, std::string &output, const void *name_token) {
22032c1f46dcSZachary Turner   StringList input;
22042c1f46dcSZachary Turner   input.SplitIntoLines(oneliner, strlen(oneliner));
22052c1f46dcSZachary Turner   return GenerateTypeSynthClass(input, output, name_token);
22062c1f46dcSZachary Turner }
22072c1f46dcSZachary Turner 
220863dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
2209738af7a6SJim Ingham     StringList &user_input, std::string &output,
2210738af7a6SJim Ingham     bool has_extra_args) {
22112c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
22122c1f46dcSZachary Turner   user_input.RemoveBlankLines();
22132c1f46dcSZachary Turner   StreamString sstr;
221497206d57SZachary Turner   Status error;
2215b9c1b51eSKate Stone   if (user_input.GetSize() == 0) {
22162c1f46dcSZachary Turner     error.SetErrorString("No input data.");
22172c1f46dcSZachary Turner     return error;
22182c1f46dcSZachary Turner   }
22192c1f46dcSZachary Turner 
2220b9c1b51eSKate Stone   std::string auto_generated_function_name(GenerateUniqueName(
2221b9c1b51eSKate Stone       "lldb_autogen_python_bp_callback_func_", num_created_functions));
2222738af7a6SJim Ingham   if (has_extra_args)
2223738af7a6SJim Ingham     sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
2224738af7a6SJim Ingham                 auto_generated_function_name.c_str());
2225738af7a6SJim Ingham   else
2226b9c1b51eSKate Stone     sstr.Printf("def %s (frame, bp_loc, internal_dict):",
2227b9c1b51eSKate Stone                 auto_generated_function_name.c_str());
22282c1f46dcSZachary Turner 
22292c1f46dcSZachary Turner   error = GenerateFunction(sstr.GetData(), user_input);
22302c1f46dcSZachary Turner   if (!error.Success())
22312c1f46dcSZachary Turner     return error;
22322c1f46dcSZachary Turner 
22332c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
22342c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
22352c1f46dcSZachary Turner   return error;
22362c1f46dcSZachary Turner }
22372c1f46dcSZachary Turner 
223863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
2239b9c1b51eSKate Stone     StringList &user_input, std::string &output) {
22402c1f46dcSZachary Turner   static uint32_t num_created_functions = 0;
22412c1f46dcSZachary Turner   user_input.RemoveBlankLines();
22422c1f46dcSZachary Turner   StreamString sstr;
22432c1f46dcSZachary Turner 
22442c1f46dcSZachary Turner   if (user_input.GetSize() == 0)
22452c1f46dcSZachary Turner     return false;
22462c1f46dcSZachary Turner 
2247b9c1b51eSKate Stone   std::string auto_generated_function_name(GenerateUniqueName(
2248b9c1b51eSKate Stone       "lldb_autogen_python_wp_callback_func_", num_created_functions));
2249b9c1b51eSKate Stone   sstr.Printf("def %s (frame, wp, internal_dict):",
2250b9c1b51eSKate Stone               auto_generated_function_name.c_str());
22512c1f46dcSZachary Turner 
22522c1f46dcSZachary Turner   if (!GenerateFunction(sstr.GetData(), user_input).Success())
22532c1f46dcSZachary Turner     return false;
22542c1f46dcSZachary Turner 
22552c1f46dcSZachary Turner   // Store the name of the auto-generated function to be called.
22562c1f46dcSZachary Turner   output.assign(auto_generated_function_name);
22572c1f46dcSZachary Turner   return true;
22582c1f46dcSZachary Turner }
22592c1f46dcSZachary Turner 
226063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetScriptedSummary(
2261b9c1b51eSKate Stone     const char *python_function_name, lldb::ValueObjectSP valobj,
2262b9c1b51eSKate Stone     StructuredData::ObjectSP &callee_wrapper_sp,
2263b9c1b51eSKate Stone     const TypeSummaryOptions &options, std::string &retval) {
22642c1f46dcSZachary Turner 
22655c1c8443SJonas Devlieghere   LLDB_SCOPED_TIMER();
22662c1f46dcSZachary Turner 
2267b9c1b51eSKate Stone   if (!valobj.get()) {
22682c1f46dcSZachary Turner     retval.assign("<no object>");
22692c1f46dcSZachary Turner     return false;
22702c1f46dcSZachary Turner   }
22712c1f46dcSZachary Turner 
22722c1f46dcSZachary Turner   void *old_callee = nullptr;
22732c1f46dcSZachary Turner   StructuredData::Generic *generic = nullptr;
2274b9c1b51eSKate Stone   if (callee_wrapper_sp) {
22752c1f46dcSZachary Turner     generic = callee_wrapper_sp->GetAsGeneric();
22762c1f46dcSZachary Turner     if (generic)
22772c1f46dcSZachary Turner       old_callee = generic->GetValue();
22782c1f46dcSZachary Turner   }
22792c1f46dcSZachary Turner   void *new_callee = old_callee;
22802c1f46dcSZachary Turner 
22812c1f46dcSZachary Turner   bool ret_val;
2282b9c1b51eSKate Stone   if (python_function_name && *python_function_name) {
22832c1f46dcSZachary Turner     {
2284b9c1b51eSKate Stone       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
2285b9c1b51eSKate Stone                                Locker::NoSTDIN);
22862c1f46dcSZachary Turner       {
22872c1f46dcSZachary Turner         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
22882c1f46dcSZachary Turner 
228905495c5dSJonas Devlieghere         static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
229005495c5dSJonas Devlieghere         Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
229105495c5dSJonas Devlieghere         ret_val = LLDBSwigPythonCallTypeScript(
2292b9c1b51eSKate Stone             python_function_name, GetSessionDictionary().get(), valobj,
2293b9c1b51eSKate Stone             &new_callee, options_sp, retval);
22942c1f46dcSZachary Turner       }
22952c1f46dcSZachary Turner     }
2296b9c1b51eSKate Stone   } else {
22972c1f46dcSZachary Turner     retval.assign("<no function name>");
22982c1f46dcSZachary Turner     return false;
22992c1f46dcSZachary Turner   }
23002c1f46dcSZachary Turner 
23012c1f46dcSZachary Turner   if (new_callee && old_callee != new_callee)
2302796ac80bSJonas Devlieghere     callee_wrapper_sp = std::make_shared<StructuredPythonObject>(new_callee);
23032c1f46dcSZachary Turner 
23042c1f46dcSZachary Turner   return ret_val;
23052c1f46dcSZachary Turner }
23062c1f46dcSZachary Turner 
230763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
2308b9c1b51eSKate Stone     void *baton, StoppointCallbackContext *context, user_id_t break_id,
2309b9c1b51eSKate Stone     user_id_t break_loc_id) {
2310f7e07256SJim Ingham   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
23112c1f46dcSZachary Turner   const char *python_function_name = bp_option_data->script_source.c_str();
23122c1f46dcSZachary Turner 
23132c1f46dcSZachary Turner   if (!context)
23142c1f46dcSZachary Turner     return true;
23152c1f46dcSZachary Turner 
23162c1f46dcSZachary Turner   ExecutionContext exe_ctx(context->exe_ctx_ref);
23172c1f46dcSZachary Turner   Target *target = exe_ctx.GetTargetPtr();
23182c1f46dcSZachary Turner 
23192c1f46dcSZachary Turner   if (!target)
23202c1f46dcSZachary Turner     return true;
23212c1f46dcSZachary Turner 
23222c1f46dcSZachary Turner   Debugger &debugger = target->GetDebugger();
232363dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
2324d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
23252c1f46dcSZachary Turner 
2326d055e3a0SPedro Tammela   if (!python_interpreter)
23272c1f46dcSZachary Turner     return true;
23282c1f46dcSZachary Turner 
2329b9c1b51eSKate Stone   if (python_function_name && python_function_name[0]) {
23302c1f46dcSZachary Turner     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
23312c1f46dcSZachary Turner     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2332b9c1b51eSKate Stone     if (breakpoint_sp) {
2333b9c1b51eSKate Stone       const BreakpointLocationSP bp_loc_sp(
2334b9c1b51eSKate Stone           breakpoint_sp->FindLocationByID(break_loc_id));
23352c1f46dcSZachary Turner 
2336b9c1b51eSKate Stone       if (stop_frame_sp && bp_loc_sp) {
23372c1f46dcSZachary Turner         bool ret_val = true;
23382c1f46dcSZachary Turner         {
2339b9c1b51eSKate Stone           Locker py_lock(python_interpreter, Locker::AcquireLock |
2340b9c1b51eSKate Stone                                                  Locker::InitSession |
2341b9c1b51eSKate Stone                                                  Locker::NoSTDIN);
2342a69bbe02SLawrence D'Anna           Expected<bool> maybe_ret_val =
2343a69bbe02SLawrence D'Anna               LLDBSwigPythonBreakpointCallbackFunction(
2344b9c1b51eSKate Stone                   python_function_name,
2345b9c1b51eSKate Stone                   python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2346a69bbe02SLawrence D'Anna                   bp_loc_sp, bp_option_data->m_extra_args_up.get());
2347a69bbe02SLawrence D'Anna 
2348a69bbe02SLawrence D'Anna           if (!maybe_ret_val) {
2349a69bbe02SLawrence D'Anna 
2350a69bbe02SLawrence D'Anna             llvm::handleAllErrors(
2351a69bbe02SLawrence D'Anna                 maybe_ret_val.takeError(),
2352a69bbe02SLawrence D'Anna                 [&](PythonException &E) {
2353a69bbe02SLawrence D'Anna                   debugger.GetErrorStream() << E.ReadBacktrace();
2354a69bbe02SLawrence D'Anna                 },
2355a69bbe02SLawrence D'Anna                 [&](const llvm::ErrorInfoBase &E) {
2356a69bbe02SLawrence D'Anna                   debugger.GetErrorStream() << E.message();
2357a69bbe02SLawrence D'Anna                 });
2358a69bbe02SLawrence D'Anna 
2359a69bbe02SLawrence D'Anna           } else {
2360a69bbe02SLawrence D'Anna             ret_val = maybe_ret_val.get();
2361a69bbe02SLawrence D'Anna           }
23622c1f46dcSZachary Turner         }
23632c1f46dcSZachary Turner         return ret_val;
23642c1f46dcSZachary Turner       }
23652c1f46dcSZachary Turner     }
23662c1f46dcSZachary Turner   }
23672c1f46dcSZachary Turner   // We currently always true so we stop in case anything goes wrong when
23682c1f46dcSZachary Turner   // trying to call the script function
23692c1f46dcSZachary Turner   return true;
23702c1f46dcSZachary Turner }
23712c1f46dcSZachary Turner 
237263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
2373b9c1b51eSKate Stone     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2374b9c1b51eSKate Stone   WatchpointOptions::CommandData *wp_option_data =
2375b9c1b51eSKate Stone       (WatchpointOptions::CommandData *)baton;
23762c1f46dcSZachary Turner   const char *python_function_name = wp_option_data->script_source.c_str();
23772c1f46dcSZachary Turner 
23782c1f46dcSZachary Turner   if (!context)
23792c1f46dcSZachary Turner     return true;
23802c1f46dcSZachary Turner 
23812c1f46dcSZachary Turner   ExecutionContext exe_ctx(context->exe_ctx_ref);
23822c1f46dcSZachary Turner   Target *target = exe_ctx.GetTargetPtr();
23832c1f46dcSZachary Turner 
23842c1f46dcSZachary Turner   if (!target)
23852c1f46dcSZachary Turner     return true;
23862c1f46dcSZachary Turner 
23872c1f46dcSZachary Turner   Debugger &debugger = target->GetDebugger();
238863dd5d25SJonas Devlieghere   ScriptInterpreterPythonImpl *python_interpreter =
2389d055e3a0SPedro Tammela       GetPythonInterpreter(debugger);
23902c1f46dcSZachary Turner 
2391d055e3a0SPedro Tammela   if (!python_interpreter)
23922c1f46dcSZachary Turner     return true;
23932c1f46dcSZachary Turner 
2394b9c1b51eSKate Stone   if (python_function_name && python_function_name[0]) {
23952c1f46dcSZachary Turner     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
23962c1f46dcSZachary Turner     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2397b9c1b51eSKate Stone     if (wp_sp) {
2398b9c1b51eSKate Stone       if (stop_frame_sp && wp_sp) {
23992c1f46dcSZachary Turner         bool ret_val = true;
24002c1f46dcSZachary Turner         {
2401b9c1b51eSKate Stone           Locker py_lock(python_interpreter, Locker::AcquireLock |
2402b9c1b51eSKate Stone                                                  Locker::InitSession |
2403b9c1b51eSKate Stone                                                  Locker::NoSTDIN);
240405495c5dSJonas Devlieghere           ret_val = LLDBSwigPythonWatchpointCallbackFunction(
2405b9c1b51eSKate Stone               python_function_name,
2406b9c1b51eSKate Stone               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
24072c1f46dcSZachary Turner               wp_sp);
24082c1f46dcSZachary Turner         }
24092c1f46dcSZachary Turner         return ret_val;
24102c1f46dcSZachary Turner       }
24112c1f46dcSZachary Turner     }
24122c1f46dcSZachary Turner   }
24132c1f46dcSZachary Turner   // We currently always true so we stop in case anything goes wrong when
24142c1f46dcSZachary Turner   // trying to call the script function
24152c1f46dcSZachary Turner   return true;
24162c1f46dcSZachary Turner }
24172c1f46dcSZachary Turner 
241863dd5d25SJonas Devlieghere size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2419b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
24202c1f46dcSZachary Turner   if (!implementor_sp)
24212c1f46dcSZachary Turner     return 0;
24222c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24232c1f46dcSZachary Turner   if (!generic)
24242c1f46dcSZachary Turner     return 0;
24252c1f46dcSZachary Turner   void *implementor = generic->GetValue();
24262c1f46dcSZachary Turner   if (!implementor)
24272c1f46dcSZachary Turner     return 0;
24282c1f46dcSZachary Turner 
24292c1f46dcSZachary Turner   size_t ret_val = 0;
24302c1f46dcSZachary Turner 
24312c1f46dcSZachary Turner   {
2432b9c1b51eSKate Stone     Locker py_lock(this,
2433b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
243405495c5dSJonas Devlieghere     ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max);
24352c1f46dcSZachary Turner   }
24362c1f46dcSZachary Turner 
24372c1f46dcSZachary Turner   return ret_val;
24382c1f46dcSZachary Turner }
24392c1f46dcSZachary Turner 
244063dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
2441b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
24422c1f46dcSZachary Turner   if (!implementor_sp)
24432c1f46dcSZachary Turner     return lldb::ValueObjectSP();
24442c1f46dcSZachary Turner 
24452c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24462c1f46dcSZachary Turner   if (!generic)
24472c1f46dcSZachary Turner     return lldb::ValueObjectSP();
24482c1f46dcSZachary Turner   void *implementor = generic->GetValue();
24492c1f46dcSZachary Turner   if (!implementor)
24502c1f46dcSZachary Turner     return lldb::ValueObjectSP();
24512c1f46dcSZachary Turner 
24522c1f46dcSZachary Turner   lldb::ValueObjectSP ret_val;
24532c1f46dcSZachary Turner   {
2454b9c1b51eSKate Stone     Locker py_lock(this,
2455b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
245605495c5dSJonas Devlieghere     void *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx);
2457b9c1b51eSKate Stone     if (child_ptr != nullptr && child_ptr != Py_None) {
2458b9c1b51eSKate Stone       lldb::SBValue *sb_value_ptr =
245905495c5dSJonas Devlieghere           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
24602c1f46dcSZachary Turner       if (sb_value_ptr == nullptr)
24612c1f46dcSZachary Turner         Py_XDECREF(child_ptr);
24622c1f46dcSZachary Turner       else
246305495c5dSJonas Devlieghere         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2464b9c1b51eSKate Stone     } else {
24652c1f46dcSZachary Turner       Py_XDECREF(child_ptr);
24662c1f46dcSZachary Turner     }
24672c1f46dcSZachary Turner   }
24682c1f46dcSZachary Turner 
24692c1f46dcSZachary Turner   return ret_val;
24702c1f46dcSZachary Turner }
24712c1f46dcSZachary Turner 
247263dd5d25SJonas Devlieghere int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2473b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
24742c1f46dcSZachary Turner   if (!implementor_sp)
24752c1f46dcSZachary Turner     return UINT32_MAX;
24762c1f46dcSZachary Turner 
24772c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24782c1f46dcSZachary Turner   if (!generic)
24792c1f46dcSZachary Turner     return UINT32_MAX;
24802c1f46dcSZachary Turner   void *implementor = generic->GetValue();
24812c1f46dcSZachary Turner   if (!implementor)
24822c1f46dcSZachary Turner     return UINT32_MAX;
24832c1f46dcSZachary Turner 
24842c1f46dcSZachary Turner   int ret_val = UINT32_MAX;
24852c1f46dcSZachary Turner 
24862c1f46dcSZachary Turner   {
2487b9c1b51eSKate Stone     Locker py_lock(this,
2488b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
248905495c5dSJonas Devlieghere     ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
24902c1f46dcSZachary Turner   }
24912c1f46dcSZachary Turner 
24922c1f46dcSZachary Turner   return ret_val;
24932c1f46dcSZachary Turner }
24942c1f46dcSZachary Turner 
249563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2496b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
24972c1f46dcSZachary Turner   bool ret_val = false;
24982c1f46dcSZachary Turner 
24992c1f46dcSZachary Turner   if (!implementor_sp)
25002c1f46dcSZachary Turner     return ret_val;
25012c1f46dcSZachary Turner 
25022c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
25032c1f46dcSZachary Turner   if (!generic)
25042c1f46dcSZachary Turner     return ret_val;
25052c1f46dcSZachary Turner   void *implementor = generic->GetValue();
25062c1f46dcSZachary Turner   if (!implementor)
25072c1f46dcSZachary Turner     return ret_val;
25082c1f46dcSZachary Turner 
25092c1f46dcSZachary Turner   {
2510b9c1b51eSKate Stone     Locker py_lock(this,
2511b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
251205495c5dSJonas Devlieghere     ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor);
25132c1f46dcSZachary Turner   }
25142c1f46dcSZachary Turner 
25152c1f46dcSZachary Turner   return ret_val;
25162c1f46dcSZachary Turner }
25172c1f46dcSZachary Turner 
251863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2519b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
25202c1f46dcSZachary Turner   bool ret_val = false;
25212c1f46dcSZachary Turner 
25222c1f46dcSZachary Turner   if (!implementor_sp)
25232c1f46dcSZachary Turner     return ret_val;
25242c1f46dcSZachary Turner 
25252c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
25262c1f46dcSZachary Turner   if (!generic)
25272c1f46dcSZachary Turner     return ret_val;
25282c1f46dcSZachary Turner   void *implementor = generic->GetValue();
25292c1f46dcSZachary Turner   if (!implementor)
25302c1f46dcSZachary Turner     return ret_val;
25312c1f46dcSZachary Turner 
25322c1f46dcSZachary Turner   {
2533b9c1b51eSKate Stone     Locker py_lock(this,
2534b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
253505495c5dSJonas Devlieghere     ret_val =
253605495c5dSJonas Devlieghere         LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor);
25372c1f46dcSZachary Turner   }
25382c1f46dcSZachary Turner 
25392c1f46dcSZachary Turner   return ret_val;
25402c1f46dcSZachary Turner }
25412c1f46dcSZachary Turner 
254263dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
2543b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
25442c1f46dcSZachary Turner   lldb::ValueObjectSP ret_val(nullptr);
25452c1f46dcSZachary Turner 
25462c1f46dcSZachary Turner   if (!implementor_sp)
25472c1f46dcSZachary Turner     return ret_val;
25482c1f46dcSZachary Turner 
25492c1f46dcSZachary Turner   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
25502c1f46dcSZachary Turner   if (!generic)
25512c1f46dcSZachary Turner     return ret_val;
25522c1f46dcSZachary Turner   void *implementor = generic->GetValue();
25532c1f46dcSZachary Turner   if (!implementor)
25542c1f46dcSZachary Turner     return ret_val;
25552c1f46dcSZachary Turner 
25562c1f46dcSZachary Turner   {
2557b9c1b51eSKate Stone     Locker py_lock(this,
2558b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
255905495c5dSJonas Devlieghere     void *child_ptr = LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2560b9c1b51eSKate Stone     if (child_ptr != nullptr && child_ptr != Py_None) {
2561b9c1b51eSKate Stone       lldb::SBValue *sb_value_ptr =
256205495c5dSJonas Devlieghere           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
25632c1f46dcSZachary Turner       if (sb_value_ptr == nullptr)
25642c1f46dcSZachary Turner         Py_XDECREF(child_ptr);
25652c1f46dcSZachary Turner       else
256605495c5dSJonas Devlieghere         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2567b9c1b51eSKate Stone     } else {
25682c1f46dcSZachary Turner       Py_XDECREF(child_ptr);
25692c1f46dcSZachary Turner     }
25702c1f46dcSZachary Turner   }
25712c1f46dcSZachary Turner 
25722c1f46dcSZachary Turner   return ret_val;
25732c1f46dcSZachary Turner }
25742c1f46dcSZachary Turner 
257563dd5d25SJonas Devlieghere ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2576b9c1b51eSKate Stone     const StructuredData::ObjectSP &implementor_sp) {
2577b9c1b51eSKate Stone   Locker py_lock(this,
2578b9c1b51eSKate Stone                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
25796eec8d6cSEnrico Granata 
25806eec8d6cSEnrico Granata   static char callee_name[] = "get_type_name";
25816eec8d6cSEnrico Granata 
25826eec8d6cSEnrico Granata   ConstString ret_val;
25836eec8d6cSEnrico Granata   bool got_string = false;
25846eec8d6cSEnrico Granata   std::string buffer;
25856eec8d6cSEnrico Granata 
25866eec8d6cSEnrico Granata   if (!implementor_sp)
25876eec8d6cSEnrico Granata     return ret_val;
25886eec8d6cSEnrico Granata 
25896eec8d6cSEnrico Granata   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
25906eec8d6cSEnrico Granata   if (!generic)
25916eec8d6cSEnrico Granata     return ret_val;
2592b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
2593b9c1b51eSKate Stone                            (PyObject *)generic->GetValue());
25946eec8d6cSEnrico Granata   if (!implementor.IsAllocated())
25956eec8d6cSEnrico Granata     return ret_val;
25966eec8d6cSEnrico Granata 
2597b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
2598b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
25996eec8d6cSEnrico Granata 
26006eec8d6cSEnrico Granata   if (PyErr_Occurred())
26016eec8d6cSEnrico Granata     PyErr_Clear();
26026eec8d6cSEnrico Granata 
26036eec8d6cSEnrico Granata   if (!pmeth.IsAllocated())
26046eec8d6cSEnrico Granata     return ret_val;
26056eec8d6cSEnrico Granata 
2606b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
26076eec8d6cSEnrico Granata     if (PyErr_Occurred())
26086eec8d6cSEnrico Granata       PyErr_Clear();
26096eec8d6cSEnrico Granata     return ret_val;
26106eec8d6cSEnrico Granata   }
26116eec8d6cSEnrico Granata 
26126eec8d6cSEnrico Granata   if (PyErr_Occurred())
26136eec8d6cSEnrico Granata     PyErr_Clear();
26146eec8d6cSEnrico Granata 
26156eec8d6cSEnrico Granata   // right now we know this function exists and is callable..
2616b9c1b51eSKate Stone   PythonObject py_return(
2617b9c1b51eSKate Stone       PyRefType::Owned,
2618b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
26196eec8d6cSEnrico Granata 
26206eec8d6cSEnrico Granata   // if it fails, print the error but otherwise go on
2621b9c1b51eSKate Stone   if (PyErr_Occurred()) {
26226eec8d6cSEnrico Granata     PyErr_Print();
26236eec8d6cSEnrico Granata     PyErr_Clear();
26246eec8d6cSEnrico Granata   }
26256eec8d6cSEnrico Granata 
2626b9c1b51eSKate Stone   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
26276eec8d6cSEnrico Granata     PythonString py_string(PyRefType::Borrowed, py_return.get());
26286eec8d6cSEnrico Granata     llvm::StringRef return_data(py_string.GetString());
2629b9c1b51eSKate Stone     if (!return_data.empty()) {
26306eec8d6cSEnrico Granata       buffer.assign(return_data.data(), return_data.size());
26316eec8d6cSEnrico Granata       got_string = true;
26326eec8d6cSEnrico Granata     }
26336eec8d6cSEnrico Granata   }
26346eec8d6cSEnrico Granata 
26356eec8d6cSEnrico Granata   if (got_string)
26366eec8d6cSEnrico Granata     ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
26376eec8d6cSEnrico Granata 
26386eec8d6cSEnrico Granata   return ret_val;
26396eec8d6cSEnrico Granata }
26406eec8d6cSEnrico Granata 
264163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
264263dd5d25SJonas Devlieghere     const char *impl_function, Process *process, std::string &output,
264397206d57SZachary Turner     Status &error) {
26442c1f46dcSZachary Turner   bool ret_val;
2645b9c1b51eSKate Stone   if (!process) {
26462c1f46dcSZachary Turner     error.SetErrorString("no process");
26472c1f46dcSZachary Turner     return false;
26482c1f46dcSZachary Turner   }
2649b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
26502c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
26512c1f46dcSZachary Turner     return false;
26522c1f46dcSZachary Turner   }
265305495c5dSJonas Devlieghere 
26542c1f46dcSZachary Turner   {
26552c1f46dcSZachary Turner     ProcessSP process_sp(process->shared_from_this());
2656b9c1b51eSKate Stone     Locker py_lock(this,
2657b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
265805495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordProcess(
2659b9c1b51eSKate Stone         impl_function, m_dictionary_name.c_str(), process_sp, output);
26602c1f46dcSZachary Turner     if (!ret_val)
26612c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
26622c1f46dcSZachary Turner   }
26632c1f46dcSZachary Turner   return ret_val;
26642c1f46dcSZachary Turner }
26652c1f46dcSZachary Turner 
266663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
266763dd5d25SJonas Devlieghere     const char *impl_function, Thread *thread, std::string &output,
266897206d57SZachary Turner     Status &error) {
26692c1f46dcSZachary Turner   bool ret_val;
2670b9c1b51eSKate Stone   if (!thread) {
26712c1f46dcSZachary Turner     error.SetErrorString("no thread");
26722c1f46dcSZachary Turner     return false;
26732c1f46dcSZachary Turner   }
2674b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
26752c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
26762c1f46dcSZachary Turner     return false;
26772c1f46dcSZachary Turner   }
267805495c5dSJonas Devlieghere 
26792c1f46dcSZachary Turner   {
26802c1f46dcSZachary Turner     ThreadSP thread_sp(thread->shared_from_this());
2681b9c1b51eSKate Stone     Locker py_lock(this,
2682b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
268305495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordThread(
2684b9c1b51eSKate Stone         impl_function, m_dictionary_name.c_str(), thread_sp, output);
26852c1f46dcSZachary Turner     if (!ret_val)
26862c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
26872c1f46dcSZachary Turner   }
26882c1f46dcSZachary Turner   return ret_val;
26892c1f46dcSZachary Turner }
26902c1f46dcSZachary Turner 
269163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
269263dd5d25SJonas Devlieghere     const char *impl_function, Target *target, std::string &output,
269397206d57SZachary Turner     Status &error) {
26942c1f46dcSZachary Turner   bool ret_val;
2695b9c1b51eSKate Stone   if (!target) {
26962c1f46dcSZachary Turner     error.SetErrorString("no thread");
26972c1f46dcSZachary Turner     return false;
26982c1f46dcSZachary Turner   }
2699b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
27002c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
27012c1f46dcSZachary Turner     return false;
27022c1f46dcSZachary Turner   }
270305495c5dSJonas Devlieghere 
27042c1f46dcSZachary Turner   {
27052c1f46dcSZachary Turner     TargetSP target_sp(target->shared_from_this());
2706b9c1b51eSKate Stone     Locker py_lock(this,
2707b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
270805495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordTarget(
2709b9c1b51eSKate Stone         impl_function, m_dictionary_name.c_str(), target_sp, output);
27102c1f46dcSZachary Turner     if (!ret_val)
27112c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
27122c1f46dcSZachary Turner   }
27132c1f46dcSZachary Turner   return ret_val;
27142c1f46dcSZachary Turner }
27152c1f46dcSZachary Turner 
271663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
271763dd5d25SJonas Devlieghere     const char *impl_function, StackFrame *frame, std::string &output,
271897206d57SZachary Turner     Status &error) {
27192c1f46dcSZachary Turner   bool ret_val;
2720b9c1b51eSKate Stone   if (!frame) {
27212c1f46dcSZachary Turner     error.SetErrorString("no frame");
27222c1f46dcSZachary Turner     return false;
27232c1f46dcSZachary Turner   }
2724b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
27252c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
27262c1f46dcSZachary Turner     return false;
27272c1f46dcSZachary Turner   }
272805495c5dSJonas Devlieghere 
27292c1f46dcSZachary Turner   {
27302c1f46dcSZachary Turner     StackFrameSP frame_sp(frame->shared_from_this());
2731b9c1b51eSKate Stone     Locker py_lock(this,
2732b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
273305495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordFrame(
2734b9c1b51eSKate Stone         impl_function, m_dictionary_name.c_str(), frame_sp, output);
27352c1f46dcSZachary Turner     if (!ret_val)
27362c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
27372c1f46dcSZachary Turner   }
27382c1f46dcSZachary Turner   return ret_val;
27392c1f46dcSZachary Turner }
27402c1f46dcSZachary Turner 
274163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
274263dd5d25SJonas Devlieghere     const char *impl_function, ValueObject *value, std::string &output,
274397206d57SZachary Turner     Status &error) {
27442c1f46dcSZachary Turner   bool ret_val;
2745b9c1b51eSKate Stone   if (!value) {
27462c1f46dcSZachary Turner     error.SetErrorString("no value");
27472c1f46dcSZachary Turner     return false;
27482c1f46dcSZachary Turner   }
2749b9c1b51eSKate Stone   if (!impl_function || !impl_function[0]) {
27502c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
27512c1f46dcSZachary Turner     return false;
27522c1f46dcSZachary Turner   }
275305495c5dSJonas Devlieghere 
27542c1f46dcSZachary Turner   {
27552c1f46dcSZachary Turner     ValueObjectSP value_sp(value->GetSP());
2756b9c1b51eSKate Stone     Locker py_lock(this,
2757b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
275805495c5dSJonas Devlieghere     ret_val = LLDBSWIGPythonRunScriptKeywordValue(
2759b9c1b51eSKate Stone         impl_function, m_dictionary_name.c_str(), value_sp, output);
27602c1f46dcSZachary Turner     if (!ret_val)
27612c1f46dcSZachary Turner       error.SetErrorString("python script evaluation failed");
27622c1f46dcSZachary Turner   }
27632c1f46dcSZachary Turner   return ret_val;
27642c1f46dcSZachary Turner }
27652c1f46dcSZachary Turner 
2766b9c1b51eSKate Stone uint64_t replace_all(std::string &str, const std::string &oldStr,
2767b9c1b51eSKate Stone                      const std::string &newStr) {
27682c1f46dcSZachary Turner   size_t pos = 0;
27692c1f46dcSZachary Turner   uint64_t matches = 0;
2770b9c1b51eSKate Stone   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
27712c1f46dcSZachary Turner     matches++;
27722c1f46dcSZachary Turner     str.replace(pos, oldStr.length(), newStr);
27732c1f46dcSZachary Turner     pos += newStr.length();
27742c1f46dcSZachary Turner   }
27752c1f46dcSZachary Turner   return matches;
27762c1f46dcSZachary Turner }
27772c1f46dcSZachary Turner 
277863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2779f9517353SJonas Devlieghere     const char *pathname, const LoadScriptOptions &options,
2780f9517353SJonas Devlieghere     lldb_private::Status &error, StructuredData::ObjectSP *module_sp,
2781f9517353SJonas Devlieghere     FileSpec extra_search_dir) {
27823b33b416SJonas Devlieghere   namespace fs = llvm::sys::fs;
278300bb397bSJonas Devlieghere   namespace path = llvm::sys::path;
27843b33b416SJonas Devlieghere 
2785f9517353SJonas Devlieghere   ExecuteScriptOptions exc_options = ExecuteScriptOptions()
2786f9517353SJonas Devlieghere                                          .SetEnableIO(!options.GetSilent())
2787f9517353SJonas Devlieghere                                          .SetSetLLDBGlobals(false);
2788f9517353SJonas Devlieghere 
2789b9c1b51eSKate Stone   if (!pathname || !pathname[0]) {
27902c1f46dcSZachary Turner     error.SetErrorString("invalid pathname");
27912c1f46dcSZachary Turner     return false;
27922c1f46dcSZachary Turner   }
27932c1f46dcSZachary Turner 
2794f9517353SJonas Devlieghere   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2795f9517353SJonas Devlieghere       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2796f9517353SJonas Devlieghere           exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2797f9517353SJonas Devlieghere 
2798f9517353SJonas Devlieghere   if (!io_redirect_or_error) {
2799f9517353SJonas Devlieghere     error = io_redirect_or_error.takeError();
2800f9517353SJonas Devlieghere     return false;
2801f9517353SJonas Devlieghere   }
2802f9517353SJonas Devlieghere 
2803f9517353SJonas Devlieghere   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
28048d1fb843SJonas Devlieghere   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
28052c1f46dcSZachary Turner 
2806f9f36097SAdrian McCarthy   // Before executing Python code, lock the GIL.
280720b52c33SJonas Devlieghere   Locker py_lock(this,
280820b52c33SJonas Devlieghere                  Locker::AcquireLock |
2809f9517353SJonas Devlieghere                      (options.GetInitSession() ? Locker::InitSession : 0) |
2810f9517353SJonas Devlieghere                      Locker::NoSTDIN,
2811b9c1b51eSKate Stone                  Locker::FreeAcquiredLock |
2812f9517353SJonas Devlieghere                      (options.GetInitSession() ? Locker::TearDownSession : 0),
2813f9517353SJonas Devlieghere                  io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2814f9517353SJonas Devlieghere                  io_redirect.GetErrorFile());
28152c1f46dcSZachary Turner 
2816f9517353SJonas Devlieghere   auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
281700bb397bSJonas Devlieghere     if (directory.empty()) {
281800bb397bSJonas Devlieghere       return llvm::make_error<llvm::StringError>(
281900bb397bSJonas Devlieghere           "invalid directory name", llvm::inconvertibleErrorCode());
282042a9da7bSStefan Granitz     }
282142a9da7bSStefan Granitz 
2822f9f36097SAdrian McCarthy     replace_all(directory, "\\", "\\\\");
28232c1f46dcSZachary Turner     replace_all(directory, "'", "\\'");
28242c1f46dcSZachary Turner 
282500bb397bSJonas Devlieghere     // Make sure that Python has "directory" in the search path.
28262c1f46dcSZachary Turner     StreamString command_stream;
2827b9c1b51eSKate Stone     command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
2828b9c1b51eSKate Stone                           "sys.path.insert(1,'%s');\n\n",
2829b9c1b51eSKate Stone                           directory.c_str(), directory.c_str());
2830b9c1b51eSKate Stone     bool syspath_retval =
2831f9517353SJonas Devlieghere         ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
2832b9c1b51eSKate Stone     if (!syspath_retval) {
283300bb397bSJonas Devlieghere       return llvm::make_error<llvm::StringError>(
283400bb397bSJonas Devlieghere           "Python sys.path handling failed", llvm::inconvertibleErrorCode());
28352c1f46dcSZachary Turner     }
28362c1f46dcSZachary Turner 
283700bb397bSJonas Devlieghere     return llvm::Error::success();
283800bb397bSJonas Devlieghere   };
283900bb397bSJonas Devlieghere 
284000bb397bSJonas Devlieghere   std::string module_name(pathname);
2841d6e80578SJonas Devlieghere   bool possible_package = false;
284200bb397bSJonas Devlieghere 
284300bb397bSJonas Devlieghere   if (extra_search_dir) {
284400bb397bSJonas Devlieghere     if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
284500bb397bSJonas Devlieghere       error = std::move(e);
284600bb397bSJonas Devlieghere       return false;
284700bb397bSJonas Devlieghere     }
284800bb397bSJonas Devlieghere   } else {
284900bb397bSJonas Devlieghere     FileSpec module_file(pathname);
285000bb397bSJonas Devlieghere     FileSystem::Instance().Resolve(module_file);
285100bb397bSJonas Devlieghere     FileSystem::Instance().Collect(module_file);
285200bb397bSJonas Devlieghere 
285300bb397bSJonas Devlieghere     fs::file_status st;
285400bb397bSJonas Devlieghere     std::error_code ec = status(module_file.GetPath(), st);
285500bb397bSJonas Devlieghere 
285600bb397bSJonas Devlieghere     if (ec || st.type() == fs::file_type::status_error ||
285700bb397bSJonas Devlieghere         st.type() == fs::file_type::type_unknown ||
285800bb397bSJonas Devlieghere         st.type() == fs::file_type::file_not_found) {
285900bb397bSJonas Devlieghere       // if not a valid file of any sort, check if it might be a filename still
286000bb397bSJonas Devlieghere       // dot can't be used but / and \ can, and if either is found, reject
286100bb397bSJonas Devlieghere       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
286200bb397bSJonas Devlieghere         error.SetErrorString("invalid pathname");
286300bb397bSJonas Devlieghere         return false;
286400bb397bSJonas Devlieghere       }
286500bb397bSJonas Devlieghere       // Not a filename, probably a package of some sort, let it go through.
2866d6e80578SJonas Devlieghere       possible_package = true;
286700bb397bSJonas Devlieghere     } else if (is_directory(st) || is_regular_file(st)) {
286800bb397bSJonas Devlieghere       if (module_file.GetDirectory().IsEmpty()) {
286900bb397bSJonas Devlieghere         error.SetErrorString("invalid directory name");
287000bb397bSJonas Devlieghere         return false;
287100bb397bSJonas Devlieghere       }
287200bb397bSJonas Devlieghere       if (llvm::Error e =
287300bb397bSJonas Devlieghere               ExtendSysPath(module_file.GetDirectory().GetCString())) {
287400bb397bSJonas Devlieghere         error = std::move(e);
287500bb397bSJonas Devlieghere         return false;
287600bb397bSJonas Devlieghere       }
287700bb397bSJonas Devlieghere       module_name = module_file.GetFilename().GetCString();
2878b9c1b51eSKate Stone     } else {
28792c1f46dcSZachary Turner       error.SetErrorString("no known way to import this module specification");
28802c1f46dcSZachary Turner       return false;
28812c1f46dcSZachary Turner     }
288200bb397bSJonas Devlieghere   }
28832c1f46dcSZachary Turner 
28841197ee35SJonas Devlieghere   // Strip .py or .pyc extension
288500bb397bSJonas Devlieghere   llvm::StringRef extension = llvm::sys::path::extension(module_name);
28861197ee35SJonas Devlieghere   if (!extension.empty()) {
28871197ee35SJonas Devlieghere     if (extension == ".py")
288800bb397bSJonas Devlieghere       module_name.resize(module_name.length() - 3);
28891197ee35SJonas Devlieghere     else if (extension == ".pyc")
289000bb397bSJonas Devlieghere       module_name.resize(module_name.length() - 4);
28911197ee35SJonas Devlieghere   }
28921197ee35SJonas Devlieghere 
2893d6e80578SJonas Devlieghere   if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2894d6e80578SJonas Devlieghere     error.SetErrorStringWithFormat(
2895d6e80578SJonas Devlieghere         "Python does not allow dots in module names: %s", module_name.c_str());
2896d6e80578SJonas Devlieghere     return false;
2897d6e80578SJonas Devlieghere   }
2898d6e80578SJonas Devlieghere 
2899d6e80578SJonas Devlieghere   if (module_name.find('-') != llvm::StringRef::npos) {
2900d6e80578SJonas Devlieghere     error.SetErrorStringWithFormat(
2901d6e80578SJonas Devlieghere         "Python discourages dashes in module names: %s", module_name.c_str());
2902d6e80578SJonas Devlieghere     return false;
2903d6e80578SJonas Devlieghere   }
2904d6e80578SJonas Devlieghere 
2905f9517353SJonas Devlieghere   // Check if the module is already imported.
290600bb397bSJonas Devlieghere   StreamString command_stream;
29072c1f46dcSZachary Turner   command_stream.Clear();
290800bb397bSJonas Devlieghere   command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
29092c1f46dcSZachary Turner   bool does_contain = false;
2910f9517353SJonas Devlieghere   // This call will succeed if the module was ever imported in any Debugger in
2911f9517353SJonas Devlieghere   // the lifetime of the process in which this LLDB framework is living.
2912f9517353SJonas Devlieghere   const bool does_contain_executed = ExecuteOneLineWithReturn(
2913b9c1b51eSKate Stone       command_stream.GetData(),
2914f9517353SJonas Devlieghere       ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options);
2915f9517353SJonas Devlieghere 
2916f9517353SJonas Devlieghere   const bool was_imported_globally = does_contain_executed && does_contain;
2917612384f6SJonas Devlieghere   const bool was_imported_locally =
2918612384f6SJonas Devlieghere       GetSessionDictionary()
291900bb397bSJonas Devlieghere           .GetItemForKey(PythonString(module_name))
2920b9c1b51eSKate Stone           .IsAllocated();
29212c1f46dcSZachary Turner 
29222c1f46dcSZachary Turner   // now actually do the import
29232c1f46dcSZachary Turner   command_stream.Clear();
29242c1f46dcSZachary Turner 
2925612384f6SJonas Devlieghere   if (was_imported_globally || was_imported_locally) {
29262c1f46dcSZachary Turner     if (!was_imported_locally)
292700bb397bSJonas Devlieghere       command_stream.Printf("import %s ; reload_module(%s)",
292800bb397bSJonas Devlieghere                             module_name.c_str(), module_name.c_str());
29292c1f46dcSZachary Turner     else
293000bb397bSJonas Devlieghere       command_stream.Printf("reload_module(%s)", module_name.c_str());
2931b9c1b51eSKate Stone   } else
293200bb397bSJonas Devlieghere     command_stream.Printf("import %s", module_name.c_str());
29332c1f46dcSZachary Turner 
2934f9517353SJonas Devlieghere   error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
29352c1f46dcSZachary Turner   if (error.Fail())
29362c1f46dcSZachary Turner     return false;
29372c1f46dcSZachary Turner 
29382c1f46dcSZachary Turner   // if we are here, everything worked
29392c1f46dcSZachary Turner   // call __lldb_init_module(debugger,dict)
294000bb397bSJonas Devlieghere   if (!LLDBSwigPythonCallModuleInit(module_name.c_str(),
294100bb397bSJonas Devlieghere                                     m_dictionary_name.c_str(), debugger_sp)) {
29422c1f46dcSZachary Turner     error.SetErrorString("calling __lldb_init_module failed");
29432c1f46dcSZachary Turner     return false;
29442c1f46dcSZachary Turner   }
29452c1f46dcSZachary Turner 
2946b9c1b51eSKate Stone   if (module_sp) {
29472c1f46dcSZachary Turner     // everything went just great, now set the module object
29482c1f46dcSZachary Turner     command_stream.Clear();
294900bb397bSJonas Devlieghere     command_stream.Printf("%s", module_name.c_str());
29502c1f46dcSZachary Turner     void *module_pyobj = nullptr;
2951b9c1b51eSKate Stone     if (ExecuteOneLineWithReturn(
2952b9c1b51eSKate Stone             command_stream.GetData(),
2953f9517353SJonas Devlieghere             ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2954f9517353SJonas Devlieghere             exc_options) &&
2955b9c1b51eSKate Stone         module_pyobj)
2956796ac80bSJonas Devlieghere       *module_sp = std::make_shared<StructuredPythonObject>(module_pyobj);
29572c1f46dcSZachary Turner   }
29582c1f46dcSZachary Turner 
29592c1f46dcSZachary Turner   return true;
29602c1f46dcSZachary Turner }
29612c1f46dcSZachary Turner 
296263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
29632c1f46dcSZachary Turner   if (!word || !word[0])
29642c1f46dcSZachary Turner     return false;
29652c1f46dcSZachary Turner 
29662c1f46dcSZachary Turner   llvm::StringRef word_sr(word);
29672c1f46dcSZachary Turner 
296805097246SAdrian Prantl   // filter out a few characters that would just confuse us and that are
296905097246SAdrian Prantl   // clearly not keyword material anyway
297010b113e8SJonas Devlieghere   if (word_sr.find('"') != llvm::StringRef::npos ||
297110b113e8SJonas Devlieghere       word_sr.find('\'') != llvm::StringRef::npos)
29722c1f46dcSZachary Turner     return false;
29732c1f46dcSZachary Turner 
29742c1f46dcSZachary Turner   StreamString command_stream;
29752c1f46dcSZachary Turner   command_stream.Printf("keyword.iskeyword('%s')", word);
29762c1f46dcSZachary Turner   bool result;
29772c1f46dcSZachary Turner   ExecuteScriptOptions options;
29782c1f46dcSZachary Turner   options.SetEnableIO(false);
29792c1f46dcSZachary Turner   options.SetMaskoutErrors(true);
29802c1f46dcSZachary Turner   options.SetSetLLDBGlobals(false);
2981b9c1b51eSKate Stone   if (ExecuteOneLineWithReturn(command_stream.GetData(),
2982b9c1b51eSKate Stone                                ScriptInterpreter::eScriptReturnTypeBool,
2983b9c1b51eSKate Stone                                &result, options))
29842c1f46dcSZachary Turner     return result;
29852c1f46dcSZachary Turner   return false;
29862c1f46dcSZachary Turner }
29872c1f46dcSZachary Turner 
298863dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2989b9c1b51eSKate Stone     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2990b9c1b51eSKate Stone     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2991b9c1b51eSKate Stone       m_old_asynch(debugger_sp->GetAsyncExecution()) {
29922c1f46dcSZachary Turner   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
29932c1f46dcSZachary Turner     m_debugger_sp->SetAsyncExecution(false);
29942c1f46dcSZachary Turner   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
29952c1f46dcSZachary Turner     m_debugger_sp->SetAsyncExecution(true);
29962c1f46dcSZachary Turner }
29972c1f46dcSZachary Turner 
299863dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
29992c1f46dcSZachary Turner   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
30002c1f46dcSZachary Turner     m_debugger_sp->SetAsyncExecution(m_old_asynch);
30012c1f46dcSZachary Turner }
30022c1f46dcSZachary Turner 
300363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
30044d51a902SRaphael Isemann     const char *impl_function, llvm::StringRef args,
30052c1f46dcSZachary Turner     ScriptedCommandSynchronicity synchronicity,
300697206d57SZachary Turner     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
3007b9c1b51eSKate Stone     const lldb_private::ExecutionContext &exe_ctx) {
3008b9c1b51eSKate Stone   if (!impl_function) {
30092c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
30102c1f46dcSZachary Turner     return false;
30112c1f46dcSZachary Turner   }
30122c1f46dcSZachary Turner 
30138d1fb843SJonas Devlieghere   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
30142c1f46dcSZachary Turner   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
30152c1f46dcSZachary Turner 
3016b9c1b51eSKate Stone   if (!debugger_sp.get()) {
30172c1f46dcSZachary Turner     error.SetErrorString("invalid Debugger pointer");
30182c1f46dcSZachary Turner     return false;
30192c1f46dcSZachary Turner   }
30202c1f46dcSZachary Turner 
30212c1f46dcSZachary Turner   bool ret_val = false;
30222c1f46dcSZachary Turner 
30232c1f46dcSZachary Turner   std::string err_msg;
30242c1f46dcSZachary Turner 
30252c1f46dcSZachary Turner   {
30262c1f46dcSZachary Turner     Locker py_lock(this,
3027b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession |
3028b9c1b51eSKate Stone                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
30292c1f46dcSZachary Turner                    Locker::FreeLock | Locker::TearDownSession);
30302c1f46dcSZachary Turner 
3031b9c1b51eSKate Stone     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
30322c1f46dcSZachary Turner 
30334d51a902SRaphael Isemann     std::string args_str = args.str();
303405495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCallCommand(
303505495c5dSJonas Devlieghere         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
303605495c5dSJonas Devlieghere         cmd_retobj, exe_ctx_ref_sp);
30372c1f46dcSZachary Turner   }
30382c1f46dcSZachary Turner 
30392c1f46dcSZachary Turner   if (!ret_val)
30402c1f46dcSZachary Turner     error.SetErrorString("unable to execute script function");
30412c1f46dcSZachary Turner   else
30422c1f46dcSZachary Turner     error.Clear();
30432c1f46dcSZachary Turner 
30442c1f46dcSZachary Turner   return ret_val;
30452c1f46dcSZachary Turner }
30462c1f46dcSZachary Turner 
304763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
30484d51a902SRaphael Isemann     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
30492c1f46dcSZachary Turner     ScriptedCommandSynchronicity synchronicity,
305097206d57SZachary Turner     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
3051b9c1b51eSKate Stone     const lldb_private::ExecutionContext &exe_ctx) {
3052b9c1b51eSKate Stone   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
30532c1f46dcSZachary Turner     error.SetErrorString("no function to execute");
30542c1f46dcSZachary Turner     return false;
30552c1f46dcSZachary Turner   }
30562c1f46dcSZachary Turner 
30578d1fb843SJonas Devlieghere   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
30582c1f46dcSZachary Turner   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
30592c1f46dcSZachary Turner 
3060b9c1b51eSKate Stone   if (!debugger_sp.get()) {
30612c1f46dcSZachary Turner     error.SetErrorString("invalid Debugger pointer");
30622c1f46dcSZachary Turner     return false;
30632c1f46dcSZachary Turner   }
30642c1f46dcSZachary Turner 
30652c1f46dcSZachary Turner   bool ret_val = false;
30662c1f46dcSZachary Turner 
30672c1f46dcSZachary Turner   std::string err_msg;
30682c1f46dcSZachary Turner 
30692c1f46dcSZachary Turner   {
30702c1f46dcSZachary Turner     Locker py_lock(this,
3071b9c1b51eSKate Stone                    Locker::AcquireLock | Locker::InitSession |
3072b9c1b51eSKate Stone                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
30732c1f46dcSZachary Turner                    Locker::FreeLock | Locker::TearDownSession);
30742c1f46dcSZachary Turner 
3075b9c1b51eSKate Stone     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
30762c1f46dcSZachary Turner 
30774d51a902SRaphael Isemann     std::string args_str = args.str();
307805495c5dSJonas Devlieghere     ret_val = LLDBSwigPythonCallCommandObject(impl_obj_sp->GetValue(),
307905495c5dSJonas Devlieghere                                               debugger_sp, args_str.c_str(),
308005495c5dSJonas Devlieghere                                               cmd_retobj, exe_ctx_ref_sp);
30812c1f46dcSZachary Turner   }
30822c1f46dcSZachary Turner 
30832c1f46dcSZachary Turner   if (!ret_val)
30842c1f46dcSZachary Turner     error.SetErrorString("unable to execute script function");
30852c1f46dcSZachary Turner   else
30862c1f46dcSZachary Turner     error.Clear();
30872c1f46dcSZachary Turner 
30882c1f46dcSZachary Turner   return ret_val;
30892c1f46dcSZachary Turner }
30902c1f46dcSZachary Turner 
309193571c3cSJonas Devlieghere /// In Python, a special attribute __doc__ contains the docstring for an object
309293571c3cSJonas Devlieghere /// (function, method, class, ...) if any is defined Otherwise, the attribute's
309393571c3cSJonas Devlieghere /// value is None.
309463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
3095b9c1b51eSKate Stone                                                           std::string &dest) {
30962c1f46dcSZachary Turner   dest.clear();
309793571c3cSJonas Devlieghere 
30982c1f46dcSZachary Turner   if (!item || !*item)
30992c1f46dcSZachary Turner     return false;
310093571c3cSJonas Devlieghere 
31012c1f46dcSZachary Turner   std::string command(item);
31022c1f46dcSZachary Turner   command += ".__doc__";
31032c1f46dcSZachary Turner 
310493571c3cSJonas Devlieghere   // Python is going to point this to valid data if ExecuteOneLineWithReturn
310593571c3cSJonas Devlieghere   // returns successfully.
310693571c3cSJonas Devlieghere   char *result_ptr = nullptr;
31072c1f46dcSZachary Turner 
3108b9c1b51eSKate Stone   if (ExecuteOneLineWithReturn(
310993571c3cSJonas Devlieghere           command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
31102c1f46dcSZachary Turner           &result_ptr,
3111fd2433e1SJonas Devlieghere           ExecuteScriptOptions().SetEnableIO(false))) {
31122c1f46dcSZachary Turner     if (result_ptr)
31132c1f46dcSZachary Turner       dest.assign(result_ptr);
31142c1f46dcSZachary Turner     return true;
31152c1f46dcSZachary Turner   }
311693571c3cSJonas Devlieghere 
311793571c3cSJonas Devlieghere   StreamString str_stream;
311893571c3cSJonas Devlieghere   str_stream << "Function " << item
311993571c3cSJonas Devlieghere              << " was not found. Containing module might be missing.";
312093571c3cSJonas Devlieghere   dest = std::string(str_stream.GetString());
312193571c3cSJonas Devlieghere 
312293571c3cSJonas Devlieghere   return false;
31232c1f46dcSZachary Turner }
31242c1f46dcSZachary Turner 
312563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
3126b9c1b51eSKate Stone     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
31272c1f46dcSZachary Turner   dest.clear();
31282c1f46dcSZachary Turner 
3129b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
31302c1f46dcSZachary Turner 
31312c1f46dcSZachary Turner   static char callee_name[] = "get_short_help";
31322c1f46dcSZachary Turner 
31332c1f46dcSZachary Turner   if (!cmd_obj_sp)
31342c1f46dcSZachary Turner     return false;
31352c1f46dcSZachary Turner 
3136b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
3137b9c1b51eSKate Stone                            (PyObject *)cmd_obj_sp->GetValue());
31382c1f46dcSZachary Turner 
3139f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
31402c1f46dcSZachary Turner     return false;
31412c1f46dcSZachary Turner 
3142b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
3143b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
31442c1f46dcSZachary Turner 
31452c1f46dcSZachary Turner   if (PyErr_Occurred())
31462c1f46dcSZachary Turner     PyErr_Clear();
31472c1f46dcSZachary Turner 
3148f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
31492c1f46dcSZachary Turner     return false;
31502c1f46dcSZachary Turner 
3151b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
31522c1f46dcSZachary Turner     if (PyErr_Occurred())
31532c1f46dcSZachary Turner       PyErr_Clear();
31542c1f46dcSZachary Turner     return false;
31552c1f46dcSZachary Turner   }
31562c1f46dcSZachary Turner 
31572c1f46dcSZachary Turner   if (PyErr_Occurred())
31582c1f46dcSZachary Turner     PyErr_Clear();
31592c1f46dcSZachary Turner 
316093571c3cSJonas Devlieghere   // Right now we know this function exists and is callable.
3161b9c1b51eSKate Stone   PythonObject py_return(
3162b9c1b51eSKate Stone       PyRefType::Owned,
3163b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
31642c1f46dcSZachary Turner 
316593571c3cSJonas Devlieghere   // If it fails, print the error but otherwise go on.
3166b9c1b51eSKate Stone   if (PyErr_Occurred()) {
31672c1f46dcSZachary Turner     PyErr_Print();
31682c1f46dcSZachary Turner     PyErr_Clear();
31692c1f46dcSZachary Turner   }
31702c1f46dcSZachary Turner 
3171b9c1b51eSKate Stone   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3172f8b22f8fSZachary Turner     PythonString py_string(PyRefType::Borrowed, py_return.get());
317322c8efcdSZachary Turner     llvm::StringRef return_data(py_string.GetString());
317422c8efcdSZachary Turner     dest.assign(return_data.data(), return_data.size());
317593571c3cSJonas Devlieghere     return true;
31762c1f46dcSZachary Turner   }
317793571c3cSJonas Devlieghere 
317893571c3cSJonas Devlieghere   return false;
31792c1f46dcSZachary Turner }
31802c1f46dcSZachary Turner 
318163dd5d25SJonas Devlieghere uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
3182b9c1b51eSKate Stone     StructuredData::GenericSP cmd_obj_sp) {
31832c1f46dcSZachary Turner   uint32_t result = 0;
31842c1f46dcSZachary Turner 
3185b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
31862c1f46dcSZachary Turner 
31872c1f46dcSZachary Turner   static char callee_name[] = "get_flags";
31882c1f46dcSZachary Turner 
31892c1f46dcSZachary Turner   if (!cmd_obj_sp)
31902c1f46dcSZachary Turner     return result;
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 result;
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 result;
32062c1f46dcSZachary Turner 
3207b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
32082c1f46dcSZachary Turner     if (PyErr_Occurred())
32092c1f46dcSZachary Turner       PyErr_Clear();
32102c1f46dcSZachary Turner     return result;
32112c1f46dcSZachary Turner   }
32122c1f46dcSZachary Turner 
32132c1f46dcSZachary Turner   if (PyErr_Occurred())
32142c1f46dcSZachary Turner     PyErr_Clear();
32152c1f46dcSZachary Turner 
321652712d3fSLawrence D'Anna   long long py_return = unwrapOrSetPythonException(
321752712d3fSLawrence D'Anna       As<long long>(implementor.CallMethod(callee_name)));
32182c1f46dcSZachary Turner 
32192c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
3220b9c1b51eSKate Stone   if (PyErr_Occurred()) {
32212c1f46dcSZachary Turner     PyErr_Print();
32222c1f46dcSZachary Turner     PyErr_Clear();
322352712d3fSLawrence D'Anna   } else {
322452712d3fSLawrence D'Anna     result = py_return;
32252c1f46dcSZachary Turner   }
32262c1f46dcSZachary Turner 
32272c1f46dcSZachary Turner   return result;
32282c1f46dcSZachary Turner }
32292c1f46dcSZachary Turner 
323063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3231b9c1b51eSKate Stone     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
32322c1f46dcSZachary Turner   bool got_string = false;
32332c1f46dcSZachary Turner   dest.clear();
32342c1f46dcSZachary Turner 
3235b9c1b51eSKate Stone   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
32362c1f46dcSZachary Turner 
32372c1f46dcSZachary Turner   static char callee_name[] = "get_long_help";
32382c1f46dcSZachary Turner 
32392c1f46dcSZachary Turner   if (!cmd_obj_sp)
32402c1f46dcSZachary Turner     return false;
32412c1f46dcSZachary Turner 
3242b9c1b51eSKate Stone   PythonObject implementor(PyRefType::Borrowed,
3243b9c1b51eSKate Stone                            (PyObject *)cmd_obj_sp->GetValue());
32442c1f46dcSZachary Turner 
3245f8b22f8fSZachary Turner   if (!implementor.IsAllocated())
32462c1f46dcSZachary Turner     return false;
32472c1f46dcSZachary Turner 
3248b9c1b51eSKate Stone   PythonObject pmeth(PyRefType::Owned,
3249b9c1b51eSKate Stone                      PyObject_GetAttrString(implementor.get(), callee_name));
32502c1f46dcSZachary Turner 
32512c1f46dcSZachary Turner   if (PyErr_Occurred())
32522c1f46dcSZachary Turner     PyErr_Clear();
32532c1f46dcSZachary Turner 
3254f8b22f8fSZachary Turner   if (!pmeth.IsAllocated())
32552c1f46dcSZachary Turner     return false;
32562c1f46dcSZachary Turner 
3257b9c1b51eSKate Stone   if (PyCallable_Check(pmeth.get()) == 0) {
32582c1f46dcSZachary Turner     if (PyErr_Occurred())
32592c1f46dcSZachary Turner       PyErr_Clear();
32602c1f46dcSZachary Turner 
32612c1f46dcSZachary Turner     return false;
32622c1f46dcSZachary Turner   }
32632c1f46dcSZachary Turner 
32642c1f46dcSZachary Turner   if (PyErr_Occurred())
32652c1f46dcSZachary Turner     PyErr_Clear();
32662c1f46dcSZachary Turner 
32672c1f46dcSZachary Turner   // right now we know this function exists and is callable..
3268b9c1b51eSKate Stone   PythonObject py_return(
3269b9c1b51eSKate Stone       PyRefType::Owned,
3270b9c1b51eSKate Stone       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
32712c1f46dcSZachary Turner 
32722c1f46dcSZachary Turner   // if it fails, print the error but otherwise go on
3273b9c1b51eSKate Stone   if (PyErr_Occurred()) {
32742c1f46dcSZachary Turner     PyErr_Print();
32752c1f46dcSZachary Turner     PyErr_Clear();
32762c1f46dcSZachary Turner   }
32772c1f46dcSZachary Turner 
3278b9c1b51eSKate Stone   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3279f8b22f8fSZachary Turner     PythonString str(PyRefType::Borrowed, py_return.get());
328022c8efcdSZachary Turner     llvm::StringRef str_data(str.GetString());
328122c8efcdSZachary Turner     dest.assign(str_data.data(), str_data.size());
32822c1f46dcSZachary Turner     got_string = true;
32832c1f46dcSZachary Turner   }
32842c1f46dcSZachary Turner 
32852c1f46dcSZachary Turner   return got_string;
32862c1f46dcSZachary Turner }
32872c1f46dcSZachary Turner 
32882c1f46dcSZachary Turner std::unique_ptr<ScriptInterpreterLocker>
328963dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3290b9c1b51eSKate Stone   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3291b9c1b51eSKate Stone       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
32922c1f46dcSZachary Turner       Locker::FreeLock | Locker::TearDownSession));
32932c1f46dcSZachary Turner   return py_lock;
32942c1f46dcSZachary Turner }
32952c1f46dcSZachary Turner 
329663dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::InitializePrivate() {
329715d1b4e2SEnrico Granata   if (g_initialized)
329815d1b4e2SEnrico Granata     return;
329915d1b4e2SEnrico Granata 
33002c1f46dcSZachary Turner   g_initialized = true;
33012c1f46dcSZachary Turner 
33025c1c8443SJonas Devlieghere   LLDB_SCOPED_TIMER();
33032c1f46dcSZachary Turner 
3304b9c1b51eSKate Stone   // RAII-based initialization which correctly handles multiple-initialization,
330505097246SAdrian Prantl   // version- specific differences among Python 2 and Python 3, and saving and
330605097246SAdrian Prantl   // restoring various other pieces of state that can get mucked with during
330705097246SAdrian Prantl   // initialization.
3308079fe48aSZachary Turner   InitializePythonRAII initialize_guard;
33092c1f46dcSZachary Turner 
331005495c5dSJonas Devlieghere   LLDBSwigPyInit();
33112c1f46dcSZachary Turner 
3312b9c1b51eSKate Stone   // Update the path python uses to search for modules to include the current
3313b9c1b51eSKate Stone   // directory.
33142c1f46dcSZachary Turner 
33152c1f46dcSZachary Turner   PyRun_SimpleString("import sys");
33162c1f46dcSZachary Turner   AddToSysPath(AddLocation::End, ".");
33172c1f46dcSZachary Turner 
3318b9c1b51eSKate Stone   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
331905097246SAdrian Prantl   // that use a backslash as the path separator, this will result in executing
332005097246SAdrian Prantl   // python code containing paths with unescaped backslashes.  But Python also
332105097246SAdrian Prantl   // accepts forward slashes, so to make life easier we just use that.
33222df331b0SPavel Labath   if (FileSpec file_spec = GetPythonDir())
33232c1f46dcSZachary Turner     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
332460f028ffSPavel Labath   if (FileSpec file_spec = HostInfo::GetShlibDir())
33252c1f46dcSZachary Turner     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
33262c1f46dcSZachary Turner 
3327b9c1b51eSKate Stone   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3328b9c1b51eSKate Stone                      "lldb.embedded_interpreter; from "
3329b9c1b51eSKate Stone                      "lldb.embedded_interpreter import run_python_interpreter; "
3330b9c1b51eSKate Stone                      "from lldb.embedded_interpreter import run_one_line");
33312c1f46dcSZachary Turner }
33322c1f46dcSZachary Turner 
333363dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3334b9c1b51eSKate Stone                                                std::string path) {
33352c1f46dcSZachary Turner   std::string path_copy;
33362c1f46dcSZachary Turner 
33372c1f46dcSZachary Turner   std::string statement;
3338b9c1b51eSKate Stone   if (location == AddLocation::Beginning) {
33392c1f46dcSZachary Turner     statement.assign("sys.path.insert(0,\"");
33402c1f46dcSZachary Turner     statement.append(path);
33412c1f46dcSZachary Turner     statement.append("\")");
3342b9c1b51eSKate Stone   } else {
33432c1f46dcSZachary Turner     statement.assign("sys.path.append(\"");
33442c1f46dcSZachary Turner     statement.append(path);
33452c1f46dcSZachary Turner     statement.append("\")");
33462c1f46dcSZachary Turner   }
33472c1f46dcSZachary Turner   PyRun_SimpleString(statement.c_str());
33482c1f46dcSZachary Turner }
33492c1f46dcSZachary Turner 
3350bcadb5a3SPavel Labath // We are intentionally NOT calling Py_Finalize here (this would be the logical
3351bcadb5a3SPavel Labath // place to call it).  Calling Py_Finalize here causes test suite runs to seg
3352bcadb5a3SPavel Labath // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
3353bcadb5a3SPavel Labath // be called 'at_exit'.  When the test suite Python harness finishes up, it
3354bcadb5a3SPavel Labath // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3355bcadb5a3SPavel Labath // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3356bcadb5a3SPavel Labath // which calls ScriptInterpreter::Terminate, which calls
335763dd5d25SJonas Devlieghere // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
335863dd5d25SJonas Devlieghere // end up with Py_Finalize being called from within Py_Finalize, which results
335963dd5d25SJonas Devlieghere // in a seg fault. Since this function only gets called when lldb is shutting
336063dd5d25SJonas Devlieghere // down and going away anyway, the fact that we don't actually call Py_Finalize
3361bcadb5a3SPavel Labath // should not cause any problems (everything should shut down/go away anyway
3362bcadb5a3SPavel Labath // when the process exits).
3363bcadb5a3SPavel Labath //
336463dd5d25SJonas Devlieghere // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3365d68983e3SPavel Labath 
33664e26cf2cSJonas Devlieghere #endif
3367