15ffd83dbSDimitry Andric //===-- ScriptInterpreterPython.cpp ---------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric
9480093f4SDimitry Andric #include "lldb/Host/Config.h"
10af732203SDimitry Andric #include "lldb/lldb-enumerations.h"
110b57cec5SDimitry Andric
12480093f4SDimitry Andric #if LLDB_ENABLE_PYTHON
130b57cec5SDimitry Andric
140b57cec5SDimitry Andric // LLDB Python header must be included first
150b57cec5SDimitry Andric #include "lldb-python.h"
160b57cec5SDimitry Andric
170b57cec5SDimitry Andric #include "PythonDataObjects.h"
18c14a5a88SDimitry Andric #include "PythonReadline.h"
19*5f7ddb14SDimitry Andric #include "SWIGPythonBridge.h"
200b57cec5SDimitry Andric #include "ScriptInterpreterPythonImpl.h"
21*5f7ddb14SDimitry Andric #include "ScriptedProcessPythonInterface.h"
22*5f7ddb14SDimitry Andric
23*5f7ddb14SDimitry Andric #include "lldb/API/SBError.h"
240b57cec5SDimitry Andric #include "lldb/API/SBFrame.h"
250b57cec5SDimitry Andric #include "lldb/API/SBValue.h"
260b57cec5SDimitry Andric #include "lldb/Breakpoint/StoppointCallbackContext.h"
270b57cec5SDimitry Andric #include "lldb/Breakpoint/WatchpointOptions.h"
280b57cec5SDimitry Andric #include "lldb/Core/Communication.h"
290b57cec5SDimitry Andric #include "lldb/Core/Debugger.h"
300b57cec5SDimitry Andric #include "lldb/Core/PluginManager.h"
310b57cec5SDimitry Andric #include "lldb/Core/ValueObject.h"
320b57cec5SDimitry Andric #include "lldb/DataFormatters/TypeSummary.h"
330b57cec5SDimitry Andric #include "lldb/Host/FileSystem.h"
340b57cec5SDimitry Andric #include "lldb/Host/HostInfo.h"
350b57cec5SDimitry Andric #include "lldb/Host/Pipe.h"
360b57cec5SDimitry Andric #include "lldb/Interpreter/CommandInterpreter.h"
370b57cec5SDimitry Andric #include "lldb/Interpreter/CommandReturnObject.h"
380b57cec5SDimitry Andric #include "lldb/Target/Thread.h"
390b57cec5SDimitry Andric #include "lldb/Target/ThreadPlan.h"
40af732203SDimitry Andric #include "lldb/Utility/ReproducerInstrumentation.h"
410b57cec5SDimitry Andric #include "lldb/Utility/Timer.h"
420b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
430b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
445ffd83dbSDimitry Andric #include "llvm/Support/Error.h"
450b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
469dba64beSDimitry Andric #include "llvm/Support/FormatAdapters.h"
470b57cec5SDimitry Andric
48*5f7ddb14SDimitry Andric #include <cstdio>
49*5f7ddb14SDimitry Andric #include <cstdlib>
500b57cec5SDimitry Andric #include <memory>
510b57cec5SDimitry Andric #include <mutex>
520b57cec5SDimitry Andric #include <string>
530b57cec5SDimitry Andric
540b57cec5SDimitry Andric using namespace lldb;
550b57cec5SDimitry Andric using namespace lldb_private;
569dba64beSDimitry Andric using namespace lldb_private::python;
579dba64beSDimitry Andric using llvm::Expected;
580b57cec5SDimitry Andric
595ffd83dbSDimitry Andric LLDB_PLUGIN_DEFINE(ScriptInterpreterPython)
605ffd83dbSDimitry Andric
610b57cec5SDimitry Andric // Defined in the SWIG source file
620b57cec5SDimitry Andric #if PY_MAJOR_VERSION >= 3
630b57cec5SDimitry Andric extern "C" PyObject *PyInit__lldb(void);
640b57cec5SDimitry Andric
650b57cec5SDimitry Andric #define LLDBSwigPyInit PyInit__lldb
660b57cec5SDimitry Andric
670b57cec5SDimitry Andric #else
680b57cec5SDimitry Andric extern "C" void init_lldb(void);
690b57cec5SDimitry Andric
700b57cec5SDimitry Andric #define LLDBSwigPyInit init_lldb
710b57cec5SDimitry Andric #endif
720b57cec5SDimitry Andric
730b57cec5SDimitry Andric // These prototypes are the Pythonic implementations of the required callbacks.
740b57cec5SDimitry Andric // Although these are scripting-language specific, their definition depends on
750b57cec5SDimitry Andric // the public API.
76480093f4SDimitry Andric
77480093f4SDimitry Andric #pragma clang diagnostic push
78480093f4SDimitry Andric #pragma clang diagnostic ignored "-Wreturn-type-c-linkage"
79480093f4SDimitry Andric
80480093f4SDimitry Andric // Disable warning C4190: 'LLDBSwigPythonBreakpointCallbackFunction' has
81480093f4SDimitry Andric // C-linkage specified, but returns UDT 'llvm::Expected<bool>' which is
82480093f4SDimitry Andric // incompatible with C
83480093f4SDimitry Andric #if _MSC_VER
84480093f4SDimitry Andric #pragma warning (push)
85480093f4SDimitry Andric #pragma warning (disable : 4190)
86480093f4SDimitry Andric #endif
87480093f4SDimitry Andric
88480093f4SDimitry Andric extern "C" llvm::Expected<bool> LLDBSwigPythonBreakpointCallbackFunction(
890b57cec5SDimitry Andric const char *python_function_name, const char *session_dictionary_name,
900b57cec5SDimitry Andric const lldb::StackFrameSP &sb_frame,
91480093f4SDimitry Andric const lldb::BreakpointLocationSP &sb_bp_loc, StructuredDataImpl *args_impl);
92480093f4SDimitry Andric
93480093f4SDimitry Andric #if _MSC_VER
94480093f4SDimitry Andric #pragma warning (pop)
95480093f4SDimitry Andric #endif
96480093f4SDimitry Andric
97480093f4SDimitry Andric #pragma clang diagnostic pop
980b57cec5SDimitry Andric
990b57cec5SDimitry Andric extern "C" bool LLDBSwigPythonWatchpointCallbackFunction(
1000b57cec5SDimitry Andric const char *python_function_name, const char *session_dictionary_name,
1010b57cec5SDimitry Andric const lldb::StackFrameSP &sb_frame, const lldb::WatchpointSP &sb_wp);
1020b57cec5SDimitry Andric
1030b57cec5SDimitry Andric extern "C" bool LLDBSwigPythonCallTypeScript(
1040b57cec5SDimitry Andric const char *python_function_name, void *session_dictionary,
1050b57cec5SDimitry Andric const lldb::ValueObjectSP &valobj_sp, void **pyfunct_wrapper,
1060b57cec5SDimitry Andric const lldb::TypeSummaryOptionsSP &options_sp, std::string &retval);
1070b57cec5SDimitry Andric
1080b57cec5SDimitry Andric extern "C" void *
1090b57cec5SDimitry Andric LLDBSwigPythonCreateSyntheticProvider(const char *python_class_name,
1100b57cec5SDimitry Andric const char *session_dictionary_name,
1110b57cec5SDimitry Andric const lldb::ValueObjectSP &valobj_sp);
1120b57cec5SDimitry Andric
1130b57cec5SDimitry Andric extern "C" void *
1140b57cec5SDimitry Andric LLDBSwigPythonCreateCommandObject(const char *python_class_name,
1150b57cec5SDimitry Andric const char *session_dictionary_name,
1160b57cec5SDimitry Andric const lldb::DebuggerSP debugger_sp);
1170b57cec5SDimitry Andric
1180b57cec5SDimitry Andric extern "C" void *LLDBSwigPythonCreateScriptedThreadPlan(
1190b57cec5SDimitry Andric const char *python_class_name, const char *session_dictionary_name,
1209dba64beSDimitry Andric StructuredDataImpl *args_data,
1219dba64beSDimitry Andric std::string &error_string,
1220b57cec5SDimitry Andric const lldb::ThreadPlanSP &thread_plan_sp);
1230b57cec5SDimitry Andric
1240b57cec5SDimitry Andric extern "C" bool LLDBSWIGPythonCallThreadPlan(void *implementor,
1250b57cec5SDimitry Andric const char *method_name,
1260b57cec5SDimitry Andric Event *event_sp, bool &got_error);
1270b57cec5SDimitry Andric
1280b57cec5SDimitry Andric extern "C" void *LLDBSwigPythonCreateScriptedBreakpointResolver(
1290b57cec5SDimitry Andric const char *python_class_name, const char *session_dictionary_name,
1300b57cec5SDimitry Andric lldb_private::StructuredDataImpl *args, lldb::BreakpointSP &bkpt_sp);
1310b57cec5SDimitry Andric
1320b57cec5SDimitry Andric extern "C" unsigned int
1330b57cec5SDimitry Andric LLDBSwigPythonCallBreakpointResolver(void *implementor, const char *method_name,
1340b57cec5SDimitry Andric lldb_private::SymbolContext *sym_ctx);
1350b57cec5SDimitry Andric
136af732203SDimitry Andric extern "C" void *LLDBSwigPythonCreateScriptedStopHook(
137af732203SDimitry Andric TargetSP target_sp, const char *python_class_name,
138af732203SDimitry Andric const char *session_dictionary_name, lldb_private::StructuredDataImpl *args,
139af732203SDimitry Andric lldb_private::Status &error);
140af732203SDimitry Andric
141af732203SDimitry Andric extern "C" bool
142af732203SDimitry Andric LLDBSwigPythonStopHookCallHandleStop(void *implementor,
143af732203SDimitry Andric lldb::ExecutionContextRefSP exc_ctx,
144af732203SDimitry Andric lldb::StreamSP stream);
145af732203SDimitry Andric
1460b57cec5SDimitry Andric extern "C" size_t LLDBSwigPython_CalculateNumChildren(void *implementor,
1470b57cec5SDimitry Andric uint32_t max);
1480b57cec5SDimitry Andric
1490b57cec5SDimitry Andric extern "C" void *LLDBSwigPython_GetChildAtIndex(void *implementor,
1500b57cec5SDimitry Andric uint32_t idx);
1510b57cec5SDimitry Andric
1520b57cec5SDimitry Andric extern "C" int LLDBSwigPython_GetIndexOfChildWithName(void *implementor,
1530b57cec5SDimitry Andric const char *child_name);
1540b57cec5SDimitry Andric
1550b57cec5SDimitry Andric extern lldb::ValueObjectSP
1560b57cec5SDimitry Andric LLDBSWIGPython_GetValueObjectSPFromSBValue(void *data);
1570b57cec5SDimitry Andric
1580b57cec5SDimitry Andric extern "C" bool LLDBSwigPython_UpdateSynthProviderInstance(void *implementor);
1590b57cec5SDimitry Andric
1600b57cec5SDimitry Andric extern "C" bool
1610b57cec5SDimitry Andric LLDBSwigPython_MightHaveChildrenSynthProviderInstance(void *implementor);
1620b57cec5SDimitry Andric
1630b57cec5SDimitry Andric extern "C" void *
1640b57cec5SDimitry Andric LLDBSwigPython_GetValueSynthProviderInstance(void *implementor);
1650b57cec5SDimitry Andric
1660b57cec5SDimitry Andric extern "C" bool
1670b57cec5SDimitry Andric LLDBSwigPythonCallCommand(const char *python_function_name,
1680b57cec5SDimitry Andric const char *session_dictionary_name,
1690b57cec5SDimitry Andric lldb::DebuggerSP &debugger, const char *args,
1700b57cec5SDimitry Andric lldb_private::CommandReturnObject &cmd_retobj,
1710b57cec5SDimitry Andric lldb::ExecutionContextRefSP exe_ctx_ref_sp);
1720b57cec5SDimitry Andric
1730b57cec5SDimitry Andric extern "C" bool
1740b57cec5SDimitry Andric LLDBSwigPythonCallCommandObject(void *implementor, lldb::DebuggerSP &debugger,
1750b57cec5SDimitry Andric const char *args,
1760b57cec5SDimitry Andric lldb_private::CommandReturnObject &cmd_retobj,
1770b57cec5SDimitry Andric lldb::ExecutionContextRefSP exe_ctx_ref_sp);
1780b57cec5SDimitry Andric
1790b57cec5SDimitry Andric extern "C" bool
1800b57cec5SDimitry Andric LLDBSwigPythonCallModuleInit(const char *python_module_name,
1810b57cec5SDimitry Andric const char *session_dictionary_name,
1820b57cec5SDimitry Andric lldb::DebuggerSP &debugger);
1830b57cec5SDimitry Andric
1840b57cec5SDimitry Andric extern "C" void *
1850b57cec5SDimitry Andric LLDBSWIGPythonCreateOSPlugin(const char *python_class_name,
1860b57cec5SDimitry Andric const char *session_dictionary_name,
1870b57cec5SDimitry Andric const lldb::ProcessSP &process_sp);
1880b57cec5SDimitry Andric
1890b57cec5SDimitry Andric extern "C" void *
1900b57cec5SDimitry Andric LLDBSWIGPython_CreateFrameRecognizer(const char *python_class_name,
1910b57cec5SDimitry Andric const char *session_dictionary_name);
1920b57cec5SDimitry Andric
1930b57cec5SDimitry Andric extern "C" void *
1940b57cec5SDimitry Andric LLDBSwigPython_GetRecognizedArguments(void *implementor,
1950b57cec5SDimitry Andric const lldb::StackFrameSP &frame_sp);
1960b57cec5SDimitry Andric
1970b57cec5SDimitry Andric extern "C" bool LLDBSWIGPythonRunScriptKeywordProcess(
1980b57cec5SDimitry Andric const char *python_function_name, const char *session_dictionary_name,
1990b57cec5SDimitry Andric lldb::ProcessSP &process, std::string &output);
2000b57cec5SDimitry Andric
2010b57cec5SDimitry Andric extern "C" bool LLDBSWIGPythonRunScriptKeywordThread(
2020b57cec5SDimitry Andric const char *python_function_name, const char *session_dictionary_name,
2030b57cec5SDimitry Andric lldb::ThreadSP &thread, std::string &output);
2040b57cec5SDimitry Andric
2050b57cec5SDimitry Andric extern "C" bool LLDBSWIGPythonRunScriptKeywordTarget(
2060b57cec5SDimitry Andric const char *python_function_name, const char *session_dictionary_name,
2070b57cec5SDimitry Andric lldb::TargetSP &target, std::string &output);
2080b57cec5SDimitry Andric
2090b57cec5SDimitry Andric extern "C" bool LLDBSWIGPythonRunScriptKeywordFrame(
2100b57cec5SDimitry Andric const char *python_function_name, const char *session_dictionary_name,
2110b57cec5SDimitry Andric lldb::StackFrameSP &frame, std::string &output);
2120b57cec5SDimitry Andric
2130b57cec5SDimitry Andric extern "C" bool LLDBSWIGPythonRunScriptKeywordValue(
2140b57cec5SDimitry Andric const char *python_function_name, const char *session_dictionary_name,
2150b57cec5SDimitry Andric lldb::ValueObjectSP &value, std::string &output);
2160b57cec5SDimitry Andric
2170b57cec5SDimitry Andric extern "C" void *
2180b57cec5SDimitry Andric LLDBSWIGPython_GetDynamicSetting(void *module, const char *setting,
2190b57cec5SDimitry Andric const lldb::TargetSP &target_sp);
2200b57cec5SDimitry Andric
GetPythonInterpreter(Debugger & debugger)221af732203SDimitry Andric static ScriptInterpreterPythonImpl *GetPythonInterpreter(Debugger &debugger) {
222af732203SDimitry Andric ScriptInterpreter *script_interpreter =
223af732203SDimitry Andric debugger.GetScriptInterpreter(true, lldb::eScriptLanguagePython);
224af732203SDimitry Andric return static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
225af732203SDimitry Andric }
226af732203SDimitry Andric
2270b57cec5SDimitry Andric static bool g_initialized = false;
2280b57cec5SDimitry Andric
2290b57cec5SDimitry Andric namespace {
2300b57cec5SDimitry Andric
2310b57cec5SDimitry Andric // Initializing Python is not a straightforward process. We cannot control
2320b57cec5SDimitry Andric // what external code may have done before getting to this point in LLDB,
2330b57cec5SDimitry Andric // including potentially having already initialized Python, so we need to do a
2340b57cec5SDimitry Andric // lot of work to ensure that the existing state of the system is maintained
2350b57cec5SDimitry Andric // across our initialization. We do this by using an RAII pattern where we
2360b57cec5SDimitry Andric // save off initial state at the beginning, and restore it at the end
2370b57cec5SDimitry Andric struct InitializePythonRAII {
2380b57cec5SDimitry Andric public:
InitializePythonRAII__anoneceaca260111::InitializePythonRAII239*5f7ddb14SDimitry Andric InitializePythonRAII() {
2400b57cec5SDimitry Andric InitializePythonHome();
2410b57cec5SDimitry Andric
242c14a5a88SDimitry Andric #ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
243c14a5a88SDimitry Andric // Python's readline is incompatible with libedit being linked into lldb.
244c14a5a88SDimitry Andric // Provide a patched version local to the embedded interpreter.
245c14a5a88SDimitry Andric bool ReadlinePatched = false;
246c14a5a88SDimitry Andric for (auto *p = PyImport_Inittab; p->name != NULL; p++) {
247c14a5a88SDimitry Andric if (strcmp(p->name, "readline") == 0) {
248c14a5a88SDimitry Andric p->initfunc = initlldb_readline;
249c14a5a88SDimitry Andric break;
250c14a5a88SDimitry Andric }
251c14a5a88SDimitry Andric }
252c14a5a88SDimitry Andric if (!ReadlinePatched) {
253c14a5a88SDimitry Andric PyImport_AppendInittab("readline", initlldb_readline);
254c14a5a88SDimitry Andric ReadlinePatched = true;
255c14a5a88SDimitry Andric }
256c14a5a88SDimitry Andric #endif
257c14a5a88SDimitry Andric
2580b57cec5SDimitry Andric // Register _lldb as a built-in module.
2590b57cec5SDimitry Andric PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
2600b57cec5SDimitry Andric
2610b57cec5SDimitry Andric // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
2620b57cec5SDimitry Andric // calling `Py_Initialize` and `PyEval_InitThreads`. < 3.2 requires that you
2630b57cec5SDimitry Andric // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
2640b57cec5SDimitry Andric #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
2650b57cec5SDimitry Andric Py_InitializeEx(0);
2660b57cec5SDimitry Andric InitializeThreadsPrivate();
2670b57cec5SDimitry Andric #else
2680b57cec5SDimitry Andric InitializeThreadsPrivate();
2690b57cec5SDimitry Andric Py_InitializeEx(0);
2700b57cec5SDimitry Andric #endif
2710b57cec5SDimitry Andric }
2720b57cec5SDimitry Andric
~InitializePythonRAII__anoneceaca260111::InitializePythonRAII2730b57cec5SDimitry Andric ~InitializePythonRAII() {
2740b57cec5SDimitry Andric if (m_was_already_initialized) {
2750b57cec5SDimitry Andric Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
2760b57cec5SDimitry Andric LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
2770b57cec5SDimitry Andric m_gil_state == PyGILState_UNLOCKED ? "un" : "");
2780b57cec5SDimitry Andric PyGILState_Release(m_gil_state);
2790b57cec5SDimitry Andric } else {
2800b57cec5SDimitry Andric // We initialized the threads in this function, just unlock the GIL.
2810b57cec5SDimitry Andric PyEval_SaveThread();
2820b57cec5SDimitry Andric }
2830b57cec5SDimitry Andric }
2840b57cec5SDimitry Andric
2850b57cec5SDimitry Andric private:
InitializePythonHome__anoneceaca260111::InitializePythonRAII2860b57cec5SDimitry Andric void InitializePythonHome() {
2875ffd83dbSDimitry Andric #if LLDB_EMBED_PYTHON_HOME
2885ffd83dbSDimitry Andric #if PY_MAJOR_VERSION >= 3
2895ffd83dbSDimitry Andric typedef wchar_t* str_type;
2905ffd83dbSDimitry Andric #else
2915ffd83dbSDimitry Andric typedef char* str_type;
2925ffd83dbSDimitry Andric #endif
2935ffd83dbSDimitry Andric static str_type g_python_home = []() -> str_type {
2945ffd83dbSDimitry Andric const char *lldb_python_home = LLDB_PYTHON_HOME;
2955ffd83dbSDimitry Andric const char *absolute_python_home = nullptr;
2965ffd83dbSDimitry Andric llvm::SmallString<64> path;
2975ffd83dbSDimitry Andric if (llvm::sys::path::is_absolute(lldb_python_home)) {
2985ffd83dbSDimitry Andric absolute_python_home = lldb_python_home;
2995ffd83dbSDimitry Andric } else {
3005ffd83dbSDimitry Andric FileSpec spec = HostInfo::GetShlibDir();
3015ffd83dbSDimitry Andric if (!spec)
3025ffd83dbSDimitry Andric return nullptr;
3035ffd83dbSDimitry Andric spec.GetPath(path);
3045ffd83dbSDimitry Andric llvm::sys::path::append(path, lldb_python_home);
3055ffd83dbSDimitry Andric absolute_python_home = path.c_str();
3065ffd83dbSDimitry Andric }
3070b57cec5SDimitry Andric #if PY_MAJOR_VERSION >= 3
3080b57cec5SDimitry Andric size_t size = 0;
3095ffd83dbSDimitry Andric return Py_DecodeLocale(absolute_python_home, &size);
3100b57cec5SDimitry Andric #else
3115ffd83dbSDimitry Andric return strdup(absolute_python_home);
3120b57cec5SDimitry Andric #endif
3135ffd83dbSDimitry Andric }();
3145ffd83dbSDimitry Andric if (g_python_home != nullptr) {
3150b57cec5SDimitry Andric Py_SetPythonHome(g_python_home);
3165ffd83dbSDimitry Andric }
3170b57cec5SDimitry Andric #else
3180b57cec5SDimitry Andric #if defined(__APPLE__) && PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION == 7
3190b57cec5SDimitry Andric // For Darwin, the only Python version supported is the one shipped in the
3200b57cec5SDimitry Andric // OS OS and linked with lldb. Other installation of Python may have higher
3210b57cec5SDimitry Andric // priorities in the path, overriding PYTHONHOME and causing
3220b57cec5SDimitry Andric // problems/incompatibilities. In order to avoid confusion, always hardcode
3230b57cec5SDimitry Andric // the PythonHome to be right, as it's not going to change.
3240b57cec5SDimitry Andric static char path[] =
3250b57cec5SDimitry Andric "/System/Library/Frameworks/Python.framework/Versions/2.7";
3260b57cec5SDimitry Andric Py_SetPythonHome(path);
3270b57cec5SDimitry Andric #endif
3280b57cec5SDimitry Andric #endif
3290b57cec5SDimitry Andric }
3300b57cec5SDimitry Andric
InitializeThreadsPrivate__anoneceaca260111::InitializePythonRAII3310b57cec5SDimitry Andric void InitializeThreadsPrivate() {
3320b57cec5SDimitry Andric // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself,
3330b57cec5SDimitry Andric // so there is no way to determine whether the embedded interpreter
3340b57cec5SDimitry Andric // was already initialized by some external code. `PyEval_ThreadsInitialized`
3350b57cec5SDimitry Andric // would always return `true` and `PyGILState_Ensure/Release` flow would be
3360b57cec5SDimitry Andric // executed instead of unlocking GIL with `PyEval_SaveThread`. When
3370b57cec5SDimitry Andric // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock.
3380b57cec5SDimitry Andric #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3)
3390b57cec5SDimitry Andric // The only case we should go further and acquire the GIL: it is unlocked.
3400b57cec5SDimitry Andric if (PyGILState_Check())
3410b57cec5SDimitry Andric return;
3420b57cec5SDimitry Andric #endif
3430b57cec5SDimitry Andric
3440b57cec5SDimitry Andric if (PyEval_ThreadsInitialized()) {
3450b57cec5SDimitry Andric Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
3460b57cec5SDimitry Andric
3470b57cec5SDimitry Andric m_was_already_initialized = true;
3480b57cec5SDimitry Andric m_gil_state = PyGILState_Ensure();
3490b57cec5SDimitry Andric LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n",
3500b57cec5SDimitry Andric m_gil_state == PyGILState_UNLOCKED ? "un" : "");
3510b57cec5SDimitry Andric return;
3520b57cec5SDimitry Andric }
3530b57cec5SDimitry Andric
3540b57cec5SDimitry Andric // InitThreads acquires the GIL if it hasn't been called before.
3550b57cec5SDimitry Andric PyEval_InitThreads();
3560b57cec5SDimitry Andric }
3570b57cec5SDimitry Andric
3580b57cec5SDimitry Andric TerminalState m_stdin_tty_state;
359*5f7ddb14SDimitry Andric PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
360*5f7ddb14SDimitry Andric bool m_was_already_initialized = false;
3610b57cec5SDimitry Andric };
3620b57cec5SDimitry Andric } // namespace
3630b57cec5SDimitry Andric
ComputePythonDirForApple(llvm::SmallVectorImpl<char> & path)3640b57cec5SDimitry Andric void ScriptInterpreterPython::ComputePythonDirForApple(
3650b57cec5SDimitry Andric llvm::SmallVectorImpl<char> &path) {
3660b57cec5SDimitry Andric auto style = llvm::sys::path::Style::posix;
3670b57cec5SDimitry Andric
3680b57cec5SDimitry Andric llvm::StringRef path_ref(path.begin(), path.size());
3690b57cec5SDimitry Andric auto rbegin = llvm::sys::path::rbegin(path_ref, style);
3700b57cec5SDimitry Andric auto rend = llvm::sys::path::rend(path_ref);
3710b57cec5SDimitry Andric auto framework = std::find(rbegin, rend, "LLDB.framework");
3720b57cec5SDimitry Andric if (framework == rend) {
3739dba64beSDimitry Andric ComputePythonDir(path);
3740b57cec5SDimitry Andric return;
3750b57cec5SDimitry Andric }
3760b57cec5SDimitry Andric path.resize(framework - rend);
3770b57cec5SDimitry Andric llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
3780b57cec5SDimitry Andric }
3790b57cec5SDimitry Andric
ComputePythonDir(llvm::SmallVectorImpl<char> & path)3809dba64beSDimitry Andric void ScriptInterpreterPython::ComputePythonDir(
3810b57cec5SDimitry Andric llvm::SmallVectorImpl<char> &path) {
3820b57cec5SDimitry Andric // Build the path by backing out of the lib dir, then building with whatever
3830b57cec5SDimitry Andric // the real python interpreter uses. (e.g. lib for most, lib64 on RHEL
3849dba64beSDimitry Andric // x86_64, or bin on Windows).
3859dba64beSDimitry Andric llvm::sys::path::remove_filename(path);
3869dba64beSDimitry Andric llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
3870b57cec5SDimitry Andric
3889dba64beSDimitry Andric #if defined(_WIN32)
3890b57cec5SDimitry Andric // This will be injected directly through FileSpec.GetDirectory().SetString(),
3900b57cec5SDimitry Andric // so we need to normalize manually.
3910b57cec5SDimitry Andric std::replace(path.begin(), path.end(), '\\', '/');
3929dba64beSDimitry Andric #endif
3930b57cec5SDimitry Andric }
3940b57cec5SDimitry Andric
GetPythonDir()3950b57cec5SDimitry Andric FileSpec ScriptInterpreterPython::GetPythonDir() {
3960b57cec5SDimitry Andric static FileSpec g_spec = []() {
3970b57cec5SDimitry Andric FileSpec spec = HostInfo::GetShlibDir();
3980b57cec5SDimitry Andric if (!spec)
3990b57cec5SDimitry Andric return FileSpec();
4000b57cec5SDimitry Andric llvm::SmallString<64> path;
4010b57cec5SDimitry Andric spec.GetPath(path);
4020b57cec5SDimitry Andric
4030b57cec5SDimitry Andric #if defined(__APPLE__)
4040b57cec5SDimitry Andric ComputePythonDirForApple(path);
4050b57cec5SDimitry Andric #else
4069dba64beSDimitry Andric ComputePythonDir(path);
4070b57cec5SDimitry Andric #endif
4080b57cec5SDimitry Andric spec.GetDirectory().SetString(path);
4090b57cec5SDimitry Andric return spec;
4100b57cec5SDimitry Andric }();
4110b57cec5SDimitry Andric return g_spec;
4120b57cec5SDimitry Andric }
4130b57cec5SDimitry Andric
SharedLibraryDirectoryHelper(FileSpec & this_file)414*5f7ddb14SDimitry Andric void ScriptInterpreterPython::SharedLibraryDirectoryHelper(
415*5f7ddb14SDimitry Andric FileSpec &this_file) {
416*5f7ddb14SDimitry Andric // When we're loaded from python, this_file will point to the file inside the
417*5f7ddb14SDimitry Andric // python package directory. Replace it with the one in the lib directory.
418*5f7ddb14SDimitry Andric #ifdef _WIN32
419*5f7ddb14SDimitry Andric // On windows, we need to manually back out of the python tree, and go into
420*5f7ddb14SDimitry Andric // the bin directory. This is pretty much the inverse of what ComputePythonDir
421*5f7ddb14SDimitry Andric // does.
422*5f7ddb14SDimitry Andric if (this_file.GetFileNameExtension() == ConstString(".pyd")) {
423*5f7ddb14SDimitry Andric this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd
424*5f7ddb14SDimitry Andric this_file.RemoveLastPathComponent(); // lldb
425*5f7ddb14SDimitry Andric llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
426*5f7ddb14SDimitry Andric for (auto it = llvm::sys::path::begin(libdir),
427*5f7ddb14SDimitry Andric end = llvm::sys::path::end(libdir);
428*5f7ddb14SDimitry Andric it != end; ++it)
429*5f7ddb14SDimitry Andric this_file.RemoveLastPathComponent();
430*5f7ddb14SDimitry Andric this_file.AppendPathComponent("bin");
431*5f7ddb14SDimitry Andric this_file.AppendPathComponent("liblldb.dll");
432*5f7ddb14SDimitry Andric }
433*5f7ddb14SDimitry Andric #else
434*5f7ddb14SDimitry Andric // The python file is a symlink, so we can find the real library by resolving
435*5f7ddb14SDimitry Andric // it. We can do this unconditionally.
436*5f7ddb14SDimitry Andric FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
437*5f7ddb14SDimitry Andric #endif
438*5f7ddb14SDimitry Andric }
439*5f7ddb14SDimitry Andric
GetPluginNameStatic()4400b57cec5SDimitry Andric lldb_private::ConstString ScriptInterpreterPython::GetPluginNameStatic() {
4410b57cec5SDimitry Andric static ConstString g_name("script-python");
4420b57cec5SDimitry Andric return g_name;
4430b57cec5SDimitry Andric }
4440b57cec5SDimitry Andric
GetPluginDescriptionStatic()4450b57cec5SDimitry Andric const char *ScriptInterpreterPython::GetPluginDescriptionStatic() {
4460b57cec5SDimitry Andric return "Embedded Python interpreter";
4470b57cec5SDimitry Andric }
4480b57cec5SDimitry Andric
Initialize()4490b57cec5SDimitry Andric void ScriptInterpreterPython::Initialize() {
4500b57cec5SDimitry Andric static llvm::once_flag g_once_flag;
4510b57cec5SDimitry Andric
4520b57cec5SDimitry Andric llvm::call_once(g_once_flag, []() {
4530b57cec5SDimitry Andric PluginManager::RegisterPlugin(GetPluginNameStatic(),
4540b57cec5SDimitry Andric GetPluginDescriptionStatic(),
4550b57cec5SDimitry Andric lldb::eScriptLanguagePython,
4560b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateInstance);
4570b57cec5SDimitry Andric });
4580b57cec5SDimitry Andric }
4590b57cec5SDimitry Andric
Terminate()4600b57cec5SDimitry Andric void ScriptInterpreterPython::Terminate() {}
4610b57cec5SDimitry Andric
Locker(ScriptInterpreterPythonImpl * py_interpreter,uint16_t on_entry,uint16_t on_leave,FileSP in,FileSP out,FileSP err)4620b57cec5SDimitry Andric ScriptInterpreterPythonImpl::Locker::Locker(
4630b57cec5SDimitry Andric ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
4649dba64beSDimitry Andric uint16_t on_leave, FileSP in, FileSP out, FileSP err)
4650b57cec5SDimitry Andric : ScriptInterpreterLocker(),
4660b57cec5SDimitry Andric m_teardown_session((on_leave & TearDownSession) == TearDownSession),
4670b57cec5SDimitry Andric m_python_interpreter(py_interpreter) {
468af732203SDimitry Andric repro::Recorder::PrivateThread();
4690b57cec5SDimitry Andric DoAcquireLock();
4700b57cec5SDimitry Andric if ((on_entry & InitSession) == InitSession) {
4710b57cec5SDimitry Andric if (!DoInitSession(on_entry, in, out, err)) {
4720b57cec5SDimitry Andric // Don't teardown the session if we didn't init it.
4730b57cec5SDimitry Andric m_teardown_session = false;
4740b57cec5SDimitry Andric }
4750b57cec5SDimitry Andric }
4760b57cec5SDimitry Andric }
4770b57cec5SDimitry Andric
DoAcquireLock()4780b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
4790b57cec5SDimitry Andric Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
4800b57cec5SDimitry Andric m_GILState = PyGILState_Ensure();
4810b57cec5SDimitry Andric LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked",
4820b57cec5SDimitry Andric m_GILState == PyGILState_UNLOCKED ? "un" : "");
4830b57cec5SDimitry Andric
4840b57cec5SDimitry Andric // we need to save the thread state when we first start the command because
4850b57cec5SDimitry Andric // we might decide to interrupt it while some action is taking place outside
4860b57cec5SDimitry Andric // of Python (e.g. printing to screen, waiting for the network, ...) in that
4870b57cec5SDimitry Andric // case, _PyThreadState_Current will be NULL - and we would be unable to set
4880b57cec5SDimitry Andric // the asynchronous exception - not a desirable situation
4890b57cec5SDimitry Andric m_python_interpreter->SetThreadState(PyThreadState_Get());
4900b57cec5SDimitry Andric m_python_interpreter->IncrementLockCount();
4910b57cec5SDimitry Andric return true;
4920b57cec5SDimitry Andric }
4930b57cec5SDimitry Andric
DoInitSession(uint16_t on_entry_flags,FileSP in,FileSP out,FileSP err)4940b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
4959dba64beSDimitry Andric FileSP in, FileSP out,
4969dba64beSDimitry Andric FileSP err) {
4970b57cec5SDimitry Andric if (!m_python_interpreter)
4980b57cec5SDimitry Andric return false;
4990b57cec5SDimitry Andric return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
5000b57cec5SDimitry Andric }
5010b57cec5SDimitry Andric
DoFreeLock()5020b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
5030b57cec5SDimitry Andric Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
5040b57cec5SDimitry Andric LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
5050b57cec5SDimitry Andric m_GILState == PyGILState_UNLOCKED ? "un" : "");
5060b57cec5SDimitry Andric PyGILState_Release(m_GILState);
5070b57cec5SDimitry Andric m_python_interpreter->DecrementLockCount();
5080b57cec5SDimitry Andric return true;
5090b57cec5SDimitry Andric }
5100b57cec5SDimitry Andric
DoTearDownSession()5110b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
5120b57cec5SDimitry Andric if (!m_python_interpreter)
5130b57cec5SDimitry Andric return false;
5140b57cec5SDimitry Andric m_python_interpreter->LeaveSession();
5150b57cec5SDimitry Andric return true;
5160b57cec5SDimitry Andric }
5170b57cec5SDimitry Andric
~Locker()5180b57cec5SDimitry Andric ScriptInterpreterPythonImpl::Locker::~Locker() {
5190b57cec5SDimitry Andric if (m_teardown_session)
5200b57cec5SDimitry Andric DoTearDownSession();
5210b57cec5SDimitry Andric DoFreeLock();
5220b57cec5SDimitry Andric }
5230b57cec5SDimitry Andric
ScriptInterpreterPythonImpl(Debugger & debugger)5240b57cec5SDimitry Andric ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger)
5250b57cec5SDimitry Andric : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
5260b57cec5SDimitry Andric m_saved_stderr(), m_main_module(),
5270b57cec5SDimitry Andric m_session_dict(PyInitialValue::Invalid),
5280b57cec5SDimitry Andric m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(),
5290b57cec5SDimitry Andric m_run_one_line_str_global(),
5300b57cec5SDimitry Andric m_dictionary_name(m_debugger.GetInstanceName().AsCString()),
5319dba64beSDimitry Andric m_active_io_handler(eIOHandlerNone), m_session_is_active(false),
5325ffd83dbSDimitry Andric m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
5339dba64beSDimitry Andric m_command_thread_state(nullptr) {
5340b57cec5SDimitry Andric InitializePrivate();
5350b57cec5SDimitry Andric
536*5f7ddb14SDimitry Andric m_scripted_process_interface_up =
537*5f7ddb14SDimitry Andric std::make_unique<ScriptedProcessPythonInterface>(*this);
538*5f7ddb14SDimitry Andric
5390b57cec5SDimitry Andric m_dictionary_name.append("_dict");
5400b57cec5SDimitry Andric StreamString run_string;
5410b57cec5SDimitry Andric run_string.Printf("%s = dict()", m_dictionary_name.c_str());
5420b57cec5SDimitry Andric
5430b57cec5SDimitry Andric Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock);
5440b57cec5SDimitry Andric PyRun_SimpleString(run_string.GetData());
5450b57cec5SDimitry Andric
5460b57cec5SDimitry Andric run_string.Clear();
5470b57cec5SDimitry Andric run_string.Printf(
5480b57cec5SDimitry Andric "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
5490b57cec5SDimitry Andric m_dictionary_name.c_str());
5500b57cec5SDimitry Andric PyRun_SimpleString(run_string.GetData());
5510b57cec5SDimitry Andric
5520b57cec5SDimitry Andric // Reloading modules requires a different syntax in Python 2 and Python 3.
5530b57cec5SDimitry Andric // This provides a consistent syntax no matter what version of Python.
5540b57cec5SDimitry Andric run_string.Clear();
5550b57cec5SDimitry Andric run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')",
5560b57cec5SDimitry Andric m_dictionary_name.c_str());
5570b57cec5SDimitry Andric PyRun_SimpleString(run_string.GetData());
5580b57cec5SDimitry Andric
5590b57cec5SDimitry Andric // WARNING: temporary code that loads Cocoa formatters - this should be done
5600b57cec5SDimitry Andric // on a per-platform basis rather than loading the whole set and letting the
5610b57cec5SDimitry Andric // individual formatter classes exploit APIs to check whether they can/cannot
5620b57cec5SDimitry Andric // do their task
5630b57cec5SDimitry Andric run_string.Clear();
5640b57cec5SDimitry Andric run_string.Printf(
5650b57cec5SDimitry Andric "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')",
5660b57cec5SDimitry Andric m_dictionary_name.c_str());
5670b57cec5SDimitry Andric PyRun_SimpleString(run_string.GetData());
5680b57cec5SDimitry Andric run_string.Clear();
5690b57cec5SDimitry Andric
5700b57cec5SDimitry Andric run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
5710b57cec5SDimitry Andric "lldb.embedded_interpreter import run_python_interpreter; "
5720b57cec5SDimitry Andric "from lldb.embedded_interpreter import run_one_line')",
5730b57cec5SDimitry Andric m_dictionary_name.c_str());
5740b57cec5SDimitry Andric PyRun_SimpleString(run_string.GetData());
5750b57cec5SDimitry Andric run_string.Clear();
5760b57cec5SDimitry Andric
5770b57cec5SDimitry Andric run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
5780b57cec5SDimitry Andric "; pydoc.pager = pydoc.plainpager')",
5790b57cec5SDimitry Andric m_dictionary_name.c_str(), m_debugger.GetID());
5800b57cec5SDimitry Andric PyRun_SimpleString(run_string.GetData());
5810b57cec5SDimitry Andric }
5820b57cec5SDimitry Andric
~ScriptInterpreterPythonImpl()5830b57cec5SDimitry Andric ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
5840b57cec5SDimitry Andric // the session dictionary may hold objects with complex state which means
5850b57cec5SDimitry Andric // that they may need to be torn down with some level of smarts and that, in
5860b57cec5SDimitry Andric // turn, requires a valid thread state force Python to procure itself such a
5870b57cec5SDimitry Andric // thread state, nuke the session dictionary and then release it for others
5880b57cec5SDimitry Andric // to use and proceed with the rest of the shutdown
5890b57cec5SDimitry Andric auto gil_state = PyGILState_Ensure();
5900b57cec5SDimitry Andric m_session_dict.Reset();
5910b57cec5SDimitry Andric PyGILState_Release(gil_state);
5920b57cec5SDimitry Andric }
5930b57cec5SDimitry Andric
GetPluginName()5940b57cec5SDimitry Andric lldb_private::ConstString ScriptInterpreterPythonImpl::GetPluginName() {
5950b57cec5SDimitry Andric return GetPluginNameStatic();
5960b57cec5SDimitry Andric }
5970b57cec5SDimitry Andric
GetPluginVersion()5980b57cec5SDimitry Andric uint32_t ScriptInterpreterPythonImpl::GetPluginVersion() { return 1; }
5990b57cec5SDimitry Andric
IOHandlerActivated(IOHandler & io_handler,bool interactive)6000b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler,
6010b57cec5SDimitry Andric bool interactive) {
6020b57cec5SDimitry Andric const char *instructions = nullptr;
6030b57cec5SDimitry Andric
6040b57cec5SDimitry Andric switch (m_active_io_handler) {
6050b57cec5SDimitry Andric case eIOHandlerNone:
6060b57cec5SDimitry Andric break;
6070b57cec5SDimitry Andric case eIOHandlerBreakpoint:
6080b57cec5SDimitry Andric instructions = R"(Enter your Python command(s). Type 'DONE' to end.
6090b57cec5SDimitry Andric def function (frame, bp_loc, internal_dict):
6100b57cec5SDimitry Andric """frame: the lldb.SBFrame for the location at which you stopped
6110b57cec5SDimitry Andric bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
6120b57cec5SDimitry Andric internal_dict: an LLDB support object not to be used"""
6130b57cec5SDimitry Andric )";
6140b57cec5SDimitry Andric break;
6150b57cec5SDimitry Andric case eIOHandlerWatchpoint:
6160b57cec5SDimitry Andric instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
6170b57cec5SDimitry Andric break;
6180b57cec5SDimitry Andric }
6190b57cec5SDimitry Andric
6200b57cec5SDimitry Andric if (instructions) {
6219dba64beSDimitry Andric StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
6220b57cec5SDimitry Andric if (output_sp && interactive) {
6230b57cec5SDimitry Andric output_sp->PutCString(instructions);
6240b57cec5SDimitry Andric output_sp->Flush();
6250b57cec5SDimitry Andric }
6260b57cec5SDimitry Andric }
6270b57cec5SDimitry Andric }
6280b57cec5SDimitry Andric
IOHandlerInputComplete(IOHandler & io_handler,std::string & data)6290b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler,
6300b57cec5SDimitry Andric std::string &data) {
6310b57cec5SDimitry Andric io_handler.SetIsDone(true);
6320b57cec5SDimitry Andric bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
6330b57cec5SDimitry Andric
6340b57cec5SDimitry Andric switch (m_active_io_handler) {
6350b57cec5SDimitry Andric case eIOHandlerNone:
6360b57cec5SDimitry Andric break;
6370b57cec5SDimitry Andric case eIOHandlerBreakpoint: {
638*5f7ddb14SDimitry Andric std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
639*5f7ddb14SDimitry Andric (std::vector<std::reference_wrapper<BreakpointOptions>> *)
640*5f7ddb14SDimitry Andric io_handler.GetUserData();
641*5f7ddb14SDimitry Andric for (BreakpointOptions &bp_options : *bp_options_vec) {
6420b57cec5SDimitry Andric
6439dba64beSDimitry Andric auto data_up = std::make_unique<CommandDataPython>();
6440b57cec5SDimitry Andric if (!data_up)
6450b57cec5SDimitry Andric break;
6460b57cec5SDimitry Andric data_up->user_source.SplitIntoLines(data);
6470b57cec5SDimitry Andric
648480093f4SDimitry Andric StructuredData::ObjectSP empty_args_sp;
6490b57cec5SDimitry Andric if (GenerateBreakpointCommandCallbackData(data_up->user_source,
650480093f4SDimitry Andric data_up->script_source,
651480093f4SDimitry Andric false)
6520b57cec5SDimitry Andric .Success()) {
6530b57cec5SDimitry Andric auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
6540b57cec5SDimitry Andric std::move(data_up));
655*5f7ddb14SDimitry Andric bp_options.SetCallback(
6560b57cec5SDimitry Andric ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
6570b57cec5SDimitry Andric } else if (!batch_mode) {
6589dba64beSDimitry Andric StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
6590b57cec5SDimitry Andric if (error_sp) {
6600b57cec5SDimitry Andric error_sp->Printf("Warning: No command attached to breakpoint.\n");
6610b57cec5SDimitry Andric error_sp->Flush();
6620b57cec5SDimitry Andric }
6630b57cec5SDimitry Andric }
6640b57cec5SDimitry Andric }
6650b57cec5SDimitry Andric m_active_io_handler = eIOHandlerNone;
6660b57cec5SDimitry Andric } break;
6670b57cec5SDimitry Andric case eIOHandlerWatchpoint: {
6680b57cec5SDimitry Andric WatchpointOptions *wp_options =
6690b57cec5SDimitry Andric (WatchpointOptions *)io_handler.GetUserData();
6709dba64beSDimitry Andric auto data_up = std::make_unique<WatchpointOptions::CommandData>();
6710b57cec5SDimitry Andric data_up->user_source.SplitIntoLines(data);
6720b57cec5SDimitry Andric
6730b57cec5SDimitry Andric if (GenerateWatchpointCommandCallbackData(data_up->user_source,
6740b57cec5SDimitry Andric data_up->script_source)) {
6750b57cec5SDimitry Andric auto baton_sp =
6760b57cec5SDimitry Andric std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
6770b57cec5SDimitry Andric wp_options->SetCallback(
6780b57cec5SDimitry Andric ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
6790b57cec5SDimitry Andric } else if (!batch_mode) {
6809dba64beSDimitry Andric StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
6810b57cec5SDimitry Andric if (error_sp) {
6820b57cec5SDimitry Andric error_sp->Printf("Warning: No command attached to breakpoint.\n");
6830b57cec5SDimitry Andric error_sp->Flush();
6840b57cec5SDimitry Andric }
6850b57cec5SDimitry Andric }
6860b57cec5SDimitry Andric m_active_io_handler = eIOHandlerNone;
6870b57cec5SDimitry Andric } break;
6880b57cec5SDimitry Andric }
6890b57cec5SDimitry Andric }
6900b57cec5SDimitry Andric
6910b57cec5SDimitry Andric lldb::ScriptInterpreterSP
CreateInstance(Debugger & debugger)6920b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) {
6930b57cec5SDimitry Andric return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
6940b57cec5SDimitry Andric }
6950b57cec5SDimitry Andric
LeaveSession()6960b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::LeaveSession() {
6970b57cec5SDimitry Andric Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
6980b57cec5SDimitry Andric if (log)
6990b57cec5SDimitry Andric log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
7000b57cec5SDimitry Andric
7019dba64beSDimitry Andric // Unset the LLDB global variables.
7029dba64beSDimitry Andric PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
7039dba64beSDimitry Andric "= None; lldb.thread = None; lldb.frame = None");
7049dba64beSDimitry Andric
7050b57cec5SDimitry Andric // checking that we have a valid thread state - since we use our own
7060b57cec5SDimitry Andric // threading and locking in some (rare) cases during cleanup Python may end
7070b57cec5SDimitry Andric // up believing we have no thread state and PyImport_AddModule will crash if
7080b57cec5SDimitry Andric // that is the case - since that seems to only happen when destroying the
7090b57cec5SDimitry Andric // SBDebugger, we can make do without clearing up stdout and stderr
7100b57cec5SDimitry Andric
7110b57cec5SDimitry Andric // rdar://problem/11292882
7120b57cec5SDimitry Andric // When the current thread state is NULL, PyThreadState_Get() issues a fatal
7130b57cec5SDimitry Andric // error.
7140b57cec5SDimitry Andric if (PyThreadState_GetDict()) {
7150b57cec5SDimitry Andric PythonDictionary &sys_module_dict = GetSysModuleDictionary();
7160b57cec5SDimitry Andric if (sys_module_dict.IsValid()) {
7170b57cec5SDimitry Andric if (m_saved_stdin.IsValid()) {
7180b57cec5SDimitry Andric sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
7190b57cec5SDimitry Andric m_saved_stdin.Reset();
7200b57cec5SDimitry Andric }
7210b57cec5SDimitry Andric if (m_saved_stdout.IsValid()) {
7220b57cec5SDimitry Andric sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
7230b57cec5SDimitry Andric m_saved_stdout.Reset();
7240b57cec5SDimitry Andric }
7250b57cec5SDimitry Andric if (m_saved_stderr.IsValid()) {
7260b57cec5SDimitry Andric sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
7270b57cec5SDimitry Andric m_saved_stderr.Reset();
7280b57cec5SDimitry Andric }
7290b57cec5SDimitry Andric }
7300b57cec5SDimitry Andric }
7310b57cec5SDimitry Andric
7320b57cec5SDimitry Andric m_session_is_active = false;
7330b57cec5SDimitry Andric }
7340b57cec5SDimitry Andric
SetStdHandle(FileSP file_sp,const char * py_name,PythonObject & save_file,const char * mode)7359dba64beSDimitry Andric bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp,
7369dba64beSDimitry Andric const char *py_name,
7379dba64beSDimitry Andric PythonObject &save_file,
7380b57cec5SDimitry Andric const char *mode) {
7399dba64beSDimitry Andric if (!file_sp || !*file_sp) {
7409dba64beSDimitry Andric save_file.Reset();
7419dba64beSDimitry Andric return false;
7429dba64beSDimitry Andric }
7439dba64beSDimitry Andric File &file = *file_sp;
7449dba64beSDimitry Andric
7450b57cec5SDimitry Andric // Flush the file before giving it to python to avoid interleaved output.
7460b57cec5SDimitry Andric file.Flush();
7470b57cec5SDimitry Andric
7480b57cec5SDimitry Andric PythonDictionary &sys_module_dict = GetSysModuleDictionary();
7490b57cec5SDimitry Andric
7509dba64beSDimitry Andric auto new_file = PythonFile::FromFile(file, mode);
7519dba64beSDimitry Andric if (!new_file) {
7529dba64beSDimitry Andric llvm::consumeError(new_file.takeError());
7530b57cec5SDimitry Andric return false;
7540b57cec5SDimitry Andric }
7550b57cec5SDimitry Andric
7569dba64beSDimitry Andric save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
7579dba64beSDimitry Andric
7589dba64beSDimitry Andric sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
7599dba64beSDimitry Andric return true;
7609dba64beSDimitry Andric }
7619dba64beSDimitry Andric
EnterSession(uint16_t on_entry_flags,FileSP in_sp,FileSP out_sp,FileSP err_sp)7620b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
7639dba64beSDimitry Andric FileSP in_sp, FileSP out_sp,
7649dba64beSDimitry Andric FileSP err_sp) {
7650b57cec5SDimitry Andric // If we have already entered the session, without having officially 'left'
7660b57cec5SDimitry Andric // it, then there is no need to 'enter' it again.
7670b57cec5SDimitry Andric Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
7680b57cec5SDimitry Andric if (m_session_is_active) {
7699dba64beSDimitry Andric LLDB_LOGF(
7709dba64beSDimitry Andric log,
7710b57cec5SDimitry Andric "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
7720b57cec5SDimitry Andric ") session is already active, returning without doing anything",
7730b57cec5SDimitry Andric on_entry_flags);
7740b57cec5SDimitry Andric return false;
7750b57cec5SDimitry Andric }
7760b57cec5SDimitry Andric
7779dba64beSDimitry Andric LLDB_LOGF(
7789dba64beSDimitry Andric log,
7799dba64beSDimitry Andric "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
7800b57cec5SDimitry Andric on_entry_flags);
7810b57cec5SDimitry Andric
7820b57cec5SDimitry Andric m_session_is_active = true;
7830b57cec5SDimitry Andric
7840b57cec5SDimitry Andric StreamString run_string;
7850b57cec5SDimitry Andric
7860b57cec5SDimitry Andric if (on_entry_flags & Locker::InitGlobals) {
7870b57cec5SDimitry Andric run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
7880b57cec5SDimitry Andric m_dictionary_name.c_str(), m_debugger.GetID());
7890b57cec5SDimitry Andric run_string.Printf(
7900b57cec5SDimitry Andric "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
7910b57cec5SDimitry Andric m_debugger.GetID());
7920b57cec5SDimitry Andric run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
7930b57cec5SDimitry Andric run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
7940b57cec5SDimitry Andric run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
7950b57cec5SDimitry Andric run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
7960b57cec5SDimitry Andric run_string.PutCString("')");
7970b57cec5SDimitry Andric } else {
7980b57cec5SDimitry Andric // If we aren't initing the globals, we should still always set the
7990b57cec5SDimitry Andric // debugger (since that is always unique.)
8000b57cec5SDimitry Andric run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
8010b57cec5SDimitry Andric m_dictionary_name.c_str(), m_debugger.GetID());
8020b57cec5SDimitry Andric run_string.Printf(
8030b57cec5SDimitry Andric "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
8040b57cec5SDimitry Andric m_debugger.GetID());
8050b57cec5SDimitry Andric run_string.PutCString("')");
8060b57cec5SDimitry Andric }
8070b57cec5SDimitry Andric
8080b57cec5SDimitry Andric PyRun_SimpleString(run_string.GetData());
8090b57cec5SDimitry Andric run_string.Clear();
8100b57cec5SDimitry Andric
8110b57cec5SDimitry Andric PythonDictionary &sys_module_dict = GetSysModuleDictionary();
8120b57cec5SDimitry Andric if (sys_module_dict.IsValid()) {
8139dba64beSDimitry Andric lldb::FileSP top_in_sp;
8149dba64beSDimitry Andric lldb::StreamFileSP top_out_sp, top_err_sp;
8159dba64beSDimitry Andric if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
8169dba64beSDimitry Andric m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
8179dba64beSDimitry Andric top_err_sp);
8180b57cec5SDimitry Andric
8190b57cec5SDimitry Andric if (on_entry_flags & Locker::NoSTDIN) {
8200b57cec5SDimitry Andric m_saved_stdin.Reset();
8210b57cec5SDimitry Andric } else {
8229dba64beSDimitry Andric if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
8239dba64beSDimitry Andric if (top_in_sp)
8249dba64beSDimitry Andric SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
8250b57cec5SDimitry Andric }
8260b57cec5SDimitry Andric }
8270b57cec5SDimitry Andric
8289dba64beSDimitry Andric if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
8299dba64beSDimitry Andric if (top_out_sp)
8309dba64beSDimitry Andric SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w");
8310b57cec5SDimitry Andric }
8320b57cec5SDimitry Andric
8339dba64beSDimitry Andric if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
8349dba64beSDimitry Andric if (top_err_sp)
8359dba64beSDimitry Andric SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w");
8360b57cec5SDimitry Andric }
8370b57cec5SDimitry Andric }
8380b57cec5SDimitry Andric
8390b57cec5SDimitry Andric if (PyErr_Occurred())
8400b57cec5SDimitry Andric PyErr_Clear();
8410b57cec5SDimitry Andric
8420b57cec5SDimitry Andric return true;
8430b57cec5SDimitry Andric }
8440b57cec5SDimitry Andric
GetMainModule()8459dba64beSDimitry Andric PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
8460b57cec5SDimitry Andric if (!m_main_module.IsValid())
8479dba64beSDimitry Andric m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__"));
8480b57cec5SDimitry Andric return m_main_module;
8490b57cec5SDimitry Andric }
8500b57cec5SDimitry Andric
GetSessionDictionary()8510b57cec5SDimitry Andric PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
8520b57cec5SDimitry Andric if (m_session_dict.IsValid())
8530b57cec5SDimitry Andric return m_session_dict;
8540b57cec5SDimitry Andric
8550b57cec5SDimitry Andric PythonObject &main_module = GetMainModule();
8560b57cec5SDimitry Andric if (!main_module.IsValid())
8570b57cec5SDimitry Andric return m_session_dict;
8580b57cec5SDimitry Andric
8590b57cec5SDimitry Andric PythonDictionary main_dict(PyRefType::Borrowed,
8600b57cec5SDimitry Andric PyModule_GetDict(main_module.get()));
8610b57cec5SDimitry Andric if (!main_dict.IsValid())
8620b57cec5SDimitry Andric return m_session_dict;
8630b57cec5SDimitry Andric
8649dba64beSDimitry Andric m_session_dict = unwrapIgnoringErrors(
8659dba64beSDimitry Andric As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
8660b57cec5SDimitry Andric return m_session_dict;
8670b57cec5SDimitry Andric }
8680b57cec5SDimitry Andric
GetSysModuleDictionary()8690b57cec5SDimitry Andric PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
8700b57cec5SDimitry Andric if (m_sys_module_dict.IsValid())
8710b57cec5SDimitry Andric return m_sys_module_dict;
8729dba64beSDimitry Andric PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys"));
8739dba64beSDimitry Andric m_sys_module_dict = sys_module.GetDictionary();
8740b57cec5SDimitry Andric return m_sys_module_dict;
8750b57cec5SDimitry Andric }
8760b57cec5SDimitry Andric
877480093f4SDimitry Andric llvm::Expected<unsigned>
GetMaxPositionalArgumentsForCallable(const llvm::StringRef & callable_name)878480093f4SDimitry Andric ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
879480093f4SDimitry Andric const llvm::StringRef &callable_name) {
880480093f4SDimitry Andric if (callable_name.empty()) {
881480093f4SDimitry Andric return llvm::createStringError(
882480093f4SDimitry Andric llvm::inconvertibleErrorCode(),
883480093f4SDimitry Andric "called with empty callable name.");
884480093f4SDimitry Andric }
885480093f4SDimitry Andric Locker py_lock(this, Locker::AcquireLock |
886480093f4SDimitry Andric Locker::InitSession |
887480093f4SDimitry Andric Locker::NoSTDIN);
888480093f4SDimitry Andric auto dict = PythonModule::MainModule()
889480093f4SDimitry Andric .ResolveName<PythonDictionary>(m_dictionary_name);
890480093f4SDimitry Andric auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
891480093f4SDimitry Andric callable_name, dict);
892480093f4SDimitry Andric if (!pfunc.IsAllocated()) {
893480093f4SDimitry Andric return llvm::createStringError(
894480093f4SDimitry Andric llvm::inconvertibleErrorCode(),
895480093f4SDimitry Andric "can't find callable: %s", callable_name.str().c_str());
896480093f4SDimitry Andric }
897480093f4SDimitry Andric llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
898480093f4SDimitry Andric if (!arg_info)
899480093f4SDimitry Andric return arg_info.takeError();
900480093f4SDimitry Andric return arg_info.get().max_positional_args;
901480093f4SDimitry Andric }
902480093f4SDimitry Andric
GenerateUniqueName(const char * base_name_wanted,uint32_t & functions_counter,const void * name_token=nullptr)9030b57cec5SDimitry Andric static std::string GenerateUniqueName(const char *base_name_wanted,
9040b57cec5SDimitry Andric uint32_t &functions_counter,
9050b57cec5SDimitry Andric const void *name_token = nullptr) {
9060b57cec5SDimitry Andric StreamString sstr;
9070b57cec5SDimitry Andric
9080b57cec5SDimitry Andric if (!base_name_wanted)
9090b57cec5SDimitry Andric return std::string();
9100b57cec5SDimitry Andric
9110b57cec5SDimitry Andric if (!name_token)
9120b57cec5SDimitry Andric sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
9130b57cec5SDimitry Andric else
9140b57cec5SDimitry Andric sstr.Printf("%s_%p", base_name_wanted, name_token);
9150b57cec5SDimitry Andric
9165ffd83dbSDimitry Andric return std::string(sstr.GetString());
9170b57cec5SDimitry Andric }
9180b57cec5SDimitry Andric
GetEmbeddedInterpreterModuleObjects()9190b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
9200b57cec5SDimitry Andric if (m_run_one_line_function.IsValid())
9210b57cec5SDimitry Andric return true;
9220b57cec5SDimitry Andric
9230b57cec5SDimitry Andric PythonObject module(PyRefType::Borrowed,
9240b57cec5SDimitry Andric PyImport_AddModule("lldb.embedded_interpreter"));
9250b57cec5SDimitry Andric if (!module.IsValid())
9260b57cec5SDimitry Andric return false;
9270b57cec5SDimitry Andric
9280b57cec5SDimitry Andric PythonDictionary module_dict(PyRefType::Borrowed,
9290b57cec5SDimitry Andric PyModule_GetDict(module.get()));
9300b57cec5SDimitry Andric if (!module_dict.IsValid())
9310b57cec5SDimitry Andric return false;
9320b57cec5SDimitry Andric
9330b57cec5SDimitry Andric m_run_one_line_function =
9340b57cec5SDimitry Andric module_dict.GetItemForKey(PythonString("run_one_line"));
9350b57cec5SDimitry Andric m_run_one_line_str_global =
9360b57cec5SDimitry Andric module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
9370b57cec5SDimitry Andric return m_run_one_line_function.IsValid();
9380b57cec5SDimitry Andric }
9390b57cec5SDimitry Andric
ExecuteOneLine(llvm::StringRef command,CommandReturnObject * result,const ExecuteScriptOptions & options)9400b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ExecuteOneLine(
9410b57cec5SDimitry Andric llvm::StringRef command, CommandReturnObject *result,
9420b57cec5SDimitry Andric const ExecuteScriptOptions &options) {
9430b57cec5SDimitry Andric std::string command_str = command.str();
9440b57cec5SDimitry Andric
9450b57cec5SDimitry Andric if (!m_valid_session)
9460b57cec5SDimitry Andric return false;
9470b57cec5SDimitry Andric
9480b57cec5SDimitry Andric if (!command.empty()) {
9490b57cec5SDimitry Andric // We want to call run_one_line, passing in the dictionary and the command
9500b57cec5SDimitry Andric // string. We cannot do this through PyRun_SimpleString here because the
9510b57cec5SDimitry Andric // command string may contain escaped characters, and putting it inside
9520b57cec5SDimitry Andric // another string to pass to PyRun_SimpleString messes up the escaping. So
9530b57cec5SDimitry Andric // we use the following more complicated method to pass the command string
9540b57cec5SDimitry Andric // directly down to Python.
9555ffd83dbSDimitry Andric llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
9565ffd83dbSDimitry Andric io_redirect_or_error = ScriptInterpreterIORedirect::Create(
9575ffd83dbSDimitry Andric options.GetEnableIO(), m_debugger, result);
9585ffd83dbSDimitry Andric if (!io_redirect_or_error) {
9595ffd83dbSDimitry Andric if (result)
9605ffd83dbSDimitry Andric result->AppendErrorWithFormatv(
9615ffd83dbSDimitry Andric "failed to redirect I/O: {0}\n",
9625ffd83dbSDimitry Andric llvm::fmt_consume(io_redirect_or_error.takeError()));
9635ffd83dbSDimitry Andric else
9645ffd83dbSDimitry Andric llvm::consumeError(io_redirect_or_error.takeError());
9659dba64beSDimitry Andric return false;
9669dba64beSDimitry Andric }
9675ffd83dbSDimitry Andric
9685ffd83dbSDimitry Andric ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
9690b57cec5SDimitry Andric
9700b57cec5SDimitry Andric bool success = false;
9710b57cec5SDimitry Andric {
9720b57cec5SDimitry Andric // WARNING! It's imperative that this RAII scope be as tight as
9730b57cec5SDimitry Andric // possible. In particular, the scope must end *before* we try to join
9740b57cec5SDimitry Andric // the read thread. The reason for this is that a pre-requisite for
9750b57cec5SDimitry Andric // joining the read thread is that we close the write handle (to break
9760b57cec5SDimitry Andric // the pipe and cause it to wake up and exit). But acquiring the GIL as
9770b57cec5SDimitry Andric // below will redirect Python's stdio to use this same handle. If we
9780b57cec5SDimitry Andric // close the handle while Python is still using it, bad things will
9790b57cec5SDimitry Andric // happen.
9800b57cec5SDimitry Andric Locker locker(
9810b57cec5SDimitry Andric this,
9820b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession |
9830b57cec5SDimitry Andric (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
9840b57cec5SDimitry Andric ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
9855ffd83dbSDimitry Andric Locker::FreeAcquiredLock | Locker::TearDownSession,
9865ffd83dbSDimitry Andric io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
9875ffd83dbSDimitry Andric io_redirect.GetErrorFile());
9880b57cec5SDimitry Andric
9890b57cec5SDimitry Andric // Find the correct script interpreter dictionary in the main module.
9900b57cec5SDimitry Andric PythonDictionary &session_dict = GetSessionDictionary();
9910b57cec5SDimitry Andric if (session_dict.IsValid()) {
9920b57cec5SDimitry Andric if (GetEmbeddedInterpreterModuleObjects()) {
9930b57cec5SDimitry Andric if (PyCallable_Check(m_run_one_line_function.get())) {
9940b57cec5SDimitry Andric PythonObject pargs(
9950b57cec5SDimitry Andric PyRefType::Owned,
9960b57cec5SDimitry Andric Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
9970b57cec5SDimitry Andric if (pargs.IsValid()) {
9980b57cec5SDimitry Andric PythonObject return_value(
9990b57cec5SDimitry Andric PyRefType::Owned,
10000b57cec5SDimitry Andric PyObject_CallObject(m_run_one_line_function.get(),
10010b57cec5SDimitry Andric pargs.get()));
10020b57cec5SDimitry Andric if (return_value.IsValid())
10030b57cec5SDimitry Andric success = true;
10040b57cec5SDimitry Andric else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
10050b57cec5SDimitry Andric PyErr_Print();
10060b57cec5SDimitry Andric PyErr_Clear();
10070b57cec5SDimitry Andric }
10080b57cec5SDimitry Andric }
10090b57cec5SDimitry Andric }
10100b57cec5SDimitry Andric }
10110b57cec5SDimitry Andric }
10120b57cec5SDimitry Andric
10135ffd83dbSDimitry Andric io_redirect.Flush();
10140b57cec5SDimitry Andric }
10150b57cec5SDimitry Andric
10160b57cec5SDimitry Andric if (success)
10170b57cec5SDimitry Andric return true;
10180b57cec5SDimitry Andric
10190b57cec5SDimitry Andric // The one-liner failed. Append the error message.
10200b57cec5SDimitry Andric if (result) {
10210b57cec5SDimitry Andric result->AppendErrorWithFormat(
10220b57cec5SDimitry Andric "python failed attempting to evaluate '%s'\n", command_str.c_str());
10230b57cec5SDimitry Andric }
10240b57cec5SDimitry Andric return false;
10250b57cec5SDimitry Andric }
10260b57cec5SDimitry Andric
10270b57cec5SDimitry Andric if (result)
10280b57cec5SDimitry Andric result->AppendError("empty command passed to python\n");
10290b57cec5SDimitry Andric return false;
10300b57cec5SDimitry Andric }
10310b57cec5SDimitry Andric
ExecuteInterpreterLoop()10320b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
1033af732203SDimitry Andric LLDB_SCOPED_TIMER();
10340b57cec5SDimitry Andric
10350b57cec5SDimitry Andric Debugger &debugger = m_debugger;
10360b57cec5SDimitry Andric
10370b57cec5SDimitry Andric // At the moment, the only time the debugger does not have an input file
10380b57cec5SDimitry Andric // handle is when this is called directly from Python, in which case it is
10390b57cec5SDimitry Andric // both dangerous and unnecessary (not to mention confusing) to try to embed
10400b57cec5SDimitry Andric // a running interpreter loop inside the already running Python interpreter
10410b57cec5SDimitry Andric // loop, so we won't do it.
10420b57cec5SDimitry Andric
10439dba64beSDimitry Andric if (!debugger.GetInputFile().IsValid())
10440b57cec5SDimitry Andric return;
10450b57cec5SDimitry Andric
10460b57cec5SDimitry Andric IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
10470b57cec5SDimitry Andric if (io_handler_sp) {
10485ffd83dbSDimitry Andric debugger.RunIOHandlerAsync(io_handler_sp);
10490b57cec5SDimitry Andric }
10500b57cec5SDimitry Andric }
10510b57cec5SDimitry Andric
Interrupt()10520b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::Interrupt() {
10530b57cec5SDimitry Andric Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
10540b57cec5SDimitry Andric
10550b57cec5SDimitry Andric if (IsExecutingPython()) {
10560b57cec5SDimitry Andric PyThreadState *state = PyThreadState_GET();
10570b57cec5SDimitry Andric if (!state)
10580b57cec5SDimitry Andric state = GetThreadState();
10590b57cec5SDimitry Andric if (state) {
10600b57cec5SDimitry Andric long tid = state->thread_id;
10610b57cec5SDimitry Andric PyThreadState_Swap(state);
10620b57cec5SDimitry Andric int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
10639dba64beSDimitry Andric LLDB_LOGF(log,
10649dba64beSDimitry Andric "ScriptInterpreterPythonImpl::Interrupt() sending "
10650b57cec5SDimitry Andric "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
10660b57cec5SDimitry Andric tid, num_threads);
10670b57cec5SDimitry Andric return true;
10680b57cec5SDimitry Andric }
10690b57cec5SDimitry Andric }
10709dba64beSDimitry Andric LLDB_LOGF(log,
10710b57cec5SDimitry Andric "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
10720b57cec5SDimitry Andric "can't interrupt");
10730b57cec5SDimitry Andric return false;
10740b57cec5SDimitry Andric }
10759dba64beSDimitry Andric
ExecuteOneLineWithReturn(llvm::StringRef in_string,ScriptInterpreter::ScriptReturnType return_type,void * ret_value,const ExecuteScriptOptions & options)10760b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
10770b57cec5SDimitry Andric llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
10780b57cec5SDimitry Andric void *ret_value, const ExecuteScriptOptions &options) {
10790b57cec5SDimitry Andric
1080*5f7ddb14SDimitry Andric llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1081*5f7ddb14SDimitry Andric io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1082*5f7ddb14SDimitry Andric options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1083*5f7ddb14SDimitry Andric
1084*5f7ddb14SDimitry Andric if (!io_redirect_or_error) {
1085*5f7ddb14SDimitry Andric llvm::consumeError(io_redirect_or_error.takeError());
1086*5f7ddb14SDimitry Andric return false;
1087*5f7ddb14SDimitry Andric }
1088*5f7ddb14SDimitry Andric
1089*5f7ddb14SDimitry Andric ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1090*5f7ddb14SDimitry Andric
10910b57cec5SDimitry Andric Locker locker(this,
10920b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession |
10930b57cec5SDimitry Andric (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
10940b57cec5SDimitry Andric Locker::NoSTDIN,
1095*5f7ddb14SDimitry Andric Locker::FreeAcquiredLock | Locker::TearDownSession,
1096*5f7ddb14SDimitry Andric io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1097*5f7ddb14SDimitry Andric io_redirect.GetErrorFile());
10980b57cec5SDimitry Andric
10999dba64beSDimitry Andric PythonModule &main_module = GetMainModule();
11009dba64beSDimitry Andric PythonDictionary globals = main_module.GetDictionary();
11010b57cec5SDimitry Andric
11020b57cec5SDimitry Andric PythonDictionary locals = GetSessionDictionary();
11039dba64beSDimitry Andric if (!locals.IsValid())
11049dba64beSDimitry Andric locals = unwrapIgnoringErrors(
11059dba64beSDimitry Andric As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
11060b57cec5SDimitry Andric if (!locals.IsValid())
11070b57cec5SDimitry Andric locals = globals;
11080b57cec5SDimitry Andric
11099dba64beSDimitry Andric Expected<PythonObject> maybe_py_return =
11109dba64beSDimitry Andric runStringOneLine(in_string, globals, locals);
11110b57cec5SDimitry Andric
11129dba64beSDimitry Andric if (!maybe_py_return) {
11139dba64beSDimitry Andric llvm::handleAllErrors(
11149dba64beSDimitry Andric maybe_py_return.takeError(),
11159dba64beSDimitry Andric [&](PythonException &E) {
11169dba64beSDimitry Andric E.Restore();
11179dba64beSDimitry Andric if (options.GetMaskoutErrors()) {
11189dba64beSDimitry Andric if (E.Matches(PyExc_SyntaxError)) {
11199dba64beSDimitry Andric PyErr_Print();
11200b57cec5SDimitry Andric }
11219dba64beSDimitry Andric PyErr_Clear();
11229dba64beSDimitry Andric }
11239dba64beSDimitry Andric },
11249dba64beSDimitry Andric [](const llvm::ErrorInfoBase &E) {});
11259dba64beSDimitry Andric return false;
11260b57cec5SDimitry Andric }
11270b57cec5SDimitry Andric
11289dba64beSDimitry Andric PythonObject py_return = std::move(maybe_py_return.get());
11299dba64beSDimitry Andric assert(py_return.IsValid());
11309dba64beSDimitry Andric
11310b57cec5SDimitry Andric switch (return_type) {
11320b57cec5SDimitry Andric case eScriptReturnTypeCharPtr: // "char *"
11330b57cec5SDimitry Andric {
11340b57cec5SDimitry Andric const char format[3] = "s#";
11359dba64beSDimitry Andric return PyArg_Parse(py_return.get(), format, (char **)ret_value);
11360b57cec5SDimitry Andric }
11370b57cec5SDimitry Andric case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
11380b57cec5SDimitry Andric // Py_None
11390b57cec5SDimitry Andric {
11400b57cec5SDimitry Andric const char format[3] = "z";
11419dba64beSDimitry Andric return PyArg_Parse(py_return.get(), format, (char **)ret_value);
11420b57cec5SDimitry Andric }
11430b57cec5SDimitry Andric case eScriptReturnTypeBool: {
11440b57cec5SDimitry Andric const char format[2] = "b";
11459dba64beSDimitry Andric return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
11460b57cec5SDimitry Andric }
11470b57cec5SDimitry Andric case eScriptReturnTypeShortInt: {
11480b57cec5SDimitry Andric const char format[2] = "h";
11499dba64beSDimitry Andric return PyArg_Parse(py_return.get(), format, (short *)ret_value);
11500b57cec5SDimitry Andric }
11510b57cec5SDimitry Andric case eScriptReturnTypeShortIntUnsigned: {
11520b57cec5SDimitry Andric const char format[2] = "H";
11539dba64beSDimitry Andric return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
11540b57cec5SDimitry Andric }
11550b57cec5SDimitry Andric case eScriptReturnTypeInt: {
11560b57cec5SDimitry Andric const char format[2] = "i";
11579dba64beSDimitry Andric return PyArg_Parse(py_return.get(), format, (int *)ret_value);
11580b57cec5SDimitry Andric }
11590b57cec5SDimitry Andric case eScriptReturnTypeIntUnsigned: {
11600b57cec5SDimitry Andric const char format[2] = "I";
11619dba64beSDimitry Andric return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
11620b57cec5SDimitry Andric }
11630b57cec5SDimitry Andric case eScriptReturnTypeLongInt: {
11640b57cec5SDimitry Andric const char format[2] = "l";
11659dba64beSDimitry Andric return PyArg_Parse(py_return.get(), format, (long *)ret_value);
11660b57cec5SDimitry Andric }
11670b57cec5SDimitry Andric case eScriptReturnTypeLongIntUnsigned: {
11680b57cec5SDimitry Andric const char format[2] = "k";
11699dba64beSDimitry Andric return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
11700b57cec5SDimitry Andric }
11710b57cec5SDimitry Andric case eScriptReturnTypeLongLong: {
11720b57cec5SDimitry Andric const char format[2] = "L";
11739dba64beSDimitry Andric return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
11740b57cec5SDimitry Andric }
11750b57cec5SDimitry Andric case eScriptReturnTypeLongLongUnsigned: {
11760b57cec5SDimitry Andric const char format[2] = "K";
11779dba64beSDimitry Andric return PyArg_Parse(py_return.get(), format,
11789dba64beSDimitry Andric (unsigned long long *)ret_value);
11790b57cec5SDimitry Andric }
11800b57cec5SDimitry Andric case eScriptReturnTypeFloat: {
11810b57cec5SDimitry Andric const char format[2] = "f";
11829dba64beSDimitry Andric return PyArg_Parse(py_return.get(), format, (float *)ret_value);
11830b57cec5SDimitry Andric }
11840b57cec5SDimitry Andric case eScriptReturnTypeDouble: {
11850b57cec5SDimitry Andric const char format[2] = "d";
11869dba64beSDimitry Andric return PyArg_Parse(py_return.get(), format, (double *)ret_value);
11870b57cec5SDimitry Andric }
11880b57cec5SDimitry Andric case eScriptReturnTypeChar: {
11890b57cec5SDimitry Andric const char format[2] = "c";
11909dba64beSDimitry Andric return PyArg_Parse(py_return.get(), format, (char *)ret_value);
11910b57cec5SDimitry Andric }
11920b57cec5SDimitry Andric case eScriptReturnTypeOpaqueObject: {
11939dba64beSDimitry Andric *((PyObject **)ret_value) = py_return.release();
11949dba64beSDimitry Andric return true;
11950b57cec5SDimitry Andric }
11960b57cec5SDimitry Andric }
1197480093f4SDimitry Andric llvm_unreachable("Fully covered switch!");
11980b57cec5SDimitry Andric }
11990b57cec5SDimitry Andric
ExecuteMultipleLines(const char * in_string,const ExecuteScriptOptions & options)12000b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
12010b57cec5SDimitry Andric const char *in_string, const ExecuteScriptOptions &options) {
12029dba64beSDimitry Andric
12039dba64beSDimitry Andric if (in_string == nullptr)
12049dba64beSDimitry Andric return Status();
12050b57cec5SDimitry Andric
1206*5f7ddb14SDimitry Andric llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1207*5f7ddb14SDimitry Andric io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1208*5f7ddb14SDimitry Andric options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1209*5f7ddb14SDimitry Andric
1210*5f7ddb14SDimitry Andric if (!io_redirect_or_error)
1211*5f7ddb14SDimitry Andric return Status(io_redirect_or_error.takeError());
1212*5f7ddb14SDimitry Andric
1213*5f7ddb14SDimitry Andric ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1214*5f7ddb14SDimitry Andric
12150b57cec5SDimitry Andric Locker locker(this,
12160b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession |
12170b57cec5SDimitry Andric (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
12180b57cec5SDimitry Andric Locker::NoSTDIN,
1219*5f7ddb14SDimitry Andric Locker::FreeAcquiredLock | Locker::TearDownSession,
1220*5f7ddb14SDimitry Andric io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1221*5f7ddb14SDimitry Andric io_redirect.GetErrorFile());
12220b57cec5SDimitry Andric
12239dba64beSDimitry Andric PythonModule &main_module = GetMainModule();
12249dba64beSDimitry Andric PythonDictionary globals = main_module.GetDictionary();
12250b57cec5SDimitry Andric
12260b57cec5SDimitry Andric PythonDictionary locals = GetSessionDictionary();
12270b57cec5SDimitry Andric if (!locals.IsValid())
12289dba64beSDimitry Andric locals = unwrapIgnoringErrors(
12299dba64beSDimitry Andric As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
12300b57cec5SDimitry Andric if (!locals.IsValid())
12310b57cec5SDimitry Andric locals = globals;
12320b57cec5SDimitry Andric
12339dba64beSDimitry Andric Expected<PythonObject> return_value =
12349dba64beSDimitry Andric runStringMultiLine(in_string, globals, locals);
12350b57cec5SDimitry Andric
12369dba64beSDimitry Andric if (!return_value) {
12379dba64beSDimitry Andric llvm::Error error =
12389dba64beSDimitry Andric llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
12399dba64beSDimitry Andric llvm::Error error = llvm::createStringError(
12409dba64beSDimitry Andric llvm::inconvertibleErrorCode(), E.ReadBacktrace());
12419dba64beSDimitry Andric if (!options.GetMaskoutErrors())
12429dba64beSDimitry Andric E.Restore();
12430b57cec5SDimitry Andric return error;
12449dba64beSDimitry Andric });
12459dba64beSDimitry Andric return Status(std::move(error));
12469dba64beSDimitry Andric }
12479dba64beSDimitry Andric
12489dba64beSDimitry Andric return Status();
12490b57cec5SDimitry Andric }
12500b57cec5SDimitry Andric
CollectDataForBreakpointCommandCallback(std::vector<std::reference_wrapper<BreakpointOptions>> & bp_options_vec,CommandReturnObject & result)12510b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1252*5f7ddb14SDimitry Andric std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
12530b57cec5SDimitry Andric CommandReturnObject &result) {
12540b57cec5SDimitry Andric m_active_io_handler = eIOHandlerBreakpoint;
12550b57cec5SDimitry Andric m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1256480093f4SDimitry Andric " ", *this, &bp_options_vec);
12570b57cec5SDimitry Andric }
12580b57cec5SDimitry Andric
CollectDataForWatchpointCommandCallback(WatchpointOptions * wp_options,CommandReturnObject & result)12590b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
12600b57cec5SDimitry Andric WatchpointOptions *wp_options, CommandReturnObject &result) {
12610b57cec5SDimitry Andric m_active_io_handler = eIOHandlerWatchpoint;
12620b57cec5SDimitry Andric m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1263480093f4SDimitry Andric " ", *this, wp_options);
12640b57cec5SDimitry Andric }
12650b57cec5SDimitry Andric
SetBreakpointCommandCallbackFunction(BreakpointOptions & bp_options,const char * function_name,StructuredData::ObjectSP extra_args_sp)1266480093f4SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1267*5f7ddb14SDimitry Andric BreakpointOptions &bp_options, const char *function_name,
1268480093f4SDimitry Andric StructuredData::ObjectSP extra_args_sp) {
1269480093f4SDimitry Andric Status error;
12700b57cec5SDimitry Andric // For now just cons up a oneliner that calls the provided function.
12710b57cec5SDimitry Andric std::string oneliner("return ");
12720b57cec5SDimitry Andric oneliner += function_name;
1273480093f4SDimitry Andric
1274480093f4SDimitry Andric llvm::Expected<unsigned> maybe_args =
1275480093f4SDimitry Andric GetMaxPositionalArgumentsForCallable(function_name);
1276480093f4SDimitry Andric if (!maybe_args) {
1277480093f4SDimitry Andric error.SetErrorStringWithFormat(
1278480093f4SDimitry Andric "could not get num args: %s",
1279480093f4SDimitry Andric llvm::toString(maybe_args.takeError()).c_str());
1280480093f4SDimitry Andric return error;
1281480093f4SDimitry Andric }
1282480093f4SDimitry Andric size_t max_args = *maybe_args;
1283480093f4SDimitry Andric
1284480093f4SDimitry Andric bool uses_extra_args = false;
1285480093f4SDimitry Andric if (max_args >= 4) {
1286480093f4SDimitry Andric uses_extra_args = true;
1287480093f4SDimitry Andric oneliner += "(frame, bp_loc, extra_args, internal_dict)";
1288480093f4SDimitry Andric } else if (max_args >= 3) {
1289480093f4SDimitry Andric if (extra_args_sp) {
1290480093f4SDimitry Andric error.SetErrorString("cannot pass extra_args to a three argument callback"
1291480093f4SDimitry Andric );
1292480093f4SDimitry Andric return error;
1293480093f4SDimitry Andric }
1294480093f4SDimitry Andric uses_extra_args = false;
12950b57cec5SDimitry Andric oneliner += "(frame, bp_loc, internal_dict)";
1296480093f4SDimitry Andric } else {
1297480093f4SDimitry Andric error.SetErrorStringWithFormat("expected 3 or 4 argument "
1298480093f4SDimitry Andric "function, %s can only take %zu",
1299480093f4SDimitry Andric function_name, max_args);
1300480093f4SDimitry Andric return error;
1301480093f4SDimitry Andric }
1302480093f4SDimitry Andric
1303480093f4SDimitry Andric SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp,
1304480093f4SDimitry Andric uses_extra_args);
1305480093f4SDimitry Andric return error;
13060b57cec5SDimitry Andric }
13070b57cec5SDimitry Andric
SetBreakpointCommandCallback(BreakpointOptions & bp_options,std::unique_ptr<BreakpointOptions::CommandData> & cmd_data_up)13080b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1309*5f7ddb14SDimitry Andric BreakpointOptions &bp_options,
13100b57cec5SDimitry Andric std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
13110b57cec5SDimitry Andric Status error;
13120b57cec5SDimitry Andric error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1313480093f4SDimitry Andric cmd_data_up->script_source,
1314480093f4SDimitry Andric false);
13150b57cec5SDimitry Andric if (error.Fail()) {
13160b57cec5SDimitry Andric return error;
13170b57cec5SDimitry Andric }
13180b57cec5SDimitry Andric auto baton_sp =
13190b57cec5SDimitry Andric std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1320*5f7ddb14SDimitry Andric bp_options.SetCallback(
13210b57cec5SDimitry Andric ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
13220b57cec5SDimitry Andric return error;
13230b57cec5SDimitry Andric }
13240b57cec5SDimitry Andric
SetBreakpointCommandCallback(BreakpointOptions & bp_options,const char * command_body_text)13250b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1326*5f7ddb14SDimitry Andric BreakpointOptions &bp_options, const char *command_body_text) {
1327480093f4SDimitry Andric return SetBreakpointCommandCallback(bp_options, command_body_text, {},false);
1328480093f4SDimitry Andric }
13290b57cec5SDimitry Andric
1330480093f4SDimitry Andric // Set a Python one-liner as the callback for the breakpoint.
SetBreakpointCommandCallback(BreakpointOptions & bp_options,const char * command_body_text,StructuredData::ObjectSP extra_args_sp,bool uses_extra_args)1331480093f4SDimitry Andric Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1332*5f7ddb14SDimitry Andric BreakpointOptions &bp_options, const char *command_body_text,
1333*5f7ddb14SDimitry Andric StructuredData::ObjectSP extra_args_sp, bool uses_extra_args) {
1334480093f4SDimitry Andric auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
13350b57cec5SDimitry Andric // Split the command_body_text into lines, and pass that to
13360b57cec5SDimitry Andric // GenerateBreakpointCommandCallbackData. That will wrap the body in an
13370b57cec5SDimitry Andric // auto-generated function, and return the function name in script_source.
13380b57cec5SDimitry Andric // That is what the callback will actually invoke.
13390b57cec5SDimitry Andric
13400b57cec5SDimitry Andric data_up->user_source.SplitIntoLines(command_body_text);
13410b57cec5SDimitry Andric Status error = GenerateBreakpointCommandCallbackData(data_up->user_source,
1342480093f4SDimitry Andric data_up->script_source,
1343480093f4SDimitry Andric uses_extra_args);
13440b57cec5SDimitry Andric if (error.Success()) {
13450b57cec5SDimitry Andric auto baton_sp =
13460b57cec5SDimitry Andric std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1347*5f7ddb14SDimitry Andric bp_options.SetCallback(
13480b57cec5SDimitry Andric ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
13490b57cec5SDimitry Andric return error;
13505ffd83dbSDimitry Andric }
13510b57cec5SDimitry Andric return error;
13520b57cec5SDimitry Andric }
13530b57cec5SDimitry Andric
13540b57cec5SDimitry Andric // Set a Python one-liner as the callback for the watchpoint.
SetWatchpointCommandCallback(WatchpointOptions * wp_options,const char * oneliner)13550b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
13560b57cec5SDimitry Andric WatchpointOptions *wp_options, const char *oneliner) {
13579dba64beSDimitry Andric auto data_up = std::make_unique<WatchpointOptions::CommandData>();
13580b57cec5SDimitry Andric
13590b57cec5SDimitry Andric // It's necessary to set both user_source and script_source to the oneliner.
13600b57cec5SDimitry Andric // The former is used to generate callback description (as in watchpoint
13610b57cec5SDimitry Andric // command list) while the latter is used for Python to interpret during the
13620b57cec5SDimitry Andric // actual callback.
13630b57cec5SDimitry Andric
13640b57cec5SDimitry Andric data_up->user_source.AppendString(oneliner);
13650b57cec5SDimitry Andric data_up->script_source.assign(oneliner);
13660b57cec5SDimitry Andric
13670b57cec5SDimitry Andric if (GenerateWatchpointCommandCallbackData(data_up->user_source,
13680b57cec5SDimitry Andric data_up->script_source)) {
13690b57cec5SDimitry Andric auto baton_sp =
13700b57cec5SDimitry Andric std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
13710b57cec5SDimitry Andric wp_options->SetCallback(
13720b57cec5SDimitry Andric ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
13730b57cec5SDimitry Andric }
13740b57cec5SDimitry Andric
13750b57cec5SDimitry Andric return;
13760b57cec5SDimitry Andric }
13770b57cec5SDimitry Andric
ExportFunctionDefinitionToInterpreter(StringList & function_def)13780b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
13790b57cec5SDimitry Andric StringList &function_def) {
13800b57cec5SDimitry Andric // Convert StringList to one long, newline delimited, const char *.
13810b57cec5SDimitry Andric std::string function_def_string(function_def.CopyList());
13820b57cec5SDimitry Andric
13830b57cec5SDimitry Andric Status error = ExecuteMultipleLines(
13840b57cec5SDimitry Andric function_def_string.c_str(),
1385*5f7ddb14SDimitry Andric ExecuteScriptOptions().SetEnableIO(false));
13860b57cec5SDimitry Andric return error;
13870b57cec5SDimitry Andric }
13880b57cec5SDimitry Andric
GenerateFunction(const char * signature,const StringList & input)13890b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature,
13900b57cec5SDimitry Andric const StringList &input) {
13910b57cec5SDimitry Andric Status error;
13920b57cec5SDimitry Andric int num_lines = input.GetSize();
13930b57cec5SDimitry Andric if (num_lines == 0) {
13940b57cec5SDimitry Andric error.SetErrorString("No input data.");
13950b57cec5SDimitry Andric return error;
13960b57cec5SDimitry Andric }
13970b57cec5SDimitry Andric
13980b57cec5SDimitry Andric if (!signature || *signature == 0) {
13990b57cec5SDimitry Andric error.SetErrorString("No output function name.");
14000b57cec5SDimitry Andric return error;
14010b57cec5SDimitry Andric }
14020b57cec5SDimitry Andric
14030b57cec5SDimitry Andric StreamString sstr;
14040b57cec5SDimitry Andric StringList auto_generated_function;
14050b57cec5SDimitry Andric auto_generated_function.AppendString(signature);
14060b57cec5SDimitry Andric auto_generated_function.AppendString(
14070b57cec5SDimitry Andric " global_dict = globals()"); // Grab the global dictionary
14080b57cec5SDimitry Andric auto_generated_function.AppendString(
14090b57cec5SDimitry Andric " new_keys = internal_dict.keys()"); // Make a list of keys in the
14100b57cec5SDimitry Andric // session dict
14110b57cec5SDimitry Andric auto_generated_function.AppendString(
14120b57cec5SDimitry Andric " old_keys = global_dict.keys()"); // Save list of keys in global dict
14130b57cec5SDimitry Andric auto_generated_function.AppendString(
14140b57cec5SDimitry Andric " global_dict.update (internal_dict)"); // Add the session dictionary
14150b57cec5SDimitry Andric // to the
14160b57cec5SDimitry Andric // global dictionary.
14170b57cec5SDimitry Andric
14180b57cec5SDimitry Andric // Wrap everything up inside the function, increasing the indentation.
14190b57cec5SDimitry Andric
14200b57cec5SDimitry Andric auto_generated_function.AppendString(" if True:");
14210b57cec5SDimitry Andric for (int i = 0; i < num_lines; ++i) {
14220b57cec5SDimitry Andric sstr.Clear();
14230b57cec5SDimitry Andric sstr.Printf(" %s", input.GetStringAtIndex(i));
14240b57cec5SDimitry Andric auto_generated_function.AppendString(sstr.GetData());
14250b57cec5SDimitry Andric }
14260b57cec5SDimitry Andric auto_generated_function.AppendString(
14270b57cec5SDimitry Andric " for key in new_keys:"); // Iterate over all the keys from session
14280b57cec5SDimitry Andric // dict
14290b57cec5SDimitry Andric auto_generated_function.AppendString(
14300b57cec5SDimitry Andric " internal_dict[key] = global_dict[key]"); // Update session dict
14310b57cec5SDimitry Andric // values
14320b57cec5SDimitry Andric auto_generated_function.AppendString(
14330b57cec5SDimitry Andric " if key not in old_keys:"); // If key was not originally in
14340b57cec5SDimitry Andric // global dict
14350b57cec5SDimitry Andric auto_generated_function.AppendString(
14360b57cec5SDimitry Andric " del global_dict[key]"); // ...then remove key/value from
14370b57cec5SDimitry Andric // global dict
14380b57cec5SDimitry Andric
14390b57cec5SDimitry Andric // Verify that the results are valid Python.
14400b57cec5SDimitry Andric
14410b57cec5SDimitry Andric error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
14420b57cec5SDimitry Andric
14430b57cec5SDimitry Andric return error;
14440b57cec5SDimitry Andric }
14450b57cec5SDimitry Andric
GenerateTypeScriptFunction(StringList & user_input,std::string & output,const void * name_token)14460b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
14470b57cec5SDimitry Andric StringList &user_input, std::string &output, const void *name_token) {
14480b57cec5SDimitry Andric static uint32_t num_created_functions = 0;
14490b57cec5SDimitry Andric user_input.RemoveBlankLines();
14500b57cec5SDimitry Andric StreamString sstr;
14510b57cec5SDimitry Andric
14520b57cec5SDimitry Andric // Check to see if we have any data; if not, just return.
14530b57cec5SDimitry Andric if (user_input.GetSize() == 0)
14540b57cec5SDimitry Andric return false;
14550b57cec5SDimitry Andric
14560b57cec5SDimitry Andric // Take what the user wrote, wrap it all up inside one big auto-generated
14570b57cec5SDimitry Andric // Python function, passing in the ValueObject as parameter to the function.
14580b57cec5SDimitry Andric
14590b57cec5SDimitry Andric std::string auto_generated_function_name(
14600b57cec5SDimitry Andric GenerateUniqueName("lldb_autogen_python_type_print_func",
14610b57cec5SDimitry Andric num_created_functions, name_token));
14620b57cec5SDimitry Andric sstr.Printf("def %s (valobj, internal_dict):",
14630b57cec5SDimitry Andric auto_generated_function_name.c_str());
14640b57cec5SDimitry Andric
14650b57cec5SDimitry Andric if (!GenerateFunction(sstr.GetData(), user_input).Success())
14660b57cec5SDimitry Andric return false;
14670b57cec5SDimitry Andric
14680b57cec5SDimitry Andric // Store the name of the auto-generated function to be called.
14690b57cec5SDimitry Andric output.assign(auto_generated_function_name);
14700b57cec5SDimitry Andric return true;
14710b57cec5SDimitry Andric }
14720b57cec5SDimitry Andric
GenerateScriptAliasFunction(StringList & user_input,std::string & output)14730b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
14740b57cec5SDimitry Andric StringList &user_input, std::string &output) {
14750b57cec5SDimitry Andric static uint32_t num_created_functions = 0;
14760b57cec5SDimitry Andric user_input.RemoveBlankLines();
14770b57cec5SDimitry Andric StreamString sstr;
14780b57cec5SDimitry Andric
14790b57cec5SDimitry Andric // Check to see if we have any data; if not, just return.
14800b57cec5SDimitry Andric if (user_input.GetSize() == 0)
14810b57cec5SDimitry Andric return false;
14820b57cec5SDimitry Andric
14830b57cec5SDimitry Andric std::string auto_generated_function_name(GenerateUniqueName(
14840b57cec5SDimitry Andric "lldb_autogen_python_cmd_alias_func", num_created_functions));
14850b57cec5SDimitry Andric
14860b57cec5SDimitry Andric sstr.Printf("def %s (debugger, args, result, internal_dict):",
14870b57cec5SDimitry Andric auto_generated_function_name.c_str());
14880b57cec5SDimitry Andric
14890b57cec5SDimitry Andric if (!GenerateFunction(sstr.GetData(), user_input).Success())
14900b57cec5SDimitry Andric return false;
14910b57cec5SDimitry Andric
14920b57cec5SDimitry Andric // Store the name of the auto-generated function to be called.
14930b57cec5SDimitry Andric output.assign(auto_generated_function_name);
14940b57cec5SDimitry Andric return true;
14950b57cec5SDimitry Andric }
14960b57cec5SDimitry Andric
GenerateTypeSynthClass(StringList & user_input,std::string & output,const void * name_token)14970b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
14980b57cec5SDimitry Andric StringList &user_input, std::string &output, const void *name_token) {
14990b57cec5SDimitry Andric static uint32_t num_created_classes = 0;
15000b57cec5SDimitry Andric user_input.RemoveBlankLines();
15010b57cec5SDimitry Andric int num_lines = user_input.GetSize();
15020b57cec5SDimitry Andric StreamString sstr;
15030b57cec5SDimitry Andric
15040b57cec5SDimitry Andric // Check to see if we have any data; if not, just return.
15050b57cec5SDimitry Andric if (user_input.GetSize() == 0)
15060b57cec5SDimitry Andric return false;
15070b57cec5SDimitry Andric
15080b57cec5SDimitry Andric // Wrap all user input into a Python class
15090b57cec5SDimitry Andric
15100b57cec5SDimitry Andric std::string auto_generated_class_name(GenerateUniqueName(
15110b57cec5SDimitry Andric "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
15120b57cec5SDimitry Andric
15130b57cec5SDimitry Andric StringList auto_generated_class;
15140b57cec5SDimitry Andric
15150b57cec5SDimitry Andric // Create the function name & definition string.
15160b57cec5SDimitry Andric
15170b57cec5SDimitry Andric sstr.Printf("class %s:", auto_generated_class_name.c_str());
15180b57cec5SDimitry Andric auto_generated_class.AppendString(sstr.GetString());
15190b57cec5SDimitry Andric
15200b57cec5SDimitry Andric // Wrap everything up inside the class, increasing the indentation. we don't
15210b57cec5SDimitry Andric // need to play any fancy indentation tricks here because there is no
15220b57cec5SDimitry Andric // surrounding code whose indentation we need to honor
15230b57cec5SDimitry Andric for (int i = 0; i < num_lines; ++i) {
15240b57cec5SDimitry Andric sstr.Clear();
15250b57cec5SDimitry Andric sstr.Printf(" %s", user_input.GetStringAtIndex(i));
15260b57cec5SDimitry Andric auto_generated_class.AppendString(sstr.GetString());
15270b57cec5SDimitry Andric }
15280b57cec5SDimitry Andric
15290b57cec5SDimitry Andric // Verify that the results are valid Python. (even though the method is
15300b57cec5SDimitry Andric // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
15310b57cec5SDimitry Andric // (TODO: rename that method to ExportDefinitionToInterpreter)
15320b57cec5SDimitry Andric if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
15330b57cec5SDimitry Andric return false;
15340b57cec5SDimitry Andric
15350b57cec5SDimitry Andric // Store the name of the auto-generated class
15360b57cec5SDimitry Andric
15370b57cec5SDimitry Andric output.assign(auto_generated_class_name);
15380b57cec5SDimitry Andric return true;
15390b57cec5SDimitry Andric }
15400b57cec5SDimitry Andric
15410b57cec5SDimitry Andric StructuredData::GenericSP
CreateFrameRecognizer(const char * class_name)15420b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
15430b57cec5SDimitry Andric if (class_name == nullptr || class_name[0] == '\0')
15440b57cec5SDimitry Andric return StructuredData::GenericSP();
15450b57cec5SDimitry Andric
15460b57cec5SDimitry Andric void *ret_val;
15470b57cec5SDimitry Andric
15480b57cec5SDimitry Andric {
15490b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
15500b57cec5SDimitry Andric Locker::FreeLock);
15510b57cec5SDimitry Andric ret_val = LLDBSWIGPython_CreateFrameRecognizer(class_name,
15520b57cec5SDimitry Andric m_dictionary_name.c_str());
15530b57cec5SDimitry Andric }
15540b57cec5SDimitry Andric
15550b57cec5SDimitry Andric return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
15560b57cec5SDimitry Andric }
15570b57cec5SDimitry Andric
GetRecognizedArguments(const StructuredData::ObjectSP & os_plugin_object_sp,lldb::StackFrameSP frame_sp)15580b57cec5SDimitry Andric lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
15590b57cec5SDimitry Andric const StructuredData::ObjectSP &os_plugin_object_sp,
15600b57cec5SDimitry Andric lldb::StackFrameSP frame_sp) {
15610b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
15620b57cec5SDimitry Andric
15630b57cec5SDimitry Andric if (!os_plugin_object_sp)
15640b57cec5SDimitry Andric return ValueObjectListSP();
15650b57cec5SDimitry Andric
15660b57cec5SDimitry Andric StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
15670b57cec5SDimitry Andric if (!generic)
15680b57cec5SDimitry Andric return nullptr;
15690b57cec5SDimitry Andric
15700b57cec5SDimitry Andric PythonObject implementor(PyRefType::Borrowed,
15710b57cec5SDimitry Andric (PyObject *)generic->GetValue());
15720b57cec5SDimitry Andric
15730b57cec5SDimitry Andric if (!implementor.IsAllocated())
15740b57cec5SDimitry Andric return ValueObjectListSP();
15750b57cec5SDimitry Andric
15760b57cec5SDimitry Andric PythonObject py_return(PyRefType::Owned,
15770b57cec5SDimitry Andric (PyObject *)LLDBSwigPython_GetRecognizedArguments(
15780b57cec5SDimitry Andric implementor.get(), frame_sp));
15790b57cec5SDimitry Andric
15800b57cec5SDimitry Andric // if it fails, print the error but otherwise go on
15810b57cec5SDimitry Andric if (PyErr_Occurred()) {
15820b57cec5SDimitry Andric PyErr_Print();
15830b57cec5SDimitry Andric PyErr_Clear();
15840b57cec5SDimitry Andric }
15850b57cec5SDimitry Andric if (py_return.get()) {
15860b57cec5SDimitry Andric PythonList result_list(PyRefType::Borrowed, py_return.get());
15870b57cec5SDimitry Andric ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
15880b57cec5SDimitry Andric for (size_t i = 0; i < result_list.GetSize(); i++) {
15890b57cec5SDimitry Andric PyObject *item = result_list.GetItemAtIndex(i).get();
15900b57cec5SDimitry Andric lldb::SBValue *sb_value_ptr =
15910b57cec5SDimitry Andric (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
15920b57cec5SDimitry Andric auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
15930b57cec5SDimitry Andric if (valobj_sp)
15940b57cec5SDimitry Andric result->Append(valobj_sp);
15950b57cec5SDimitry Andric }
15960b57cec5SDimitry Andric return result;
15970b57cec5SDimitry Andric }
15980b57cec5SDimitry Andric return ValueObjectListSP();
15990b57cec5SDimitry Andric }
16000b57cec5SDimitry Andric
16010b57cec5SDimitry Andric StructuredData::GenericSP
OSPlugin_CreatePluginObject(const char * class_name,lldb::ProcessSP process_sp)16020b57cec5SDimitry Andric ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject(
16030b57cec5SDimitry Andric const char *class_name, lldb::ProcessSP process_sp) {
16040b57cec5SDimitry Andric if (class_name == nullptr || class_name[0] == '\0')
16050b57cec5SDimitry Andric return StructuredData::GenericSP();
16060b57cec5SDimitry Andric
16070b57cec5SDimitry Andric if (!process_sp)
16080b57cec5SDimitry Andric return StructuredData::GenericSP();
16090b57cec5SDimitry Andric
16100b57cec5SDimitry Andric void *ret_val;
16110b57cec5SDimitry Andric
16120b57cec5SDimitry Andric {
16130b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
16140b57cec5SDimitry Andric Locker::FreeLock);
16150b57cec5SDimitry Andric ret_val = LLDBSWIGPythonCreateOSPlugin(
16160b57cec5SDimitry Andric class_name, m_dictionary_name.c_str(), process_sp);
16170b57cec5SDimitry Andric }
16180b57cec5SDimitry Andric
16190b57cec5SDimitry Andric return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
16200b57cec5SDimitry Andric }
16210b57cec5SDimitry Andric
OSPlugin_RegisterInfo(StructuredData::ObjectSP os_plugin_object_sp)16220b57cec5SDimitry Andric StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo(
16230b57cec5SDimitry Andric StructuredData::ObjectSP os_plugin_object_sp) {
16240b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
16250b57cec5SDimitry Andric
16260b57cec5SDimitry Andric static char callee_name[] = "get_register_info";
16270b57cec5SDimitry Andric
16280b57cec5SDimitry Andric if (!os_plugin_object_sp)
16290b57cec5SDimitry Andric return StructuredData::DictionarySP();
16300b57cec5SDimitry Andric
16310b57cec5SDimitry Andric StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
16320b57cec5SDimitry Andric if (!generic)
16330b57cec5SDimitry Andric return nullptr;
16340b57cec5SDimitry Andric
16350b57cec5SDimitry Andric PythonObject implementor(PyRefType::Borrowed,
16360b57cec5SDimitry Andric (PyObject *)generic->GetValue());
16370b57cec5SDimitry Andric
16380b57cec5SDimitry Andric if (!implementor.IsAllocated())
16390b57cec5SDimitry Andric return StructuredData::DictionarySP();
16400b57cec5SDimitry Andric
16410b57cec5SDimitry Andric PythonObject pmeth(PyRefType::Owned,
16420b57cec5SDimitry Andric PyObject_GetAttrString(implementor.get(), callee_name));
16430b57cec5SDimitry Andric
16440b57cec5SDimitry Andric if (PyErr_Occurred())
16450b57cec5SDimitry Andric PyErr_Clear();
16460b57cec5SDimitry Andric
16470b57cec5SDimitry Andric if (!pmeth.IsAllocated())
16480b57cec5SDimitry Andric return StructuredData::DictionarySP();
16490b57cec5SDimitry Andric
16500b57cec5SDimitry Andric if (PyCallable_Check(pmeth.get()) == 0) {
16510b57cec5SDimitry Andric if (PyErr_Occurred())
16520b57cec5SDimitry Andric PyErr_Clear();
16530b57cec5SDimitry Andric
16540b57cec5SDimitry Andric return StructuredData::DictionarySP();
16550b57cec5SDimitry Andric }
16560b57cec5SDimitry Andric
16570b57cec5SDimitry Andric if (PyErr_Occurred())
16580b57cec5SDimitry Andric PyErr_Clear();
16590b57cec5SDimitry Andric
16600b57cec5SDimitry Andric // right now we know this function exists and is callable..
16610b57cec5SDimitry Andric PythonObject py_return(
16620b57cec5SDimitry Andric PyRefType::Owned,
16630b57cec5SDimitry Andric PyObject_CallMethod(implementor.get(), callee_name, nullptr));
16640b57cec5SDimitry Andric
16650b57cec5SDimitry Andric // if it fails, print the error but otherwise go on
16660b57cec5SDimitry Andric if (PyErr_Occurred()) {
16670b57cec5SDimitry Andric PyErr_Print();
16680b57cec5SDimitry Andric PyErr_Clear();
16690b57cec5SDimitry Andric }
16700b57cec5SDimitry Andric if (py_return.get()) {
16710b57cec5SDimitry Andric PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
16720b57cec5SDimitry Andric return result_dict.CreateStructuredDictionary();
16730b57cec5SDimitry Andric }
16740b57cec5SDimitry Andric return StructuredData::DictionarySP();
16750b57cec5SDimitry Andric }
16760b57cec5SDimitry Andric
OSPlugin_ThreadsInfo(StructuredData::ObjectSP os_plugin_object_sp)16770b57cec5SDimitry Andric StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo(
16780b57cec5SDimitry Andric StructuredData::ObjectSP os_plugin_object_sp) {
16790b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
16800b57cec5SDimitry Andric
16810b57cec5SDimitry Andric static char callee_name[] = "get_thread_info";
16820b57cec5SDimitry Andric
16830b57cec5SDimitry Andric if (!os_plugin_object_sp)
16840b57cec5SDimitry Andric return StructuredData::ArraySP();
16850b57cec5SDimitry Andric
16860b57cec5SDimitry Andric StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
16870b57cec5SDimitry Andric if (!generic)
16880b57cec5SDimitry Andric return nullptr;
16890b57cec5SDimitry Andric
16900b57cec5SDimitry Andric PythonObject implementor(PyRefType::Borrowed,
16910b57cec5SDimitry Andric (PyObject *)generic->GetValue());
16920b57cec5SDimitry Andric
16930b57cec5SDimitry Andric if (!implementor.IsAllocated())
16940b57cec5SDimitry Andric return StructuredData::ArraySP();
16950b57cec5SDimitry Andric
16960b57cec5SDimitry Andric PythonObject pmeth(PyRefType::Owned,
16970b57cec5SDimitry Andric PyObject_GetAttrString(implementor.get(), callee_name));
16980b57cec5SDimitry Andric
16990b57cec5SDimitry Andric if (PyErr_Occurred())
17000b57cec5SDimitry Andric PyErr_Clear();
17010b57cec5SDimitry Andric
17020b57cec5SDimitry Andric if (!pmeth.IsAllocated())
17030b57cec5SDimitry Andric return StructuredData::ArraySP();
17040b57cec5SDimitry Andric
17050b57cec5SDimitry Andric if (PyCallable_Check(pmeth.get()) == 0) {
17060b57cec5SDimitry Andric if (PyErr_Occurred())
17070b57cec5SDimitry Andric PyErr_Clear();
17080b57cec5SDimitry Andric
17090b57cec5SDimitry Andric return StructuredData::ArraySP();
17100b57cec5SDimitry Andric }
17110b57cec5SDimitry Andric
17120b57cec5SDimitry Andric if (PyErr_Occurred())
17130b57cec5SDimitry Andric PyErr_Clear();
17140b57cec5SDimitry Andric
17150b57cec5SDimitry Andric // right now we know this function exists and is callable..
17160b57cec5SDimitry Andric PythonObject py_return(
17170b57cec5SDimitry Andric PyRefType::Owned,
17180b57cec5SDimitry Andric PyObject_CallMethod(implementor.get(), callee_name, nullptr));
17190b57cec5SDimitry Andric
17200b57cec5SDimitry Andric // if it fails, print the error but otherwise go on
17210b57cec5SDimitry Andric if (PyErr_Occurred()) {
17220b57cec5SDimitry Andric PyErr_Print();
17230b57cec5SDimitry Andric PyErr_Clear();
17240b57cec5SDimitry Andric }
17250b57cec5SDimitry Andric
17260b57cec5SDimitry Andric if (py_return.get()) {
17270b57cec5SDimitry Andric PythonList result_list(PyRefType::Borrowed, py_return.get());
17280b57cec5SDimitry Andric return result_list.CreateStructuredArray();
17290b57cec5SDimitry Andric }
17300b57cec5SDimitry Andric return StructuredData::ArraySP();
17310b57cec5SDimitry Andric }
17320b57cec5SDimitry Andric
17330b57cec5SDimitry Andric StructuredData::StringSP
OSPlugin_RegisterContextData(StructuredData::ObjectSP os_plugin_object_sp,lldb::tid_t tid)17340b57cec5SDimitry Andric ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData(
17350b57cec5SDimitry Andric StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
17360b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
17370b57cec5SDimitry Andric
17380b57cec5SDimitry Andric static char callee_name[] = "get_register_data";
17390b57cec5SDimitry Andric static char *param_format =
17400b57cec5SDimitry Andric const_cast<char *>(GetPythonValueFormatString(tid));
17410b57cec5SDimitry Andric
17420b57cec5SDimitry Andric if (!os_plugin_object_sp)
17430b57cec5SDimitry Andric return StructuredData::StringSP();
17440b57cec5SDimitry Andric
17450b57cec5SDimitry Andric StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
17460b57cec5SDimitry Andric if (!generic)
17470b57cec5SDimitry Andric return nullptr;
17480b57cec5SDimitry Andric PythonObject implementor(PyRefType::Borrowed,
17490b57cec5SDimitry Andric (PyObject *)generic->GetValue());
17500b57cec5SDimitry Andric
17510b57cec5SDimitry Andric if (!implementor.IsAllocated())
17520b57cec5SDimitry Andric return StructuredData::StringSP();
17530b57cec5SDimitry Andric
17540b57cec5SDimitry Andric PythonObject pmeth(PyRefType::Owned,
17550b57cec5SDimitry Andric PyObject_GetAttrString(implementor.get(), callee_name));
17560b57cec5SDimitry Andric
17570b57cec5SDimitry Andric if (PyErr_Occurred())
17580b57cec5SDimitry Andric PyErr_Clear();
17590b57cec5SDimitry Andric
17600b57cec5SDimitry Andric if (!pmeth.IsAllocated())
17610b57cec5SDimitry Andric return StructuredData::StringSP();
17620b57cec5SDimitry Andric
17630b57cec5SDimitry Andric if (PyCallable_Check(pmeth.get()) == 0) {
17640b57cec5SDimitry Andric if (PyErr_Occurred())
17650b57cec5SDimitry Andric PyErr_Clear();
17660b57cec5SDimitry Andric return StructuredData::StringSP();
17670b57cec5SDimitry Andric }
17680b57cec5SDimitry Andric
17690b57cec5SDimitry Andric if (PyErr_Occurred())
17700b57cec5SDimitry Andric PyErr_Clear();
17710b57cec5SDimitry Andric
17720b57cec5SDimitry Andric // right now we know this function exists and is callable..
17730b57cec5SDimitry Andric PythonObject py_return(
17740b57cec5SDimitry Andric PyRefType::Owned,
17750b57cec5SDimitry Andric PyObject_CallMethod(implementor.get(), callee_name, param_format, tid));
17760b57cec5SDimitry Andric
17770b57cec5SDimitry Andric // if it fails, print the error but otherwise go on
17780b57cec5SDimitry Andric if (PyErr_Occurred()) {
17790b57cec5SDimitry Andric PyErr_Print();
17800b57cec5SDimitry Andric PyErr_Clear();
17810b57cec5SDimitry Andric }
17820b57cec5SDimitry Andric
17830b57cec5SDimitry Andric if (py_return.get()) {
17840b57cec5SDimitry Andric PythonBytes result(PyRefType::Borrowed, py_return.get());
17850b57cec5SDimitry Andric return result.CreateStructuredString();
17860b57cec5SDimitry Andric }
17870b57cec5SDimitry Andric return StructuredData::StringSP();
17880b57cec5SDimitry Andric }
17890b57cec5SDimitry Andric
OSPlugin_CreateThread(StructuredData::ObjectSP os_plugin_object_sp,lldb::tid_t tid,lldb::addr_t context)17900b57cec5SDimitry Andric StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread(
17910b57cec5SDimitry Andric StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
17920b57cec5SDimitry Andric lldb::addr_t context) {
17930b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
17940b57cec5SDimitry Andric
17950b57cec5SDimitry Andric static char callee_name[] = "create_thread";
17960b57cec5SDimitry Andric std::string param_format;
17970b57cec5SDimitry Andric param_format += GetPythonValueFormatString(tid);
17980b57cec5SDimitry Andric param_format += GetPythonValueFormatString(context);
17990b57cec5SDimitry Andric
18000b57cec5SDimitry Andric if (!os_plugin_object_sp)
18010b57cec5SDimitry Andric return StructuredData::DictionarySP();
18020b57cec5SDimitry Andric
18030b57cec5SDimitry Andric StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
18040b57cec5SDimitry Andric if (!generic)
18050b57cec5SDimitry Andric return nullptr;
18060b57cec5SDimitry Andric
18070b57cec5SDimitry Andric PythonObject implementor(PyRefType::Borrowed,
18080b57cec5SDimitry Andric (PyObject *)generic->GetValue());
18090b57cec5SDimitry Andric
18100b57cec5SDimitry Andric if (!implementor.IsAllocated())
18110b57cec5SDimitry Andric return StructuredData::DictionarySP();
18120b57cec5SDimitry Andric
18130b57cec5SDimitry Andric PythonObject pmeth(PyRefType::Owned,
18140b57cec5SDimitry Andric PyObject_GetAttrString(implementor.get(), callee_name));
18150b57cec5SDimitry Andric
18160b57cec5SDimitry Andric if (PyErr_Occurred())
18170b57cec5SDimitry Andric PyErr_Clear();
18180b57cec5SDimitry Andric
18190b57cec5SDimitry Andric if (!pmeth.IsAllocated())
18200b57cec5SDimitry Andric return StructuredData::DictionarySP();
18210b57cec5SDimitry Andric
18220b57cec5SDimitry Andric if (PyCallable_Check(pmeth.get()) == 0) {
18230b57cec5SDimitry Andric if (PyErr_Occurred())
18240b57cec5SDimitry Andric PyErr_Clear();
18250b57cec5SDimitry Andric return StructuredData::DictionarySP();
18260b57cec5SDimitry Andric }
18270b57cec5SDimitry Andric
18280b57cec5SDimitry Andric if (PyErr_Occurred())
18290b57cec5SDimitry Andric PyErr_Clear();
18300b57cec5SDimitry Andric
18310b57cec5SDimitry Andric // right now we know this function exists and is callable..
18320b57cec5SDimitry Andric PythonObject py_return(PyRefType::Owned,
18330b57cec5SDimitry Andric PyObject_CallMethod(implementor.get(), callee_name,
18340b57cec5SDimitry Andric ¶m_format[0], tid, context));
18350b57cec5SDimitry Andric
18360b57cec5SDimitry Andric // if it fails, print the error but otherwise go on
18370b57cec5SDimitry Andric if (PyErr_Occurred()) {
18380b57cec5SDimitry Andric PyErr_Print();
18390b57cec5SDimitry Andric PyErr_Clear();
18400b57cec5SDimitry Andric }
18410b57cec5SDimitry Andric
18420b57cec5SDimitry Andric if (py_return.get()) {
18430b57cec5SDimitry Andric PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
18440b57cec5SDimitry Andric return result_dict.CreateStructuredDictionary();
18450b57cec5SDimitry Andric }
18460b57cec5SDimitry Andric return StructuredData::DictionarySP();
18470b57cec5SDimitry Andric }
18480b57cec5SDimitry Andric
CreateScriptedThreadPlan(const char * class_name,StructuredDataImpl * args_data,std::string & error_str,lldb::ThreadPlanSP thread_plan_sp)18490b57cec5SDimitry Andric StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan(
18509dba64beSDimitry Andric const char *class_name, StructuredDataImpl *args_data,
1851480093f4SDimitry Andric std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) {
18520b57cec5SDimitry Andric if (class_name == nullptr || class_name[0] == '\0')
18530b57cec5SDimitry Andric return StructuredData::ObjectSP();
18540b57cec5SDimitry Andric
18550b57cec5SDimitry Andric if (!thread_plan_sp.get())
18569dba64beSDimitry Andric return {};
18570b57cec5SDimitry Andric
18580b57cec5SDimitry Andric Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
18590b57cec5SDimitry Andric ScriptInterpreterPythonImpl *python_interpreter =
1860af732203SDimitry Andric GetPythonInterpreter(debugger);
18610b57cec5SDimitry Andric
1862af732203SDimitry Andric if (!python_interpreter)
18639dba64beSDimitry Andric return {};
18640b57cec5SDimitry Andric
18650b57cec5SDimitry Andric void *ret_val;
18660b57cec5SDimitry Andric
18670b57cec5SDimitry Andric {
18680b57cec5SDimitry Andric Locker py_lock(this,
18690b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
18700b57cec5SDimitry Andric ret_val = LLDBSwigPythonCreateScriptedThreadPlan(
18710b57cec5SDimitry Andric class_name, python_interpreter->m_dictionary_name.c_str(),
18729dba64beSDimitry Andric args_data, error_str, thread_plan_sp);
18739dba64beSDimitry Andric if (!ret_val)
18749dba64beSDimitry Andric return {};
18750b57cec5SDimitry Andric }
18760b57cec5SDimitry Andric
18770b57cec5SDimitry Andric return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
18780b57cec5SDimitry Andric }
18790b57cec5SDimitry Andric
ScriptedThreadPlanExplainsStop(StructuredData::ObjectSP implementor_sp,Event * event,bool & script_error)18800b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop(
18810b57cec5SDimitry Andric StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
18820b57cec5SDimitry Andric bool explains_stop = true;
18830b57cec5SDimitry Andric StructuredData::Generic *generic = nullptr;
18840b57cec5SDimitry Andric if (implementor_sp)
18850b57cec5SDimitry Andric generic = implementor_sp->GetAsGeneric();
18860b57cec5SDimitry Andric if (generic) {
18870b57cec5SDimitry Andric Locker py_lock(this,
18880b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
18890b57cec5SDimitry Andric explains_stop = LLDBSWIGPythonCallThreadPlan(
18900b57cec5SDimitry Andric generic->GetValue(), "explains_stop", event, script_error);
18910b57cec5SDimitry Andric if (script_error)
18920b57cec5SDimitry Andric return true;
18930b57cec5SDimitry Andric }
18940b57cec5SDimitry Andric return explains_stop;
18950b57cec5SDimitry Andric }
18960b57cec5SDimitry Andric
ScriptedThreadPlanShouldStop(StructuredData::ObjectSP implementor_sp,Event * event,bool & script_error)18970b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop(
18980b57cec5SDimitry Andric StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
18990b57cec5SDimitry Andric bool should_stop = true;
19000b57cec5SDimitry Andric StructuredData::Generic *generic = nullptr;
19010b57cec5SDimitry Andric if (implementor_sp)
19020b57cec5SDimitry Andric generic = implementor_sp->GetAsGeneric();
19030b57cec5SDimitry Andric if (generic) {
19040b57cec5SDimitry Andric Locker py_lock(this,
19050b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19060b57cec5SDimitry Andric should_stop = LLDBSWIGPythonCallThreadPlan(
19070b57cec5SDimitry Andric generic->GetValue(), "should_stop", event, script_error);
19080b57cec5SDimitry Andric if (script_error)
19090b57cec5SDimitry Andric return true;
19100b57cec5SDimitry Andric }
19110b57cec5SDimitry Andric return should_stop;
19120b57cec5SDimitry Andric }
19130b57cec5SDimitry Andric
ScriptedThreadPlanIsStale(StructuredData::ObjectSP implementor_sp,bool & script_error)19140b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale(
19150b57cec5SDimitry Andric StructuredData::ObjectSP implementor_sp, bool &script_error) {
19160b57cec5SDimitry Andric bool is_stale = true;
19170b57cec5SDimitry Andric StructuredData::Generic *generic = nullptr;
19180b57cec5SDimitry Andric if (implementor_sp)
19190b57cec5SDimitry Andric generic = implementor_sp->GetAsGeneric();
19200b57cec5SDimitry Andric if (generic) {
19210b57cec5SDimitry Andric Locker py_lock(this,
19220b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19230b57cec5SDimitry Andric is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale",
19240b57cec5SDimitry Andric nullptr, script_error);
19250b57cec5SDimitry Andric if (script_error)
19260b57cec5SDimitry Andric return true;
19270b57cec5SDimitry Andric }
19280b57cec5SDimitry Andric return is_stale;
19290b57cec5SDimitry Andric }
19300b57cec5SDimitry Andric
ScriptedThreadPlanGetRunState(StructuredData::ObjectSP implementor_sp,bool & script_error)19310b57cec5SDimitry Andric lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState(
19320b57cec5SDimitry Andric StructuredData::ObjectSP implementor_sp, bool &script_error) {
19330b57cec5SDimitry Andric bool should_step = false;
19340b57cec5SDimitry Andric StructuredData::Generic *generic = nullptr;
19350b57cec5SDimitry Andric if (implementor_sp)
19360b57cec5SDimitry Andric generic = implementor_sp->GetAsGeneric();
19370b57cec5SDimitry Andric if (generic) {
19380b57cec5SDimitry Andric Locker py_lock(this,
19390b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19400b57cec5SDimitry Andric should_step = LLDBSWIGPythonCallThreadPlan(
19410b57cec5SDimitry Andric generic->GetValue(), "should_step", nullptr, script_error);
19420b57cec5SDimitry Andric if (script_error)
19430b57cec5SDimitry Andric should_step = true;
19440b57cec5SDimitry Andric }
19450b57cec5SDimitry Andric if (should_step)
19460b57cec5SDimitry Andric return lldb::eStateStepping;
19470b57cec5SDimitry Andric return lldb::eStateRunning;
19480b57cec5SDimitry Andric }
19490b57cec5SDimitry Andric
19500b57cec5SDimitry Andric StructuredData::GenericSP
CreateScriptedBreakpointResolver(const char * class_name,StructuredDataImpl * args_data,lldb::BreakpointSP & bkpt_sp)19510b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
19520b57cec5SDimitry Andric const char *class_name, StructuredDataImpl *args_data,
19530b57cec5SDimitry Andric lldb::BreakpointSP &bkpt_sp) {
19540b57cec5SDimitry Andric
19550b57cec5SDimitry Andric if (class_name == nullptr || class_name[0] == '\0')
19560b57cec5SDimitry Andric return StructuredData::GenericSP();
19570b57cec5SDimitry Andric
19580b57cec5SDimitry Andric if (!bkpt_sp.get())
19590b57cec5SDimitry Andric return StructuredData::GenericSP();
19600b57cec5SDimitry Andric
19610b57cec5SDimitry Andric Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
19620b57cec5SDimitry Andric ScriptInterpreterPythonImpl *python_interpreter =
1963af732203SDimitry Andric GetPythonInterpreter(debugger);
19640b57cec5SDimitry Andric
1965af732203SDimitry Andric if (!python_interpreter)
19660b57cec5SDimitry Andric return StructuredData::GenericSP();
19670b57cec5SDimitry Andric
19680b57cec5SDimitry Andric void *ret_val;
19690b57cec5SDimitry Andric
19700b57cec5SDimitry Andric {
19710b57cec5SDimitry Andric Locker py_lock(this,
19720b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19730b57cec5SDimitry Andric
19740b57cec5SDimitry Andric ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver(
19750b57cec5SDimitry Andric class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
19760b57cec5SDimitry Andric bkpt_sp);
19770b57cec5SDimitry Andric }
19780b57cec5SDimitry Andric
19790b57cec5SDimitry Andric return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
19800b57cec5SDimitry Andric }
19810b57cec5SDimitry Andric
ScriptedBreakpointResolverSearchCallback(StructuredData::GenericSP implementor_sp,SymbolContext * sym_ctx)19820b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
19830b57cec5SDimitry Andric StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
19840b57cec5SDimitry Andric bool should_continue = false;
19850b57cec5SDimitry Andric
19860b57cec5SDimitry Andric if (implementor_sp) {
19870b57cec5SDimitry Andric Locker py_lock(this,
19880b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
19890b57cec5SDimitry Andric should_continue = LLDBSwigPythonCallBreakpointResolver(
19900b57cec5SDimitry Andric implementor_sp->GetValue(), "__callback__", sym_ctx);
19910b57cec5SDimitry Andric if (PyErr_Occurred()) {
19920b57cec5SDimitry Andric PyErr_Print();
19930b57cec5SDimitry Andric PyErr_Clear();
19940b57cec5SDimitry Andric }
19950b57cec5SDimitry Andric }
19960b57cec5SDimitry Andric return should_continue;
19970b57cec5SDimitry Andric }
19980b57cec5SDimitry Andric
19990b57cec5SDimitry Andric lldb::SearchDepth
ScriptedBreakpointResolverSearchDepth(StructuredData::GenericSP implementor_sp)20000b57cec5SDimitry Andric ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
20010b57cec5SDimitry Andric StructuredData::GenericSP implementor_sp) {
20020b57cec5SDimitry Andric int depth_as_int = lldb::eSearchDepthModule;
20030b57cec5SDimitry Andric if (implementor_sp) {
20040b57cec5SDimitry Andric Locker py_lock(this,
20050b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
20060b57cec5SDimitry Andric depth_as_int = LLDBSwigPythonCallBreakpointResolver(
20070b57cec5SDimitry Andric implementor_sp->GetValue(), "__get_depth__", nullptr);
20080b57cec5SDimitry Andric if (PyErr_Occurred()) {
20090b57cec5SDimitry Andric PyErr_Print();
20100b57cec5SDimitry Andric PyErr_Clear();
20110b57cec5SDimitry Andric }
20120b57cec5SDimitry Andric }
20130b57cec5SDimitry Andric if (depth_as_int == lldb::eSearchDepthInvalid)
20140b57cec5SDimitry Andric return lldb::eSearchDepthModule;
20150b57cec5SDimitry Andric
20160b57cec5SDimitry Andric if (depth_as_int <= lldb::kLastSearchDepthKind)
20170b57cec5SDimitry Andric return (lldb::SearchDepth)depth_as_int;
20180b57cec5SDimitry Andric return lldb::eSearchDepthModule;
20190b57cec5SDimitry Andric }
20200b57cec5SDimitry Andric
CreateScriptedStopHook(TargetSP target_sp,const char * class_name,StructuredDataImpl * args_data,Status & error)2021af732203SDimitry Andric StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
2022af732203SDimitry Andric TargetSP target_sp, const char *class_name, StructuredDataImpl *args_data,
2023af732203SDimitry Andric Status &error) {
2024af732203SDimitry Andric
2025af732203SDimitry Andric if (!target_sp) {
2026af732203SDimitry Andric error.SetErrorString("No target for scripted stop-hook.");
2027af732203SDimitry Andric return StructuredData::GenericSP();
2028af732203SDimitry Andric }
2029af732203SDimitry Andric
2030af732203SDimitry Andric if (class_name == nullptr || class_name[0] == '\0') {
2031af732203SDimitry Andric error.SetErrorString("No class name for scripted stop-hook.");
2032af732203SDimitry Andric return StructuredData::GenericSP();
2033af732203SDimitry Andric }
2034af732203SDimitry Andric
2035af732203SDimitry Andric ScriptInterpreterPythonImpl *python_interpreter =
2036af732203SDimitry Andric GetPythonInterpreter(m_debugger);
2037af732203SDimitry Andric
2038af732203SDimitry Andric if (!python_interpreter) {
2039af732203SDimitry Andric error.SetErrorString("No script interpreter for scripted stop-hook.");
2040af732203SDimitry Andric return StructuredData::GenericSP();
2041af732203SDimitry Andric }
2042af732203SDimitry Andric
2043af732203SDimitry Andric void *ret_val;
2044af732203SDimitry Andric
2045af732203SDimitry Andric {
2046af732203SDimitry Andric Locker py_lock(this,
2047af732203SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2048af732203SDimitry Andric
2049af732203SDimitry Andric ret_val = LLDBSwigPythonCreateScriptedStopHook(
2050af732203SDimitry Andric target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
2051af732203SDimitry Andric args_data, error);
2052af732203SDimitry Andric }
2053af732203SDimitry Andric
2054af732203SDimitry Andric return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
2055af732203SDimitry Andric }
2056af732203SDimitry Andric
ScriptedStopHookHandleStop(StructuredData::GenericSP implementor_sp,ExecutionContext & exc_ctx,lldb::StreamSP stream_sp)2057af732203SDimitry Andric bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
2058af732203SDimitry Andric StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
2059af732203SDimitry Andric lldb::StreamSP stream_sp) {
2060af732203SDimitry Andric assert(implementor_sp &&
2061af732203SDimitry Andric "can't call a stop hook with an invalid implementor");
2062af732203SDimitry Andric assert(stream_sp && "can't call a stop hook with an invalid stream");
2063af732203SDimitry Andric
2064af732203SDimitry Andric Locker py_lock(this,
2065af732203SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2066af732203SDimitry Andric
2067af732203SDimitry Andric lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
2068af732203SDimitry Andric
2069af732203SDimitry Andric bool ret_val = LLDBSwigPythonStopHookCallHandleStop(
2070af732203SDimitry Andric implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
2071af732203SDimitry Andric return ret_val;
2072af732203SDimitry Andric }
2073af732203SDimitry Andric
20740b57cec5SDimitry Andric StructuredData::ObjectSP
LoadPluginModule(const FileSpec & file_spec,lldb_private::Status & error)20750b57cec5SDimitry Andric ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
20760b57cec5SDimitry Andric lldb_private::Status &error) {
20770b57cec5SDimitry Andric if (!FileSystem::Instance().Exists(file_spec)) {
20780b57cec5SDimitry Andric error.SetErrorString("no such file");
20790b57cec5SDimitry Andric return StructuredData::ObjectSP();
20800b57cec5SDimitry Andric }
20810b57cec5SDimitry Andric
20820b57cec5SDimitry Andric StructuredData::ObjectSP module_sp;
20830b57cec5SDimitry Andric
2084*5f7ddb14SDimitry Andric LoadScriptOptions load_script_options =
2085*5f7ddb14SDimitry Andric LoadScriptOptions().SetInitSession(true).SetSilent(false);
2086*5f7ddb14SDimitry Andric if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
2087*5f7ddb14SDimitry Andric error, &module_sp))
20880b57cec5SDimitry Andric return module_sp;
20890b57cec5SDimitry Andric
20900b57cec5SDimitry Andric return StructuredData::ObjectSP();
20910b57cec5SDimitry Andric }
20920b57cec5SDimitry Andric
GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp,Target * target,const char * setting_name,lldb_private::Status & error)20930b57cec5SDimitry Andric StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
20940b57cec5SDimitry Andric StructuredData::ObjectSP plugin_module_sp, Target *target,
20950b57cec5SDimitry Andric const char *setting_name, lldb_private::Status &error) {
20960b57cec5SDimitry Andric if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
20970b57cec5SDimitry Andric return StructuredData::DictionarySP();
20980b57cec5SDimitry Andric StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
20990b57cec5SDimitry Andric if (!generic)
21000b57cec5SDimitry Andric return StructuredData::DictionarySP();
21010b57cec5SDimitry Andric
21020b57cec5SDimitry Andric Locker py_lock(this,
21030b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
21040b57cec5SDimitry Andric TargetSP target_sp(target->shared_from_this());
21050b57cec5SDimitry Andric
21069dba64beSDimitry Andric auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting(
21079dba64beSDimitry Andric generic->GetValue(), setting_name, target_sp);
21089dba64beSDimitry Andric
21099dba64beSDimitry Andric if (!setting)
21109dba64beSDimitry Andric return StructuredData::DictionarySP();
21119dba64beSDimitry Andric
21129dba64beSDimitry Andric PythonDictionary py_dict =
21139dba64beSDimitry Andric unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
21149dba64beSDimitry Andric
21159dba64beSDimitry Andric if (!py_dict)
21169dba64beSDimitry Andric return StructuredData::DictionarySP();
21179dba64beSDimitry Andric
21180b57cec5SDimitry Andric return py_dict.CreateStructuredDictionary();
21190b57cec5SDimitry Andric }
21200b57cec5SDimitry Andric
21210b57cec5SDimitry Andric StructuredData::ObjectSP
CreateSyntheticScriptedProvider(const char * class_name,lldb::ValueObjectSP valobj)21220b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
21230b57cec5SDimitry Andric const char *class_name, lldb::ValueObjectSP valobj) {
21240b57cec5SDimitry Andric if (class_name == nullptr || class_name[0] == '\0')
21250b57cec5SDimitry Andric return StructuredData::ObjectSP();
21260b57cec5SDimitry Andric
21270b57cec5SDimitry Andric if (!valobj.get())
21280b57cec5SDimitry Andric return StructuredData::ObjectSP();
21290b57cec5SDimitry Andric
21300b57cec5SDimitry Andric ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
21310b57cec5SDimitry Andric Target *target = exe_ctx.GetTargetPtr();
21320b57cec5SDimitry Andric
21330b57cec5SDimitry Andric if (!target)
21340b57cec5SDimitry Andric return StructuredData::ObjectSP();
21350b57cec5SDimitry Andric
21360b57cec5SDimitry Andric Debugger &debugger = target->GetDebugger();
21370b57cec5SDimitry Andric ScriptInterpreterPythonImpl *python_interpreter =
2138af732203SDimitry Andric GetPythonInterpreter(debugger);
21390b57cec5SDimitry Andric
2140af732203SDimitry Andric if (!python_interpreter)
21410b57cec5SDimitry Andric return StructuredData::ObjectSP();
21420b57cec5SDimitry Andric
21430b57cec5SDimitry Andric void *ret_val = nullptr;
21440b57cec5SDimitry Andric
21450b57cec5SDimitry Andric {
21460b57cec5SDimitry Andric Locker py_lock(this,
21470b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
21480b57cec5SDimitry Andric ret_val = LLDBSwigPythonCreateSyntheticProvider(
21490b57cec5SDimitry Andric class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
21500b57cec5SDimitry Andric }
21510b57cec5SDimitry Andric
21520b57cec5SDimitry Andric return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
21530b57cec5SDimitry Andric }
21540b57cec5SDimitry Andric
21550b57cec5SDimitry Andric StructuredData::GenericSP
CreateScriptCommandObject(const char * class_name)21560b57cec5SDimitry Andric ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
21570b57cec5SDimitry Andric DebuggerSP debugger_sp(m_debugger.shared_from_this());
21580b57cec5SDimitry Andric
21590b57cec5SDimitry Andric if (class_name == nullptr || class_name[0] == '\0')
21600b57cec5SDimitry Andric return StructuredData::GenericSP();
21610b57cec5SDimitry Andric
21620b57cec5SDimitry Andric if (!debugger_sp.get())
21630b57cec5SDimitry Andric return StructuredData::GenericSP();
21640b57cec5SDimitry Andric
21650b57cec5SDimitry Andric void *ret_val;
21660b57cec5SDimitry Andric
21670b57cec5SDimitry Andric {
21680b57cec5SDimitry Andric Locker py_lock(this,
21690b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
21700b57cec5SDimitry Andric ret_val = LLDBSwigPythonCreateCommandObject(
21710b57cec5SDimitry Andric class_name, m_dictionary_name.c_str(), debugger_sp);
21720b57cec5SDimitry Andric }
21730b57cec5SDimitry Andric
21740b57cec5SDimitry Andric return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
21750b57cec5SDimitry Andric }
21760b57cec5SDimitry Andric
GenerateTypeScriptFunction(const char * oneliner,std::string & output,const void * name_token)21770b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
21780b57cec5SDimitry Andric const char *oneliner, std::string &output, const void *name_token) {
21790b57cec5SDimitry Andric StringList input;
21800b57cec5SDimitry Andric input.SplitIntoLines(oneliner, strlen(oneliner));
21810b57cec5SDimitry Andric return GenerateTypeScriptFunction(input, output, name_token);
21820b57cec5SDimitry Andric }
21830b57cec5SDimitry Andric
GenerateTypeSynthClass(const char * oneliner,std::string & output,const void * name_token)21840b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
21850b57cec5SDimitry Andric const char *oneliner, std::string &output, const void *name_token) {
21860b57cec5SDimitry Andric StringList input;
21870b57cec5SDimitry Andric input.SplitIntoLines(oneliner, strlen(oneliner));
21880b57cec5SDimitry Andric return GenerateTypeSynthClass(input, output, name_token);
21890b57cec5SDimitry Andric }
21900b57cec5SDimitry Andric
GenerateBreakpointCommandCallbackData(StringList & user_input,std::string & output,bool has_extra_args)21910b57cec5SDimitry Andric Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
2192480093f4SDimitry Andric StringList &user_input, std::string &output,
2193480093f4SDimitry Andric bool has_extra_args) {
21940b57cec5SDimitry Andric static uint32_t num_created_functions = 0;
21950b57cec5SDimitry Andric user_input.RemoveBlankLines();
21960b57cec5SDimitry Andric StreamString sstr;
21970b57cec5SDimitry Andric Status error;
21980b57cec5SDimitry Andric if (user_input.GetSize() == 0) {
21990b57cec5SDimitry Andric error.SetErrorString("No input data.");
22000b57cec5SDimitry Andric return error;
22010b57cec5SDimitry Andric }
22020b57cec5SDimitry Andric
22030b57cec5SDimitry Andric std::string auto_generated_function_name(GenerateUniqueName(
22040b57cec5SDimitry Andric "lldb_autogen_python_bp_callback_func_", num_created_functions));
2205480093f4SDimitry Andric if (has_extra_args)
2206480093f4SDimitry Andric sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
2207480093f4SDimitry Andric auto_generated_function_name.c_str());
2208480093f4SDimitry Andric else
22090b57cec5SDimitry Andric sstr.Printf("def %s (frame, bp_loc, internal_dict):",
22100b57cec5SDimitry Andric auto_generated_function_name.c_str());
22110b57cec5SDimitry Andric
22120b57cec5SDimitry Andric error = GenerateFunction(sstr.GetData(), user_input);
22130b57cec5SDimitry Andric if (!error.Success())
22140b57cec5SDimitry Andric return error;
22150b57cec5SDimitry Andric
22160b57cec5SDimitry Andric // Store the name of the auto-generated function to be called.
22170b57cec5SDimitry Andric output.assign(auto_generated_function_name);
22180b57cec5SDimitry Andric return error;
22190b57cec5SDimitry Andric }
22200b57cec5SDimitry Andric
GenerateWatchpointCommandCallbackData(StringList & user_input,std::string & output)22210b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
22220b57cec5SDimitry Andric StringList &user_input, std::string &output) {
22230b57cec5SDimitry Andric static uint32_t num_created_functions = 0;
22240b57cec5SDimitry Andric user_input.RemoveBlankLines();
22250b57cec5SDimitry Andric StreamString sstr;
22260b57cec5SDimitry Andric
22270b57cec5SDimitry Andric if (user_input.GetSize() == 0)
22280b57cec5SDimitry Andric return false;
22290b57cec5SDimitry Andric
22300b57cec5SDimitry Andric std::string auto_generated_function_name(GenerateUniqueName(
22310b57cec5SDimitry Andric "lldb_autogen_python_wp_callback_func_", num_created_functions));
22320b57cec5SDimitry Andric sstr.Printf("def %s (frame, wp, internal_dict):",
22330b57cec5SDimitry Andric auto_generated_function_name.c_str());
22340b57cec5SDimitry Andric
22350b57cec5SDimitry Andric if (!GenerateFunction(sstr.GetData(), user_input).Success())
22360b57cec5SDimitry Andric return false;
22370b57cec5SDimitry Andric
22380b57cec5SDimitry Andric // Store the name of the auto-generated function to be called.
22390b57cec5SDimitry Andric output.assign(auto_generated_function_name);
22400b57cec5SDimitry Andric return true;
22410b57cec5SDimitry Andric }
22420b57cec5SDimitry Andric
GetScriptedSummary(const char * python_function_name,lldb::ValueObjectSP valobj,StructuredData::ObjectSP & callee_wrapper_sp,const TypeSummaryOptions & options,std::string & retval)22430b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetScriptedSummary(
22440b57cec5SDimitry Andric const char *python_function_name, lldb::ValueObjectSP valobj,
22450b57cec5SDimitry Andric StructuredData::ObjectSP &callee_wrapper_sp,
22460b57cec5SDimitry Andric const TypeSummaryOptions &options, std::string &retval) {
22470b57cec5SDimitry Andric
2248af732203SDimitry Andric LLDB_SCOPED_TIMER();
22490b57cec5SDimitry Andric
22500b57cec5SDimitry Andric if (!valobj.get()) {
22510b57cec5SDimitry Andric retval.assign("<no object>");
22520b57cec5SDimitry Andric return false;
22530b57cec5SDimitry Andric }
22540b57cec5SDimitry Andric
22550b57cec5SDimitry Andric void *old_callee = nullptr;
22560b57cec5SDimitry Andric StructuredData::Generic *generic = nullptr;
22570b57cec5SDimitry Andric if (callee_wrapper_sp) {
22580b57cec5SDimitry Andric generic = callee_wrapper_sp->GetAsGeneric();
22590b57cec5SDimitry Andric if (generic)
22600b57cec5SDimitry Andric old_callee = generic->GetValue();
22610b57cec5SDimitry Andric }
22620b57cec5SDimitry Andric void *new_callee = old_callee;
22630b57cec5SDimitry Andric
22640b57cec5SDimitry Andric bool ret_val;
22650b57cec5SDimitry Andric if (python_function_name && *python_function_name) {
22660b57cec5SDimitry Andric {
22670b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
22680b57cec5SDimitry Andric Locker::NoSTDIN);
22690b57cec5SDimitry Andric {
22700b57cec5SDimitry Andric TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
22710b57cec5SDimitry Andric
22720b57cec5SDimitry Andric static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
22730b57cec5SDimitry Andric Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
22740b57cec5SDimitry Andric ret_val = LLDBSwigPythonCallTypeScript(
22750b57cec5SDimitry Andric python_function_name, GetSessionDictionary().get(), valobj,
22760b57cec5SDimitry Andric &new_callee, options_sp, retval);
22770b57cec5SDimitry Andric }
22780b57cec5SDimitry Andric }
22790b57cec5SDimitry Andric } else {
22800b57cec5SDimitry Andric retval.assign("<no function name>");
22810b57cec5SDimitry Andric return false;
22820b57cec5SDimitry Andric }
22830b57cec5SDimitry Andric
22840b57cec5SDimitry Andric if (new_callee && old_callee != new_callee)
22850b57cec5SDimitry Andric callee_wrapper_sp = std::make_shared<StructuredPythonObject>(new_callee);
22860b57cec5SDimitry Andric
22870b57cec5SDimitry Andric return ret_val;
22880b57cec5SDimitry Andric }
22890b57cec5SDimitry Andric
BreakpointCallbackFunction(void * baton,StoppointCallbackContext * context,user_id_t break_id,user_id_t break_loc_id)22900b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
22910b57cec5SDimitry Andric void *baton, StoppointCallbackContext *context, user_id_t break_id,
22920b57cec5SDimitry Andric user_id_t break_loc_id) {
22930b57cec5SDimitry Andric CommandDataPython *bp_option_data = (CommandDataPython *)baton;
22940b57cec5SDimitry Andric const char *python_function_name = bp_option_data->script_source.c_str();
22950b57cec5SDimitry Andric
22960b57cec5SDimitry Andric if (!context)
22970b57cec5SDimitry Andric return true;
22980b57cec5SDimitry Andric
22990b57cec5SDimitry Andric ExecutionContext exe_ctx(context->exe_ctx_ref);
23000b57cec5SDimitry Andric Target *target = exe_ctx.GetTargetPtr();
23010b57cec5SDimitry Andric
23020b57cec5SDimitry Andric if (!target)
23030b57cec5SDimitry Andric return true;
23040b57cec5SDimitry Andric
23050b57cec5SDimitry Andric Debugger &debugger = target->GetDebugger();
23060b57cec5SDimitry Andric ScriptInterpreterPythonImpl *python_interpreter =
2307af732203SDimitry Andric GetPythonInterpreter(debugger);
23080b57cec5SDimitry Andric
2309af732203SDimitry Andric if (!python_interpreter)
23100b57cec5SDimitry Andric return true;
23110b57cec5SDimitry Andric
23120b57cec5SDimitry Andric if (python_function_name && python_function_name[0]) {
23130b57cec5SDimitry Andric const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
23140b57cec5SDimitry Andric BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
23150b57cec5SDimitry Andric if (breakpoint_sp) {
23160b57cec5SDimitry Andric const BreakpointLocationSP bp_loc_sp(
23170b57cec5SDimitry Andric breakpoint_sp->FindLocationByID(break_loc_id));
23180b57cec5SDimitry Andric
23190b57cec5SDimitry Andric if (stop_frame_sp && bp_loc_sp) {
23200b57cec5SDimitry Andric bool ret_val = true;
23210b57cec5SDimitry Andric {
23220b57cec5SDimitry Andric Locker py_lock(python_interpreter, Locker::AcquireLock |
23230b57cec5SDimitry Andric Locker::InitSession |
23240b57cec5SDimitry Andric Locker::NoSTDIN);
2325480093f4SDimitry Andric Expected<bool> maybe_ret_val =
2326480093f4SDimitry Andric LLDBSwigPythonBreakpointCallbackFunction(
23270b57cec5SDimitry Andric python_function_name,
23280b57cec5SDimitry Andric python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2329480093f4SDimitry Andric bp_loc_sp, bp_option_data->m_extra_args_up.get());
2330480093f4SDimitry Andric
2331480093f4SDimitry Andric if (!maybe_ret_val) {
2332480093f4SDimitry Andric
2333480093f4SDimitry Andric llvm::handleAllErrors(
2334480093f4SDimitry Andric maybe_ret_val.takeError(),
2335480093f4SDimitry Andric [&](PythonException &E) {
2336480093f4SDimitry Andric debugger.GetErrorStream() << E.ReadBacktrace();
2337480093f4SDimitry Andric },
2338480093f4SDimitry Andric [&](const llvm::ErrorInfoBase &E) {
2339480093f4SDimitry Andric debugger.GetErrorStream() << E.message();
2340480093f4SDimitry Andric });
2341480093f4SDimitry Andric
2342480093f4SDimitry Andric } else {
2343480093f4SDimitry Andric ret_val = maybe_ret_val.get();
2344480093f4SDimitry Andric }
23450b57cec5SDimitry Andric }
23460b57cec5SDimitry Andric return ret_val;
23470b57cec5SDimitry Andric }
23480b57cec5SDimitry Andric }
23490b57cec5SDimitry Andric }
23500b57cec5SDimitry Andric // We currently always true so we stop in case anything goes wrong when
23510b57cec5SDimitry Andric // trying to call the script function
23520b57cec5SDimitry Andric return true;
23530b57cec5SDimitry Andric }
23540b57cec5SDimitry Andric
WatchpointCallbackFunction(void * baton,StoppointCallbackContext * context,user_id_t watch_id)23550b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
23560b57cec5SDimitry Andric void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
23570b57cec5SDimitry Andric WatchpointOptions::CommandData *wp_option_data =
23580b57cec5SDimitry Andric (WatchpointOptions::CommandData *)baton;
23590b57cec5SDimitry Andric const char *python_function_name = wp_option_data->script_source.c_str();
23600b57cec5SDimitry Andric
23610b57cec5SDimitry Andric if (!context)
23620b57cec5SDimitry Andric return true;
23630b57cec5SDimitry Andric
23640b57cec5SDimitry Andric ExecutionContext exe_ctx(context->exe_ctx_ref);
23650b57cec5SDimitry Andric Target *target = exe_ctx.GetTargetPtr();
23660b57cec5SDimitry Andric
23670b57cec5SDimitry Andric if (!target)
23680b57cec5SDimitry Andric return true;
23690b57cec5SDimitry Andric
23700b57cec5SDimitry Andric Debugger &debugger = target->GetDebugger();
23710b57cec5SDimitry Andric ScriptInterpreterPythonImpl *python_interpreter =
2372af732203SDimitry Andric GetPythonInterpreter(debugger);
23730b57cec5SDimitry Andric
2374af732203SDimitry Andric if (!python_interpreter)
23750b57cec5SDimitry Andric return true;
23760b57cec5SDimitry Andric
23770b57cec5SDimitry Andric if (python_function_name && python_function_name[0]) {
23780b57cec5SDimitry Andric const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
23790b57cec5SDimitry Andric WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
23800b57cec5SDimitry Andric if (wp_sp) {
23810b57cec5SDimitry Andric if (stop_frame_sp && wp_sp) {
23820b57cec5SDimitry Andric bool ret_val = true;
23830b57cec5SDimitry Andric {
23840b57cec5SDimitry Andric Locker py_lock(python_interpreter, Locker::AcquireLock |
23850b57cec5SDimitry Andric Locker::InitSession |
23860b57cec5SDimitry Andric Locker::NoSTDIN);
23870b57cec5SDimitry Andric ret_val = LLDBSwigPythonWatchpointCallbackFunction(
23880b57cec5SDimitry Andric python_function_name,
23890b57cec5SDimitry Andric python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
23900b57cec5SDimitry Andric wp_sp);
23910b57cec5SDimitry Andric }
23920b57cec5SDimitry Andric return ret_val;
23930b57cec5SDimitry Andric }
23940b57cec5SDimitry Andric }
23950b57cec5SDimitry Andric }
23960b57cec5SDimitry Andric // We currently always true so we stop in case anything goes wrong when
23970b57cec5SDimitry Andric // trying to call the script function
23980b57cec5SDimitry Andric return true;
23990b57cec5SDimitry Andric }
24000b57cec5SDimitry Andric
CalculateNumChildren(const StructuredData::ObjectSP & implementor_sp,uint32_t max)24010b57cec5SDimitry Andric size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
24020b57cec5SDimitry Andric const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
24030b57cec5SDimitry Andric if (!implementor_sp)
24040b57cec5SDimitry Andric return 0;
24050b57cec5SDimitry Andric StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24060b57cec5SDimitry Andric if (!generic)
24070b57cec5SDimitry Andric return 0;
24080b57cec5SDimitry Andric void *implementor = generic->GetValue();
24090b57cec5SDimitry Andric if (!implementor)
24100b57cec5SDimitry Andric return 0;
24110b57cec5SDimitry Andric
24120b57cec5SDimitry Andric size_t ret_val = 0;
24130b57cec5SDimitry Andric
24140b57cec5SDimitry Andric {
24150b57cec5SDimitry Andric Locker py_lock(this,
24160b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
24170b57cec5SDimitry Andric ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max);
24180b57cec5SDimitry Andric }
24190b57cec5SDimitry Andric
24200b57cec5SDimitry Andric return ret_val;
24210b57cec5SDimitry Andric }
24220b57cec5SDimitry Andric
GetChildAtIndex(const StructuredData::ObjectSP & implementor_sp,uint32_t idx)24230b57cec5SDimitry Andric lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
24240b57cec5SDimitry Andric const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
24250b57cec5SDimitry Andric if (!implementor_sp)
24260b57cec5SDimitry Andric return lldb::ValueObjectSP();
24270b57cec5SDimitry Andric
24280b57cec5SDimitry Andric StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24290b57cec5SDimitry Andric if (!generic)
24300b57cec5SDimitry Andric return lldb::ValueObjectSP();
24310b57cec5SDimitry Andric void *implementor = generic->GetValue();
24320b57cec5SDimitry Andric if (!implementor)
24330b57cec5SDimitry Andric return lldb::ValueObjectSP();
24340b57cec5SDimitry Andric
24350b57cec5SDimitry Andric lldb::ValueObjectSP ret_val;
24360b57cec5SDimitry Andric {
24370b57cec5SDimitry Andric Locker py_lock(this,
24380b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
24390b57cec5SDimitry Andric void *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx);
24400b57cec5SDimitry Andric if (child_ptr != nullptr && child_ptr != Py_None) {
24410b57cec5SDimitry Andric lldb::SBValue *sb_value_ptr =
24420b57cec5SDimitry Andric (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
24430b57cec5SDimitry Andric if (sb_value_ptr == nullptr)
24440b57cec5SDimitry Andric Py_XDECREF(child_ptr);
24450b57cec5SDimitry Andric else
24460b57cec5SDimitry Andric ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
24470b57cec5SDimitry Andric } else {
24480b57cec5SDimitry Andric Py_XDECREF(child_ptr);
24490b57cec5SDimitry Andric }
24500b57cec5SDimitry Andric }
24510b57cec5SDimitry Andric
24520b57cec5SDimitry Andric return ret_val;
24530b57cec5SDimitry Andric }
24540b57cec5SDimitry Andric
GetIndexOfChildWithName(const StructuredData::ObjectSP & implementor_sp,const char * child_name)24550b57cec5SDimitry Andric int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
24560b57cec5SDimitry Andric const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
24570b57cec5SDimitry Andric if (!implementor_sp)
24580b57cec5SDimitry Andric return UINT32_MAX;
24590b57cec5SDimitry Andric
24600b57cec5SDimitry Andric StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24610b57cec5SDimitry Andric if (!generic)
24620b57cec5SDimitry Andric return UINT32_MAX;
24630b57cec5SDimitry Andric void *implementor = generic->GetValue();
24640b57cec5SDimitry Andric if (!implementor)
24650b57cec5SDimitry Andric return UINT32_MAX;
24660b57cec5SDimitry Andric
24670b57cec5SDimitry Andric int ret_val = UINT32_MAX;
24680b57cec5SDimitry Andric
24690b57cec5SDimitry Andric {
24700b57cec5SDimitry Andric Locker py_lock(this,
24710b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
24720b57cec5SDimitry Andric ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
24730b57cec5SDimitry Andric }
24740b57cec5SDimitry Andric
24750b57cec5SDimitry Andric return ret_val;
24760b57cec5SDimitry Andric }
24770b57cec5SDimitry Andric
UpdateSynthProviderInstance(const StructuredData::ObjectSP & implementor_sp)24780b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
24790b57cec5SDimitry Andric const StructuredData::ObjectSP &implementor_sp) {
24800b57cec5SDimitry Andric bool ret_val = false;
24810b57cec5SDimitry Andric
24820b57cec5SDimitry Andric if (!implementor_sp)
24830b57cec5SDimitry Andric return ret_val;
24840b57cec5SDimitry Andric
24850b57cec5SDimitry Andric StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
24860b57cec5SDimitry Andric if (!generic)
24870b57cec5SDimitry Andric return ret_val;
24880b57cec5SDimitry Andric void *implementor = generic->GetValue();
24890b57cec5SDimitry Andric if (!implementor)
24900b57cec5SDimitry Andric return ret_val;
24910b57cec5SDimitry Andric
24920b57cec5SDimitry Andric {
24930b57cec5SDimitry Andric Locker py_lock(this,
24940b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
24950b57cec5SDimitry Andric ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor);
24960b57cec5SDimitry Andric }
24970b57cec5SDimitry Andric
24980b57cec5SDimitry Andric return ret_val;
24990b57cec5SDimitry Andric }
25000b57cec5SDimitry Andric
MightHaveChildrenSynthProviderInstance(const StructuredData::ObjectSP & implementor_sp)25010b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
25020b57cec5SDimitry Andric const StructuredData::ObjectSP &implementor_sp) {
25030b57cec5SDimitry Andric bool ret_val = false;
25040b57cec5SDimitry Andric
25050b57cec5SDimitry Andric if (!implementor_sp)
25060b57cec5SDimitry Andric return ret_val;
25070b57cec5SDimitry Andric
25080b57cec5SDimitry Andric StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
25090b57cec5SDimitry Andric if (!generic)
25100b57cec5SDimitry Andric return ret_val;
25110b57cec5SDimitry Andric void *implementor = generic->GetValue();
25120b57cec5SDimitry Andric if (!implementor)
25130b57cec5SDimitry Andric return ret_val;
25140b57cec5SDimitry Andric
25150b57cec5SDimitry Andric {
25160b57cec5SDimitry Andric Locker py_lock(this,
25170b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
25180b57cec5SDimitry Andric ret_val =
25190b57cec5SDimitry Andric LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor);
25200b57cec5SDimitry Andric }
25210b57cec5SDimitry Andric
25220b57cec5SDimitry Andric return ret_val;
25230b57cec5SDimitry Andric }
25240b57cec5SDimitry Andric
GetSyntheticValue(const StructuredData::ObjectSP & implementor_sp)25250b57cec5SDimitry Andric lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
25260b57cec5SDimitry Andric const StructuredData::ObjectSP &implementor_sp) {
25270b57cec5SDimitry Andric lldb::ValueObjectSP ret_val(nullptr);
25280b57cec5SDimitry Andric
25290b57cec5SDimitry Andric if (!implementor_sp)
25300b57cec5SDimitry Andric return ret_val;
25310b57cec5SDimitry Andric
25320b57cec5SDimitry Andric StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
25330b57cec5SDimitry Andric if (!generic)
25340b57cec5SDimitry Andric return ret_val;
25350b57cec5SDimitry Andric void *implementor = generic->GetValue();
25360b57cec5SDimitry Andric if (!implementor)
25370b57cec5SDimitry Andric return ret_val;
25380b57cec5SDimitry Andric
25390b57cec5SDimitry Andric {
25400b57cec5SDimitry Andric Locker py_lock(this,
25410b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
25420b57cec5SDimitry Andric void *child_ptr = LLDBSwigPython_GetValueSynthProviderInstance(implementor);
25430b57cec5SDimitry Andric if (child_ptr != nullptr && child_ptr != Py_None) {
25440b57cec5SDimitry Andric lldb::SBValue *sb_value_ptr =
25450b57cec5SDimitry Andric (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
25460b57cec5SDimitry Andric if (sb_value_ptr == nullptr)
25470b57cec5SDimitry Andric Py_XDECREF(child_ptr);
25480b57cec5SDimitry Andric else
25490b57cec5SDimitry Andric ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
25500b57cec5SDimitry Andric } else {
25510b57cec5SDimitry Andric Py_XDECREF(child_ptr);
25520b57cec5SDimitry Andric }
25530b57cec5SDimitry Andric }
25540b57cec5SDimitry Andric
25550b57cec5SDimitry Andric return ret_val;
25560b57cec5SDimitry Andric }
25570b57cec5SDimitry Andric
GetSyntheticTypeName(const StructuredData::ObjectSP & implementor_sp)25580b57cec5SDimitry Andric ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
25590b57cec5SDimitry Andric const StructuredData::ObjectSP &implementor_sp) {
25600b57cec5SDimitry Andric Locker py_lock(this,
25610b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
25620b57cec5SDimitry Andric
25630b57cec5SDimitry Andric static char callee_name[] = "get_type_name";
25640b57cec5SDimitry Andric
25650b57cec5SDimitry Andric ConstString ret_val;
25660b57cec5SDimitry Andric bool got_string = false;
25670b57cec5SDimitry Andric std::string buffer;
25680b57cec5SDimitry Andric
25690b57cec5SDimitry Andric if (!implementor_sp)
25700b57cec5SDimitry Andric return ret_val;
25710b57cec5SDimitry Andric
25720b57cec5SDimitry Andric StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
25730b57cec5SDimitry Andric if (!generic)
25740b57cec5SDimitry Andric return ret_val;
25750b57cec5SDimitry Andric PythonObject implementor(PyRefType::Borrowed,
25760b57cec5SDimitry Andric (PyObject *)generic->GetValue());
25770b57cec5SDimitry Andric if (!implementor.IsAllocated())
25780b57cec5SDimitry Andric return ret_val;
25790b57cec5SDimitry Andric
25800b57cec5SDimitry Andric PythonObject pmeth(PyRefType::Owned,
25810b57cec5SDimitry Andric PyObject_GetAttrString(implementor.get(), callee_name));
25820b57cec5SDimitry Andric
25830b57cec5SDimitry Andric if (PyErr_Occurred())
25840b57cec5SDimitry Andric PyErr_Clear();
25850b57cec5SDimitry Andric
25860b57cec5SDimitry Andric if (!pmeth.IsAllocated())
25870b57cec5SDimitry Andric return ret_val;
25880b57cec5SDimitry Andric
25890b57cec5SDimitry Andric if (PyCallable_Check(pmeth.get()) == 0) {
25900b57cec5SDimitry Andric if (PyErr_Occurred())
25910b57cec5SDimitry Andric PyErr_Clear();
25920b57cec5SDimitry Andric return ret_val;
25930b57cec5SDimitry Andric }
25940b57cec5SDimitry Andric
25950b57cec5SDimitry Andric if (PyErr_Occurred())
25960b57cec5SDimitry Andric PyErr_Clear();
25970b57cec5SDimitry Andric
25980b57cec5SDimitry Andric // right now we know this function exists and is callable..
25990b57cec5SDimitry Andric PythonObject py_return(
26000b57cec5SDimitry Andric PyRefType::Owned,
26010b57cec5SDimitry Andric PyObject_CallMethod(implementor.get(), callee_name, nullptr));
26020b57cec5SDimitry Andric
26030b57cec5SDimitry Andric // if it fails, print the error but otherwise go on
26040b57cec5SDimitry Andric if (PyErr_Occurred()) {
26050b57cec5SDimitry Andric PyErr_Print();
26060b57cec5SDimitry Andric PyErr_Clear();
26070b57cec5SDimitry Andric }
26080b57cec5SDimitry Andric
26090b57cec5SDimitry Andric if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
26100b57cec5SDimitry Andric PythonString py_string(PyRefType::Borrowed, py_return.get());
26110b57cec5SDimitry Andric llvm::StringRef return_data(py_string.GetString());
26120b57cec5SDimitry Andric if (!return_data.empty()) {
26130b57cec5SDimitry Andric buffer.assign(return_data.data(), return_data.size());
26140b57cec5SDimitry Andric got_string = true;
26150b57cec5SDimitry Andric }
26160b57cec5SDimitry Andric }
26170b57cec5SDimitry Andric
26180b57cec5SDimitry Andric if (got_string)
26190b57cec5SDimitry Andric ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
26200b57cec5SDimitry Andric
26210b57cec5SDimitry Andric return ret_val;
26220b57cec5SDimitry Andric }
26230b57cec5SDimitry Andric
RunScriptFormatKeyword(const char * impl_function,Process * process,std::string & output,Status & error)26240b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
26250b57cec5SDimitry Andric const char *impl_function, Process *process, std::string &output,
26260b57cec5SDimitry Andric Status &error) {
26270b57cec5SDimitry Andric bool ret_val;
26280b57cec5SDimitry Andric if (!process) {
26290b57cec5SDimitry Andric error.SetErrorString("no process");
26300b57cec5SDimitry Andric return false;
26310b57cec5SDimitry Andric }
26320b57cec5SDimitry Andric if (!impl_function || !impl_function[0]) {
26330b57cec5SDimitry Andric error.SetErrorString("no function to execute");
26340b57cec5SDimitry Andric return false;
26350b57cec5SDimitry Andric }
26360b57cec5SDimitry Andric
26370b57cec5SDimitry Andric {
26380b57cec5SDimitry Andric ProcessSP process_sp(process->shared_from_this());
26390b57cec5SDimitry Andric Locker py_lock(this,
26400b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
26410b57cec5SDimitry Andric ret_val = LLDBSWIGPythonRunScriptKeywordProcess(
26420b57cec5SDimitry Andric impl_function, m_dictionary_name.c_str(), process_sp, output);
26430b57cec5SDimitry Andric if (!ret_val)
26440b57cec5SDimitry Andric error.SetErrorString("python script evaluation failed");
26450b57cec5SDimitry Andric }
26460b57cec5SDimitry Andric return ret_val;
26470b57cec5SDimitry Andric }
26480b57cec5SDimitry Andric
RunScriptFormatKeyword(const char * impl_function,Thread * thread,std::string & output,Status & error)26490b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
26500b57cec5SDimitry Andric const char *impl_function, Thread *thread, std::string &output,
26510b57cec5SDimitry Andric Status &error) {
26520b57cec5SDimitry Andric bool ret_val;
26530b57cec5SDimitry Andric if (!thread) {
26540b57cec5SDimitry Andric error.SetErrorString("no thread");
26550b57cec5SDimitry Andric return false;
26560b57cec5SDimitry Andric }
26570b57cec5SDimitry Andric if (!impl_function || !impl_function[0]) {
26580b57cec5SDimitry Andric error.SetErrorString("no function to execute");
26590b57cec5SDimitry Andric return false;
26600b57cec5SDimitry Andric }
26610b57cec5SDimitry Andric
26620b57cec5SDimitry Andric {
26630b57cec5SDimitry Andric ThreadSP thread_sp(thread->shared_from_this());
26640b57cec5SDimitry Andric Locker py_lock(this,
26650b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
26660b57cec5SDimitry Andric ret_val = LLDBSWIGPythonRunScriptKeywordThread(
26670b57cec5SDimitry Andric impl_function, m_dictionary_name.c_str(), thread_sp, output);
26680b57cec5SDimitry Andric if (!ret_val)
26690b57cec5SDimitry Andric error.SetErrorString("python script evaluation failed");
26700b57cec5SDimitry Andric }
26710b57cec5SDimitry Andric return ret_val;
26720b57cec5SDimitry Andric }
26730b57cec5SDimitry Andric
RunScriptFormatKeyword(const char * impl_function,Target * target,std::string & output,Status & error)26740b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
26750b57cec5SDimitry Andric const char *impl_function, Target *target, std::string &output,
26760b57cec5SDimitry Andric Status &error) {
26770b57cec5SDimitry Andric bool ret_val;
26780b57cec5SDimitry Andric if (!target) {
26790b57cec5SDimitry Andric error.SetErrorString("no thread");
26800b57cec5SDimitry Andric return false;
26810b57cec5SDimitry Andric }
26820b57cec5SDimitry Andric if (!impl_function || !impl_function[0]) {
26830b57cec5SDimitry Andric error.SetErrorString("no function to execute");
26840b57cec5SDimitry Andric return false;
26850b57cec5SDimitry Andric }
26860b57cec5SDimitry Andric
26870b57cec5SDimitry Andric {
26880b57cec5SDimitry Andric TargetSP target_sp(target->shared_from_this());
26890b57cec5SDimitry Andric Locker py_lock(this,
26900b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
26910b57cec5SDimitry Andric ret_val = LLDBSWIGPythonRunScriptKeywordTarget(
26920b57cec5SDimitry Andric impl_function, m_dictionary_name.c_str(), target_sp, output);
26930b57cec5SDimitry Andric if (!ret_val)
26940b57cec5SDimitry Andric error.SetErrorString("python script evaluation failed");
26950b57cec5SDimitry Andric }
26960b57cec5SDimitry Andric return ret_val;
26970b57cec5SDimitry Andric }
26980b57cec5SDimitry Andric
RunScriptFormatKeyword(const char * impl_function,StackFrame * frame,std::string & output,Status & error)26990b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
27000b57cec5SDimitry Andric const char *impl_function, StackFrame *frame, std::string &output,
27010b57cec5SDimitry Andric Status &error) {
27020b57cec5SDimitry Andric bool ret_val;
27030b57cec5SDimitry Andric if (!frame) {
27040b57cec5SDimitry Andric error.SetErrorString("no frame");
27050b57cec5SDimitry Andric return false;
27060b57cec5SDimitry Andric }
27070b57cec5SDimitry Andric if (!impl_function || !impl_function[0]) {
27080b57cec5SDimitry Andric error.SetErrorString("no function to execute");
27090b57cec5SDimitry Andric return false;
27100b57cec5SDimitry Andric }
27110b57cec5SDimitry Andric
27120b57cec5SDimitry Andric {
27130b57cec5SDimitry Andric StackFrameSP frame_sp(frame->shared_from_this());
27140b57cec5SDimitry Andric Locker py_lock(this,
27150b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
27160b57cec5SDimitry Andric ret_val = LLDBSWIGPythonRunScriptKeywordFrame(
27170b57cec5SDimitry Andric impl_function, m_dictionary_name.c_str(), frame_sp, output);
27180b57cec5SDimitry Andric if (!ret_val)
27190b57cec5SDimitry Andric error.SetErrorString("python script evaluation failed");
27200b57cec5SDimitry Andric }
27210b57cec5SDimitry Andric return ret_val;
27220b57cec5SDimitry Andric }
27230b57cec5SDimitry Andric
RunScriptFormatKeyword(const char * impl_function,ValueObject * value,std::string & output,Status & error)27240b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
27250b57cec5SDimitry Andric const char *impl_function, ValueObject *value, std::string &output,
27260b57cec5SDimitry Andric Status &error) {
27270b57cec5SDimitry Andric bool ret_val;
27280b57cec5SDimitry Andric if (!value) {
27290b57cec5SDimitry Andric error.SetErrorString("no value");
27300b57cec5SDimitry Andric return false;
27310b57cec5SDimitry Andric }
27320b57cec5SDimitry Andric if (!impl_function || !impl_function[0]) {
27330b57cec5SDimitry Andric error.SetErrorString("no function to execute");
27340b57cec5SDimitry Andric return false;
27350b57cec5SDimitry Andric }
27360b57cec5SDimitry Andric
27370b57cec5SDimitry Andric {
27380b57cec5SDimitry Andric ValueObjectSP value_sp(value->GetSP());
27390b57cec5SDimitry Andric Locker py_lock(this,
27400b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
27410b57cec5SDimitry Andric ret_val = LLDBSWIGPythonRunScriptKeywordValue(
27420b57cec5SDimitry Andric impl_function, m_dictionary_name.c_str(), value_sp, output);
27430b57cec5SDimitry Andric if (!ret_val)
27440b57cec5SDimitry Andric error.SetErrorString("python script evaluation failed");
27450b57cec5SDimitry Andric }
27460b57cec5SDimitry Andric return ret_val;
27470b57cec5SDimitry Andric }
27480b57cec5SDimitry Andric
replace_all(std::string & str,const std::string & oldStr,const std::string & newStr)27490b57cec5SDimitry Andric uint64_t replace_all(std::string &str, const std::string &oldStr,
27500b57cec5SDimitry Andric const std::string &newStr) {
27510b57cec5SDimitry Andric size_t pos = 0;
27520b57cec5SDimitry Andric uint64_t matches = 0;
27530b57cec5SDimitry Andric while ((pos = str.find(oldStr, pos)) != std::string::npos) {
27540b57cec5SDimitry Andric matches++;
27550b57cec5SDimitry Andric str.replace(pos, oldStr.length(), newStr);
27560b57cec5SDimitry Andric pos += newStr.length();
27570b57cec5SDimitry Andric }
27580b57cec5SDimitry Andric return matches;
27590b57cec5SDimitry Andric }
27600b57cec5SDimitry Andric
LoadScriptingModule(const char * pathname,const LoadScriptOptions & options,lldb_private::Status & error,StructuredData::ObjectSP * module_sp,FileSpec extra_search_dir)27610b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2762*5f7ddb14SDimitry Andric const char *pathname, const LoadScriptOptions &options,
2763*5f7ddb14SDimitry Andric lldb_private::Status &error, StructuredData::ObjectSP *module_sp,
2764*5f7ddb14SDimitry Andric FileSpec extra_search_dir) {
2765af732203SDimitry Andric namespace fs = llvm::sys::fs;
2766af732203SDimitry Andric namespace path = llvm::sys::path;
2767af732203SDimitry Andric
2768*5f7ddb14SDimitry Andric ExecuteScriptOptions exc_options = ExecuteScriptOptions()
2769*5f7ddb14SDimitry Andric .SetEnableIO(!options.GetSilent())
2770*5f7ddb14SDimitry Andric .SetSetLLDBGlobals(false);
2771*5f7ddb14SDimitry Andric
27720b57cec5SDimitry Andric if (!pathname || !pathname[0]) {
27730b57cec5SDimitry Andric error.SetErrorString("invalid pathname");
27740b57cec5SDimitry Andric return false;
27750b57cec5SDimitry Andric }
27760b57cec5SDimitry Andric
2777*5f7ddb14SDimitry Andric llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2778*5f7ddb14SDimitry Andric io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2779*5f7ddb14SDimitry Andric exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2780*5f7ddb14SDimitry Andric
2781*5f7ddb14SDimitry Andric if (!io_redirect_or_error) {
2782*5f7ddb14SDimitry Andric error = io_redirect_or_error.takeError();
2783*5f7ddb14SDimitry Andric return false;
2784*5f7ddb14SDimitry Andric }
2785*5f7ddb14SDimitry Andric
2786*5f7ddb14SDimitry Andric ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
27870b57cec5SDimitry Andric lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
27880b57cec5SDimitry Andric
27890b57cec5SDimitry Andric // Before executing Python code, lock the GIL.
27900b57cec5SDimitry Andric Locker py_lock(this,
27910b57cec5SDimitry Andric Locker::AcquireLock |
2792*5f7ddb14SDimitry Andric (options.GetInitSession() ? Locker::InitSession : 0) |
2793*5f7ddb14SDimitry Andric Locker::NoSTDIN,
27940b57cec5SDimitry Andric Locker::FreeAcquiredLock |
2795*5f7ddb14SDimitry Andric (options.GetInitSession() ? Locker::TearDownSession : 0),
2796*5f7ddb14SDimitry Andric io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2797*5f7ddb14SDimitry Andric io_redirect.GetErrorFile());
27980b57cec5SDimitry Andric
2799*5f7ddb14SDimitry Andric auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2800af732203SDimitry Andric if (directory.empty()) {
2801af732203SDimitry Andric return llvm::make_error<llvm::StringError>(
2802af732203SDimitry Andric "invalid directory name", llvm::inconvertibleErrorCode());
28030b57cec5SDimitry Andric }
28040b57cec5SDimitry Andric
28050b57cec5SDimitry Andric replace_all(directory, "\\", "\\\\");
28060b57cec5SDimitry Andric replace_all(directory, "'", "\\'");
28070b57cec5SDimitry Andric
2808af732203SDimitry Andric // Make sure that Python has "directory" in the search path.
28090b57cec5SDimitry Andric StreamString command_stream;
28100b57cec5SDimitry Andric command_stream.Printf("if not (sys.path.__contains__('%s')):\n "
28110b57cec5SDimitry Andric "sys.path.insert(1,'%s');\n\n",
28120b57cec5SDimitry Andric directory.c_str(), directory.c_str());
28130b57cec5SDimitry Andric bool syspath_retval =
2814*5f7ddb14SDimitry Andric ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
28150b57cec5SDimitry Andric if (!syspath_retval) {
2816af732203SDimitry Andric return llvm::make_error<llvm::StringError>(
2817af732203SDimitry Andric "Python sys.path handling failed", llvm::inconvertibleErrorCode());
28180b57cec5SDimitry Andric }
28190b57cec5SDimitry Andric
2820af732203SDimitry Andric return llvm::Error::success();
2821af732203SDimitry Andric };
2822af732203SDimitry Andric
2823af732203SDimitry Andric std::string module_name(pathname);
2824*5f7ddb14SDimitry Andric bool possible_package = false;
2825af732203SDimitry Andric
2826af732203SDimitry Andric if (extra_search_dir) {
2827af732203SDimitry Andric if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2828af732203SDimitry Andric error = std::move(e);
2829af732203SDimitry Andric return false;
28300b57cec5SDimitry Andric }
28310b57cec5SDimitry Andric } else {
2832af732203SDimitry Andric FileSpec module_file(pathname);
2833af732203SDimitry Andric FileSystem::Instance().Resolve(module_file);
2834af732203SDimitry Andric FileSystem::Instance().Collect(module_file);
2835af732203SDimitry Andric
2836af732203SDimitry Andric fs::file_status st;
2837af732203SDimitry Andric std::error_code ec = status(module_file.GetPath(), st);
2838af732203SDimitry Andric
2839af732203SDimitry Andric if (ec || st.type() == fs::file_type::status_error ||
2840af732203SDimitry Andric st.type() == fs::file_type::type_unknown ||
2841af732203SDimitry Andric st.type() == fs::file_type::file_not_found) {
2842af732203SDimitry Andric // if not a valid file of any sort, check if it might be a filename still
2843af732203SDimitry Andric // dot can't be used but / and \ can, and if either is found, reject
2844af732203SDimitry Andric if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2845af732203SDimitry Andric error.SetErrorString("invalid pathname");
2846af732203SDimitry Andric return false;
2847af732203SDimitry Andric }
2848af732203SDimitry Andric // Not a filename, probably a package of some sort, let it go through.
2849*5f7ddb14SDimitry Andric possible_package = true;
2850af732203SDimitry Andric } else if (is_directory(st) || is_regular_file(st)) {
2851af732203SDimitry Andric if (module_file.GetDirectory().IsEmpty()) {
2852af732203SDimitry Andric error.SetErrorString("invalid directory name");
2853af732203SDimitry Andric return false;
2854af732203SDimitry Andric }
2855af732203SDimitry Andric if (llvm::Error e =
2856af732203SDimitry Andric ExtendSysPath(module_file.GetDirectory().GetCString())) {
2857af732203SDimitry Andric error = std::move(e);
2858af732203SDimitry Andric return false;
2859af732203SDimitry Andric }
2860af732203SDimitry Andric module_name = module_file.GetFilename().GetCString();
2861af732203SDimitry Andric } else {
28620b57cec5SDimitry Andric error.SetErrorString("no known way to import this module specification");
28630b57cec5SDimitry Andric return false;
28640b57cec5SDimitry Andric }
2865af732203SDimitry Andric }
2866af732203SDimitry Andric
2867af732203SDimitry Andric // Strip .py or .pyc extension
2868af732203SDimitry Andric llvm::StringRef extension = llvm::sys::path::extension(module_name);
2869af732203SDimitry Andric if (!extension.empty()) {
2870af732203SDimitry Andric if (extension == ".py")
2871af732203SDimitry Andric module_name.resize(module_name.length() - 3);
2872af732203SDimitry Andric else if (extension == ".pyc")
2873af732203SDimitry Andric module_name.resize(module_name.length() - 4);
2874af732203SDimitry Andric }
28750b57cec5SDimitry Andric
2876*5f7ddb14SDimitry Andric if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2877*5f7ddb14SDimitry Andric error.SetErrorStringWithFormat(
2878*5f7ddb14SDimitry Andric "Python does not allow dots in module names: %s", module_name.c_str());
2879*5f7ddb14SDimitry Andric return false;
2880*5f7ddb14SDimitry Andric }
2881*5f7ddb14SDimitry Andric
2882*5f7ddb14SDimitry Andric if (module_name.find('-') != llvm::StringRef::npos) {
2883*5f7ddb14SDimitry Andric error.SetErrorStringWithFormat(
2884*5f7ddb14SDimitry Andric "Python discourages dashes in module names: %s", module_name.c_str());
2885*5f7ddb14SDimitry Andric return false;
2886*5f7ddb14SDimitry Andric }
2887*5f7ddb14SDimitry Andric
2888*5f7ddb14SDimitry Andric // Check if the module is already imported.
2889af732203SDimitry Andric StreamString command_stream;
28900b57cec5SDimitry Andric command_stream.Clear();
2891af732203SDimitry Andric command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
28920b57cec5SDimitry Andric bool does_contain = false;
2893*5f7ddb14SDimitry Andric // This call will succeed if the module was ever imported in any Debugger in
2894*5f7ddb14SDimitry Andric // the lifetime of the process in which this LLDB framework is living.
2895*5f7ddb14SDimitry Andric const bool does_contain_executed = ExecuteOneLineWithReturn(
28960b57cec5SDimitry Andric command_stream.GetData(),
2897*5f7ddb14SDimitry Andric ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options);
2898*5f7ddb14SDimitry Andric
2899*5f7ddb14SDimitry Andric const bool was_imported_globally = does_contain_executed && does_contain;
2900*5f7ddb14SDimitry Andric const bool was_imported_locally =
2901*5f7ddb14SDimitry Andric GetSessionDictionary()
2902af732203SDimitry Andric .GetItemForKey(PythonString(module_name))
29030b57cec5SDimitry Andric .IsAllocated();
29040b57cec5SDimitry Andric
29050b57cec5SDimitry Andric // now actually do the import
29060b57cec5SDimitry Andric command_stream.Clear();
29070b57cec5SDimitry Andric
2908*5f7ddb14SDimitry Andric if (was_imported_globally || was_imported_locally) {
29090b57cec5SDimitry Andric if (!was_imported_locally)
2910af732203SDimitry Andric command_stream.Printf("import %s ; reload_module(%s)",
2911af732203SDimitry Andric module_name.c_str(), module_name.c_str());
29120b57cec5SDimitry Andric else
2913af732203SDimitry Andric command_stream.Printf("reload_module(%s)", module_name.c_str());
29140b57cec5SDimitry Andric } else
2915af732203SDimitry Andric command_stream.Printf("import %s", module_name.c_str());
29160b57cec5SDimitry Andric
2917*5f7ddb14SDimitry Andric error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
29180b57cec5SDimitry Andric if (error.Fail())
29190b57cec5SDimitry Andric return false;
29200b57cec5SDimitry Andric
29210b57cec5SDimitry Andric // if we are here, everything worked
29220b57cec5SDimitry Andric // call __lldb_init_module(debugger,dict)
2923af732203SDimitry Andric if (!LLDBSwigPythonCallModuleInit(module_name.c_str(),
29240b57cec5SDimitry Andric m_dictionary_name.c_str(), debugger_sp)) {
29250b57cec5SDimitry Andric error.SetErrorString("calling __lldb_init_module failed");
29260b57cec5SDimitry Andric return false;
29270b57cec5SDimitry Andric }
29280b57cec5SDimitry Andric
29290b57cec5SDimitry Andric if (module_sp) {
29300b57cec5SDimitry Andric // everything went just great, now set the module object
29310b57cec5SDimitry Andric command_stream.Clear();
2932af732203SDimitry Andric command_stream.Printf("%s", module_name.c_str());
29330b57cec5SDimitry Andric void *module_pyobj = nullptr;
29340b57cec5SDimitry Andric if (ExecuteOneLineWithReturn(
29350b57cec5SDimitry Andric command_stream.GetData(),
2936*5f7ddb14SDimitry Andric ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2937*5f7ddb14SDimitry Andric exc_options) &&
29380b57cec5SDimitry Andric module_pyobj)
29390b57cec5SDimitry Andric *module_sp = std::make_shared<StructuredPythonObject>(module_pyobj);
29400b57cec5SDimitry Andric }
29410b57cec5SDimitry Andric
29420b57cec5SDimitry Andric return true;
29430b57cec5SDimitry Andric }
29440b57cec5SDimitry Andric
IsReservedWord(const char * word)29450b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
29460b57cec5SDimitry Andric if (!word || !word[0])
29470b57cec5SDimitry Andric return false;
29480b57cec5SDimitry Andric
29490b57cec5SDimitry Andric llvm::StringRef word_sr(word);
29500b57cec5SDimitry Andric
29510b57cec5SDimitry Andric // filter out a few characters that would just confuse us and that are
29520b57cec5SDimitry Andric // clearly not keyword material anyway
29530b57cec5SDimitry Andric if (word_sr.find('"') != llvm::StringRef::npos ||
29540b57cec5SDimitry Andric word_sr.find('\'') != llvm::StringRef::npos)
29550b57cec5SDimitry Andric return false;
29560b57cec5SDimitry Andric
29570b57cec5SDimitry Andric StreamString command_stream;
29580b57cec5SDimitry Andric command_stream.Printf("keyword.iskeyword('%s')", word);
29590b57cec5SDimitry Andric bool result;
29600b57cec5SDimitry Andric ExecuteScriptOptions options;
29610b57cec5SDimitry Andric options.SetEnableIO(false);
29620b57cec5SDimitry Andric options.SetMaskoutErrors(true);
29630b57cec5SDimitry Andric options.SetSetLLDBGlobals(false);
29640b57cec5SDimitry Andric if (ExecuteOneLineWithReturn(command_stream.GetData(),
29650b57cec5SDimitry Andric ScriptInterpreter::eScriptReturnTypeBool,
29660b57cec5SDimitry Andric &result, options))
29670b57cec5SDimitry Andric return result;
29680b57cec5SDimitry Andric return false;
29690b57cec5SDimitry Andric }
29700b57cec5SDimitry Andric
SynchronicityHandler(lldb::DebuggerSP debugger_sp,ScriptedCommandSynchronicity synchro)29710b57cec5SDimitry Andric ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
29720b57cec5SDimitry Andric lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
29730b57cec5SDimitry Andric : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
29740b57cec5SDimitry Andric m_old_asynch(debugger_sp->GetAsyncExecution()) {
29750b57cec5SDimitry Andric if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
29760b57cec5SDimitry Andric m_debugger_sp->SetAsyncExecution(false);
29770b57cec5SDimitry Andric else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
29780b57cec5SDimitry Andric m_debugger_sp->SetAsyncExecution(true);
29790b57cec5SDimitry Andric }
29800b57cec5SDimitry Andric
~SynchronicityHandler()29810b57cec5SDimitry Andric ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
29820b57cec5SDimitry Andric if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
29830b57cec5SDimitry Andric m_debugger_sp->SetAsyncExecution(m_old_asynch);
29840b57cec5SDimitry Andric }
29850b57cec5SDimitry Andric
RunScriptBasedCommand(const char * impl_function,llvm::StringRef args,ScriptedCommandSynchronicity synchronicity,lldb_private::CommandReturnObject & cmd_retobj,Status & error,const lldb_private::ExecutionContext & exe_ctx)29860b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
29870b57cec5SDimitry Andric const char *impl_function, llvm::StringRef args,
29880b57cec5SDimitry Andric ScriptedCommandSynchronicity synchronicity,
29890b57cec5SDimitry Andric lldb_private::CommandReturnObject &cmd_retobj, Status &error,
29900b57cec5SDimitry Andric const lldb_private::ExecutionContext &exe_ctx) {
29910b57cec5SDimitry Andric if (!impl_function) {
29920b57cec5SDimitry Andric error.SetErrorString("no function to execute");
29930b57cec5SDimitry Andric return false;
29940b57cec5SDimitry Andric }
29950b57cec5SDimitry Andric
29960b57cec5SDimitry Andric lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
29970b57cec5SDimitry Andric lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
29980b57cec5SDimitry Andric
29990b57cec5SDimitry Andric if (!debugger_sp.get()) {
30000b57cec5SDimitry Andric error.SetErrorString("invalid Debugger pointer");
30010b57cec5SDimitry Andric return false;
30020b57cec5SDimitry Andric }
30030b57cec5SDimitry Andric
30040b57cec5SDimitry Andric bool ret_val = false;
30050b57cec5SDimitry Andric
30060b57cec5SDimitry Andric std::string err_msg;
30070b57cec5SDimitry Andric
30080b57cec5SDimitry Andric {
30090b57cec5SDimitry Andric Locker py_lock(this,
30100b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession |
30110b57cec5SDimitry Andric (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
30120b57cec5SDimitry Andric Locker::FreeLock | Locker::TearDownSession);
30130b57cec5SDimitry Andric
30140b57cec5SDimitry Andric SynchronicityHandler synch_handler(debugger_sp, synchronicity);
30150b57cec5SDimitry Andric
30160b57cec5SDimitry Andric std::string args_str = args.str();
30170b57cec5SDimitry Andric ret_val = LLDBSwigPythonCallCommand(
30180b57cec5SDimitry Andric impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
30190b57cec5SDimitry Andric cmd_retobj, exe_ctx_ref_sp);
30200b57cec5SDimitry Andric }
30210b57cec5SDimitry Andric
30220b57cec5SDimitry Andric if (!ret_val)
30230b57cec5SDimitry Andric error.SetErrorString("unable to execute script function");
30240b57cec5SDimitry Andric else
30250b57cec5SDimitry Andric error.Clear();
30260b57cec5SDimitry Andric
30270b57cec5SDimitry Andric return ret_val;
30280b57cec5SDimitry Andric }
30290b57cec5SDimitry Andric
RunScriptBasedCommand(StructuredData::GenericSP impl_obj_sp,llvm::StringRef args,ScriptedCommandSynchronicity synchronicity,lldb_private::CommandReturnObject & cmd_retobj,Status & error,const lldb_private::ExecutionContext & exe_ctx)30300b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
30310b57cec5SDimitry Andric StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
30320b57cec5SDimitry Andric ScriptedCommandSynchronicity synchronicity,
30330b57cec5SDimitry Andric lldb_private::CommandReturnObject &cmd_retobj, Status &error,
30340b57cec5SDimitry Andric const lldb_private::ExecutionContext &exe_ctx) {
30350b57cec5SDimitry Andric if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
30360b57cec5SDimitry Andric error.SetErrorString("no function to execute");
30370b57cec5SDimitry Andric return false;
30380b57cec5SDimitry Andric }
30390b57cec5SDimitry Andric
30400b57cec5SDimitry Andric lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
30410b57cec5SDimitry Andric lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
30420b57cec5SDimitry Andric
30430b57cec5SDimitry Andric if (!debugger_sp.get()) {
30440b57cec5SDimitry Andric error.SetErrorString("invalid Debugger pointer");
30450b57cec5SDimitry Andric return false;
30460b57cec5SDimitry Andric }
30470b57cec5SDimitry Andric
30480b57cec5SDimitry Andric bool ret_val = false;
30490b57cec5SDimitry Andric
30500b57cec5SDimitry Andric std::string err_msg;
30510b57cec5SDimitry Andric
30520b57cec5SDimitry Andric {
30530b57cec5SDimitry Andric Locker py_lock(this,
30540b57cec5SDimitry Andric Locker::AcquireLock | Locker::InitSession |
30550b57cec5SDimitry Andric (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
30560b57cec5SDimitry Andric Locker::FreeLock | Locker::TearDownSession);
30570b57cec5SDimitry Andric
30580b57cec5SDimitry Andric SynchronicityHandler synch_handler(debugger_sp, synchronicity);
30590b57cec5SDimitry Andric
30600b57cec5SDimitry Andric std::string args_str = args.str();
30610b57cec5SDimitry Andric ret_val = LLDBSwigPythonCallCommandObject(impl_obj_sp->GetValue(),
30620b57cec5SDimitry Andric debugger_sp, args_str.c_str(),
30630b57cec5SDimitry Andric cmd_retobj, exe_ctx_ref_sp);
30640b57cec5SDimitry Andric }
30650b57cec5SDimitry Andric
30660b57cec5SDimitry Andric if (!ret_val)
30670b57cec5SDimitry Andric error.SetErrorString("unable to execute script function");
30680b57cec5SDimitry Andric else
30690b57cec5SDimitry Andric error.Clear();
30700b57cec5SDimitry Andric
30710b57cec5SDimitry Andric return ret_val;
30720b57cec5SDimitry Andric }
30730b57cec5SDimitry Andric
30745ffd83dbSDimitry Andric /// In Python, a special attribute __doc__ contains the docstring for an object
30755ffd83dbSDimitry Andric /// (function, method, class, ...) if any is defined Otherwise, the attribute's
30765ffd83dbSDimitry Andric /// value is None.
GetDocumentationForItem(const char * item,std::string & dest)30770b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
30780b57cec5SDimitry Andric std::string &dest) {
30790b57cec5SDimitry Andric dest.clear();
30805ffd83dbSDimitry Andric
30810b57cec5SDimitry Andric if (!item || !*item)
30820b57cec5SDimitry Andric return false;
30835ffd83dbSDimitry Andric
30840b57cec5SDimitry Andric std::string command(item);
30850b57cec5SDimitry Andric command += ".__doc__";
30860b57cec5SDimitry Andric
30875ffd83dbSDimitry Andric // Python is going to point this to valid data if ExecuteOneLineWithReturn
30885ffd83dbSDimitry Andric // returns successfully.
30895ffd83dbSDimitry Andric char *result_ptr = nullptr;
30900b57cec5SDimitry Andric
30910b57cec5SDimitry Andric if (ExecuteOneLineWithReturn(
30925ffd83dbSDimitry Andric command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
30930b57cec5SDimitry Andric &result_ptr,
3094*5f7ddb14SDimitry Andric ExecuteScriptOptions().SetEnableIO(false))) {
30950b57cec5SDimitry Andric if (result_ptr)
30960b57cec5SDimitry Andric dest.assign(result_ptr);
30970b57cec5SDimitry Andric return true;
30980b57cec5SDimitry Andric }
30995ffd83dbSDimitry Andric
31005ffd83dbSDimitry Andric StreamString str_stream;
31015ffd83dbSDimitry Andric str_stream << "Function " << item
31025ffd83dbSDimitry Andric << " was not found. Containing module might be missing.";
31035ffd83dbSDimitry Andric dest = std::string(str_stream.GetString());
31045ffd83dbSDimitry Andric
31055ffd83dbSDimitry Andric return false;
31060b57cec5SDimitry Andric }
31070b57cec5SDimitry Andric
GetShortHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp,std::string & dest)31080b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
31090b57cec5SDimitry Andric StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
31100b57cec5SDimitry Andric dest.clear();
31110b57cec5SDimitry Andric
31120b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
31130b57cec5SDimitry Andric
31140b57cec5SDimitry Andric static char callee_name[] = "get_short_help";
31150b57cec5SDimitry Andric
31160b57cec5SDimitry Andric if (!cmd_obj_sp)
31170b57cec5SDimitry Andric return false;
31180b57cec5SDimitry Andric
31190b57cec5SDimitry Andric PythonObject implementor(PyRefType::Borrowed,
31200b57cec5SDimitry Andric (PyObject *)cmd_obj_sp->GetValue());
31210b57cec5SDimitry Andric
31220b57cec5SDimitry Andric if (!implementor.IsAllocated())
31230b57cec5SDimitry Andric return false;
31240b57cec5SDimitry Andric
31250b57cec5SDimitry Andric PythonObject pmeth(PyRefType::Owned,
31260b57cec5SDimitry Andric PyObject_GetAttrString(implementor.get(), callee_name));
31270b57cec5SDimitry Andric
31280b57cec5SDimitry Andric if (PyErr_Occurred())
31290b57cec5SDimitry Andric PyErr_Clear();
31300b57cec5SDimitry Andric
31310b57cec5SDimitry Andric if (!pmeth.IsAllocated())
31320b57cec5SDimitry Andric return false;
31330b57cec5SDimitry Andric
31340b57cec5SDimitry Andric if (PyCallable_Check(pmeth.get()) == 0) {
31350b57cec5SDimitry Andric if (PyErr_Occurred())
31360b57cec5SDimitry Andric PyErr_Clear();
31370b57cec5SDimitry Andric return false;
31380b57cec5SDimitry Andric }
31390b57cec5SDimitry Andric
31400b57cec5SDimitry Andric if (PyErr_Occurred())
31410b57cec5SDimitry Andric PyErr_Clear();
31420b57cec5SDimitry Andric
31435ffd83dbSDimitry Andric // Right now we know this function exists and is callable.
31440b57cec5SDimitry Andric PythonObject py_return(
31450b57cec5SDimitry Andric PyRefType::Owned,
31460b57cec5SDimitry Andric PyObject_CallMethod(implementor.get(), callee_name, nullptr));
31470b57cec5SDimitry Andric
31485ffd83dbSDimitry Andric // If it fails, print the error but otherwise go on.
31490b57cec5SDimitry Andric if (PyErr_Occurred()) {
31500b57cec5SDimitry Andric PyErr_Print();
31510b57cec5SDimitry Andric PyErr_Clear();
31520b57cec5SDimitry Andric }
31530b57cec5SDimitry Andric
31540b57cec5SDimitry Andric if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
31550b57cec5SDimitry Andric PythonString py_string(PyRefType::Borrowed, py_return.get());
31560b57cec5SDimitry Andric llvm::StringRef return_data(py_string.GetString());
31570b57cec5SDimitry Andric dest.assign(return_data.data(), return_data.size());
31585ffd83dbSDimitry Andric return true;
31590b57cec5SDimitry Andric }
31605ffd83dbSDimitry Andric
31615ffd83dbSDimitry Andric return false;
31620b57cec5SDimitry Andric }
31630b57cec5SDimitry Andric
GetFlagsForCommandObject(StructuredData::GenericSP cmd_obj_sp)31640b57cec5SDimitry Andric uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
31650b57cec5SDimitry Andric StructuredData::GenericSP cmd_obj_sp) {
31660b57cec5SDimitry Andric uint32_t result = 0;
31670b57cec5SDimitry Andric
31680b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
31690b57cec5SDimitry Andric
31700b57cec5SDimitry Andric static char callee_name[] = "get_flags";
31710b57cec5SDimitry Andric
31720b57cec5SDimitry Andric if (!cmd_obj_sp)
31730b57cec5SDimitry Andric return result;
31740b57cec5SDimitry Andric
31750b57cec5SDimitry Andric PythonObject implementor(PyRefType::Borrowed,
31760b57cec5SDimitry Andric (PyObject *)cmd_obj_sp->GetValue());
31770b57cec5SDimitry Andric
31780b57cec5SDimitry Andric if (!implementor.IsAllocated())
31790b57cec5SDimitry Andric return result;
31800b57cec5SDimitry Andric
31810b57cec5SDimitry Andric PythonObject pmeth(PyRefType::Owned,
31820b57cec5SDimitry Andric PyObject_GetAttrString(implementor.get(), callee_name));
31830b57cec5SDimitry Andric
31840b57cec5SDimitry Andric if (PyErr_Occurred())
31850b57cec5SDimitry Andric PyErr_Clear();
31860b57cec5SDimitry Andric
31870b57cec5SDimitry Andric if (!pmeth.IsAllocated())
31880b57cec5SDimitry Andric return result;
31890b57cec5SDimitry Andric
31900b57cec5SDimitry Andric if (PyCallable_Check(pmeth.get()) == 0) {
31910b57cec5SDimitry Andric if (PyErr_Occurred())
31920b57cec5SDimitry Andric PyErr_Clear();
31930b57cec5SDimitry Andric return result;
31940b57cec5SDimitry Andric }
31950b57cec5SDimitry Andric
31960b57cec5SDimitry Andric if (PyErr_Occurred())
31970b57cec5SDimitry Andric PyErr_Clear();
31980b57cec5SDimitry Andric
31995ffd83dbSDimitry Andric long long py_return = unwrapOrSetPythonException(
32005ffd83dbSDimitry Andric As<long long>(implementor.CallMethod(callee_name)));
32010b57cec5SDimitry Andric
32020b57cec5SDimitry Andric // if it fails, print the error but otherwise go on
32030b57cec5SDimitry Andric if (PyErr_Occurred()) {
32040b57cec5SDimitry Andric PyErr_Print();
32050b57cec5SDimitry Andric PyErr_Clear();
32065ffd83dbSDimitry Andric } else {
32075ffd83dbSDimitry Andric result = py_return;
32080b57cec5SDimitry Andric }
32090b57cec5SDimitry Andric
32100b57cec5SDimitry Andric return result;
32110b57cec5SDimitry Andric }
32120b57cec5SDimitry Andric
GetLongHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp,std::string & dest)32130b57cec5SDimitry Andric bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
32140b57cec5SDimitry Andric StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
32150b57cec5SDimitry Andric bool got_string = false;
32160b57cec5SDimitry Andric dest.clear();
32170b57cec5SDimitry Andric
32180b57cec5SDimitry Andric Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
32190b57cec5SDimitry Andric
32200b57cec5SDimitry Andric static char callee_name[] = "get_long_help";
32210b57cec5SDimitry Andric
32220b57cec5SDimitry Andric if (!cmd_obj_sp)
32230b57cec5SDimitry Andric return false;
32240b57cec5SDimitry Andric
32250b57cec5SDimitry Andric PythonObject implementor(PyRefType::Borrowed,
32260b57cec5SDimitry Andric (PyObject *)cmd_obj_sp->GetValue());
32270b57cec5SDimitry Andric
32280b57cec5SDimitry Andric if (!implementor.IsAllocated())
32290b57cec5SDimitry Andric return false;
32300b57cec5SDimitry Andric
32310b57cec5SDimitry Andric PythonObject pmeth(PyRefType::Owned,
32320b57cec5SDimitry Andric PyObject_GetAttrString(implementor.get(), callee_name));
32330b57cec5SDimitry Andric
32340b57cec5SDimitry Andric if (PyErr_Occurred())
32350b57cec5SDimitry Andric PyErr_Clear();
32360b57cec5SDimitry Andric
32370b57cec5SDimitry Andric if (!pmeth.IsAllocated())
32380b57cec5SDimitry Andric return false;
32390b57cec5SDimitry Andric
32400b57cec5SDimitry Andric if (PyCallable_Check(pmeth.get()) == 0) {
32410b57cec5SDimitry Andric if (PyErr_Occurred())
32420b57cec5SDimitry Andric PyErr_Clear();
32430b57cec5SDimitry Andric
32440b57cec5SDimitry Andric return false;
32450b57cec5SDimitry Andric }
32460b57cec5SDimitry Andric
32470b57cec5SDimitry Andric if (PyErr_Occurred())
32480b57cec5SDimitry Andric PyErr_Clear();
32490b57cec5SDimitry Andric
32500b57cec5SDimitry Andric // right now we know this function exists and is callable..
32510b57cec5SDimitry Andric PythonObject py_return(
32520b57cec5SDimitry Andric PyRefType::Owned,
32530b57cec5SDimitry Andric PyObject_CallMethod(implementor.get(), callee_name, nullptr));
32540b57cec5SDimitry Andric
32550b57cec5SDimitry Andric // if it fails, print the error but otherwise go on
32560b57cec5SDimitry Andric if (PyErr_Occurred()) {
32570b57cec5SDimitry Andric PyErr_Print();
32580b57cec5SDimitry Andric PyErr_Clear();
32590b57cec5SDimitry Andric }
32600b57cec5SDimitry Andric
32610b57cec5SDimitry Andric if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
32620b57cec5SDimitry Andric PythonString str(PyRefType::Borrowed, py_return.get());
32630b57cec5SDimitry Andric llvm::StringRef str_data(str.GetString());
32640b57cec5SDimitry Andric dest.assign(str_data.data(), str_data.size());
32650b57cec5SDimitry Andric got_string = true;
32660b57cec5SDimitry Andric }
32670b57cec5SDimitry Andric
32680b57cec5SDimitry Andric return got_string;
32690b57cec5SDimitry Andric }
32700b57cec5SDimitry Andric
32710b57cec5SDimitry Andric std::unique_ptr<ScriptInterpreterLocker>
AcquireInterpreterLock()32720b57cec5SDimitry Andric ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
32730b57cec5SDimitry Andric std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
32740b57cec5SDimitry Andric this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
32750b57cec5SDimitry Andric Locker::FreeLock | Locker::TearDownSession));
32760b57cec5SDimitry Andric return py_lock;
32770b57cec5SDimitry Andric }
32780b57cec5SDimitry Andric
InitializePrivate()32790b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::InitializePrivate() {
32800b57cec5SDimitry Andric if (g_initialized)
32810b57cec5SDimitry Andric return;
32820b57cec5SDimitry Andric
32830b57cec5SDimitry Andric g_initialized = true;
32840b57cec5SDimitry Andric
3285af732203SDimitry Andric LLDB_SCOPED_TIMER();
32860b57cec5SDimitry Andric
32870b57cec5SDimitry Andric // RAII-based initialization which correctly handles multiple-initialization,
32880b57cec5SDimitry Andric // version- specific differences among Python 2 and Python 3, and saving and
32890b57cec5SDimitry Andric // restoring various other pieces of state that can get mucked with during
32900b57cec5SDimitry Andric // initialization.
32910b57cec5SDimitry Andric InitializePythonRAII initialize_guard;
32920b57cec5SDimitry Andric
32930b57cec5SDimitry Andric LLDBSwigPyInit();
32940b57cec5SDimitry Andric
32950b57cec5SDimitry Andric // Update the path python uses to search for modules to include the current
32960b57cec5SDimitry Andric // directory.
32970b57cec5SDimitry Andric
32980b57cec5SDimitry Andric PyRun_SimpleString("import sys");
32990b57cec5SDimitry Andric AddToSysPath(AddLocation::End, ".");
33000b57cec5SDimitry Andric
33010b57cec5SDimitry Andric // Don't denormalize paths when calling file_spec.GetPath(). On platforms
33020b57cec5SDimitry Andric // that use a backslash as the path separator, this will result in executing
33030b57cec5SDimitry Andric // python code containing paths with unescaped backslashes. But Python also
33040b57cec5SDimitry Andric // accepts forward slashes, so to make life easier we just use that.
33050b57cec5SDimitry Andric if (FileSpec file_spec = GetPythonDir())
33060b57cec5SDimitry Andric AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
33070b57cec5SDimitry Andric if (FileSpec file_spec = HostInfo::GetShlibDir())
33080b57cec5SDimitry Andric AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
33090b57cec5SDimitry Andric
33100b57cec5SDimitry Andric PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
33110b57cec5SDimitry Andric "lldb.embedded_interpreter; from "
33120b57cec5SDimitry Andric "lldb.embedded_interpreter import run_python_interpreter; "
33130b57cec5SDimitry Andric "from lldb.embedded_interpreter import run_one_line");
33140b57cec5SDimitry Andric }
33150b57cec5SDimitry Andric
AddToSysPath(AddLocation location,std::string path)33160b57cec5SDimitry Andric void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
33170b57cec5SDimitry Andric std::string path) {
33180b57cec5SDimitry Andric std::string path_copy;
33190b57cec5SDimitry Andric
33200b57cec5SDimitry Andric std::string statement;
33210b57cec5SDimitry Andric if (location == AddLocation::Beginning) {
33220b57cec5SDimitry Andric statement.assign("sys.path.insert(0,\"");
33230b57cec5SDimitry Andric statement.append(path);
33240b57cec5SDimitry Andric statement.append("\")");
33250b57cec5SDimitry Andric } else {
33260b57cec5SDimitry Andric statement.assign("sys.path.append(\"");
33270b57cec5SDimitry Andric statement.append(path);
33280b57cec5SDimitry Andric statement.append("\")");
33290b57cec5SDimitry Andric }
33300b57cec5SDimitry Andric PyRun_SimpleString(statement.c_str());
33310b57cec5SDimitry Andric }
33320b57cec5SDimitry Andric
33330b57cec5SDimitry Andric // We are intentionally NOT calling Py_Finalize here (this would be the logical
33340b57cec5SDimitry Andric // place to call it). Calling Py_Finalize here causes test suite runs to seg
33350b57cec5SDimitry Andric // fault: The test suite runs in Python. It registers SBDebugger::Terminate to
33360b57cec5SDimitry Andric // be called 'at_exit'. When the test suite Python harness finishes up, it
33370b57cec5SDimitry Andric // calls Py_Finalize, which calls all the 'at_exit' registered functions.
33380b57cec5SDimitry Andric // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
33390b57cec5SDimitry Andric // which calls ScriptInterpreter::Terminate, which calls
33400b57cec5SDimitry Andric // ScriptInterpreterPythonImpl::Terminate. So if we call Py_Finalize here, we
33410b57cec5SDimitry Andric // end up with Py_Finalize being called from within Py_Finalize, which results
33420b57cec5SDimitry Andric // in a seg fault. Since this function only gets called when lldb is shutting
33430b57cec5SDimitry Andric // down and going away anyway, the fact that we don't actually call Py_Finalize
33440b57cec5SDimitry Andric // should not cause any problems (everything should shut down/go away anyway
33450b57cec5SDimitry Andric // when the process exits).
33460b57cec5SDimitry Andric //
33470b57cec5SDimitry Andric // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
33480b57cec5SDimitry Andric
3349480093f4SDimitry Andric #endif
3350