180814287SRaphael Isemann //===-- ScriptInterpreterPython.cpp ---------------------------------------===// 22c1f46dcSZachary Turner // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 62c1f46dcSZachary Turner // 72c1f46dcSZachary Turner //===----------------------------------------------------------------------===// 82c1f46dcSZachary Turner 959998b7bSJonas Devlieghere #include "lldb/Host/Config.h" 10d055e3a0SPedro Tammela #include "lldb/lldb-enumerations.h" 11d68983e3SPavel Labath 124e26cf2cSJonas Devlieghere #if LLDB_ENABLE_PYTHON 13d68983e3SPavel Labath 1441de9a97SKate Stone // LLDB Python header must be included first 152c1f46dcSZachary Turner #include "lldb-python.h" 1641de9a97SKate Stone 172c1f46dcSZachary Turner #include "PythonDataObjects.h" 189357b5d0Sserge-sans-paille #include "PythonReadline.h" 1963dd5d25SJonas Devlieghere #include "ScriptInterpreterPythonImpl.h" 2041ae8e74SKuba Mracek #include "lldb/API/SBFrame.h" 2163dd5d25SJonas Devlieghere #include "lldb/API/SBValue.h" 222c1f46dcSZachary Turner #include "lldb/Breakpoint/StoppointCallbackContext.h" 232c1f46dcSZachary Turner #include "lldb/Breakpoint/WatchpointOptions.h" 242c1f46dcSZachary Turner #include "lldb/Core/Communication.h" 252c1f46dcSZachary Turner #include "lldb/Core/Debugger.h" 262c1f46dcSZachary Turner #include "lldb/Core/PluginManager.h" 272c1f46dcSZachary Turner #include "lldb/Core/ValueObject.h" 282c1f46dcSZachary Turner #include "lldb/DataFormatters/TypeSummary.h" 294eff2d31SZachary Turner #include "lldb/Host/FileSystem.h" 302c1f46dcSZachary Turner #include "lldb/Host/HostInfo.h" 312c1f46dcSZachary Turner #include "lldb/Host/Pipe.h" 322c1f46dcSZachary Turner #include "lldb/Interpreter/CommandInterpreter.h" 332c1f46dcSZachary Turner #include "lldb/Interpreter/CommandReturnObject.h" 342c1f46dcSZachary Turner #include "lldb/Target/Thread.h" 352c1f46dcSZachary Turner #include "lldb/Target/ThreadPlan.h" 365861234eSJonas Devlieghere #include "lldb/Utility/ReproducerInstrumentation.h" 3738d0632eSPavel Labath #include "lldb/Utility/Timer.h" 3822c8efcdSZachary Turner #include "llvm/ADT/STLExtras.h" 39b9c1b51eSKate Stone #include "llvm/ADT/StringRef.h" 40d79273c9SJonas Devlieghere #include "llvm/Support/Error.h" 417d86ee5aSZachary Turner #include "llvm/Support/FileSystem.h" 422fce1137SLawrence D'Anna #include "llvm/Support/FormatAdapters.h" 432c1f46dcSZachary Turner 449a6c7572SJonas Devlieghere #include <memory> 459a6c7572SJonas Devlieghere #include <mutex> 469a6c7572SJonas Devlieghere #include <stdio.h> 479a6c7572SJonas Devlieghere #include <stdlib.h> 489a6c7572SJonas Devlieghere #include <string> 499a6c7572SJonas Devlieghere 502c1f46dcSZachary Turner using namespace lldb; 512c1f46dcSZachary Turner using namespace lldb_private; 52722b6189SLawrence D'Anna using namespace lldb_private::python; 5304edd189SLawrence D'Anna using llvm::Expected; 542c1f46dcSZachary Turner 55bba9ba8dSJonas Devlieghere LLDB_PLUGIN_DEFINE(ScriptInterpreterPython) 56fbb4d1e4SJonas Devlieghere 57b01b1087SJonas Devlieghere // Defined in the SWIG source file 58b01b1087SJonas Devlieghere #if PY_MAJOR_VERSION >= 3 59b01b1087SJonas Devlieghere extern "C" PyObject *PyInit__lldb(void); 60b01b1087SJonas Devlieghere 61b01b1087SJonas Devlieghere #define LLDBSwigPyInit PyInit__lldb 62b01b1087SJonas Devlieghere 63b01b1087SJonas Devlieghere #else 64b01b1087SJonas Devlieghere extern "C" void init_lldb(void); 65b01b1087SJonas Devlieghere 66b01b1087SJonas Devlieghere #define LLDBSwigPyInit init_lldb 67b01b1087SJonas Devlieghere #endif 68b01b1087SJonas Devlieghere 6905495c5dSJonas Devlieghere // These prototypes are the Pythonic implementations of the required callbacks. 7005495c5dSJonas Devlieghere // Although these are scripting-language specific, their definition depends on 7105495c5dSJonas Devlieghere // the public API. 72a69bbe02SLawrence D'Anna 73a69bbe02SLawrence D'Anna #pragma clang diagnostic push 74a69bbe02SLawrence D'Anna #pragma clang diagnostic ignored "-Wreturn-type-c-linkage" 75a69bbe02SLawrence D'Anna 761cc0ba4cSAlexandre Ganea // Disable warning C4190: 'LLDBSwigPythonBreakpointCallbackFunction' has 771cc0ba4cSAlexandre Ganea // C-linkage specified, but returns UDT 'llvm::Expected<bool>' which is 781cc0ba4cSAlexandre Ganea // incompatible with C 791cc0ba4cSAlexandre Ganea #if _MSC_VER 801cc0ba4cSAlexandre Ganea #pragma warning (push) 811cc0ba4cSAlexandre Ganea #pragma warning (disable : 4190) 821cc0ba4cSAlexandre Ganea #endif 831cc0ba4cSAlexandre Ganea 84a69bbe02SLawrence D'Anna extern "C" llvm::Expected<bool> LLDBSwigPythonBreakpointCallbackFunction( 85b01b1087SJonas Devlieghere const char *python_function_name, const char *session_dictionary_name, 86b01b1087SJonas Devlieghere const lldb::StackFrameSP &sb_frame, 87a69bbe02SLawrence D'Anna const lldb::BreakpointLocationSP &sb_bp_loc, StructuredDataImpl *args_impl); 88a69bbe02SLawrence D'Anna 891cc0ba4cSAlexandre Ganea #if _MSC_VER 901cc0ba4cSAlexandre Ganea #pragma warning (pop) 911cc0ba4cSAlexandre Ganea #endif 921cc0ba4cSAlexandre Ganea 93a69bbe02SLawrence D'Anna #pragma clang diagnostic pop 94b01b1087SJonas Devlieghere 95b01b1087SJonas Devlieghere extern "C" bool LLDBSwigPythonWatchpointCallbackFunction( 96b01b1087SJonas Devlieghere const char *python_function_name, const char *session_dictionary_name, 97b01b1087SJonas Devlieghere const lldb::StackFrameSP &sb_frame, const lldb::WatchpointSP &sb_wp); 98b01b1087SJonas Devlieghere 99b01b1087SJonas Devlieghere extern "C" bool LLDBSwigPythonCallTypeScript( 100b01b1087SJonas Devlieghere const char *python_function_name, void *session_dictionary, 101b01b1087SJonas Devlieghere const lldb::ValueObjectSP &valobj_sp, void **pyfunct_wrapper, 102b01b1087SJonas Devlieghere const lldb::TypeSummaryOptionsSP &options_sp, std::string &retval); 103b01b1087SJonas Devlieghere 104b01b1087SJonas Devlieghere extern "C" void * 105b01b1087SJonas Devlieghere LLDBSwigPythonCreateSyntheticProvider(const char *python_class_name, 106b01b1087SJonas Devlieghere const char *session_dictionary_name, 107b01b1087SJonas Devlieghere const lldb::ValueObjectSP &valobj_sp); 108b01b1087SJonas Devlieghere 109b01b1087SJonas Devlieghere extern "C" void * 110b01b1087SJonas Devlieghere LLDBSwigPythonCreateCommandObject(const char *python_class_name, 111b01b1087SJonas Devlieghere const char *session_dictionary_name, 112b01b1087SJonas Devlieghere const lldb::DebuggerSP debugger_sp); 113b01b1087SJonas Devlieghere 114b01b1087SJonas Devlieghere extern "C" void *LLDBSwigPythonCreateScriptedThreadPlan( 115b01b1087SJonas Devlieghere const char *python_class_name, const char *session_dictionary_name, 11627a14f19SJim Ingham StructuredDataImpl *args_data, 11793c98346SJim Ingham std::string &error_string, 118b01b1087SJonas Devlieghere const lldb::ThreadPlanSP &thread_plan_sp); 119b01b1087SJonas Devlieghere 120b01b1087SJonas Devlieghere extern "C" bool LLDBSWIGPythonCallThreadPlan(void *implementor, 121b01b1087SJonas Devlieghere const char *method_name, 122b01b1087SJonas Devlieghere Event *event_sp, bool &got_error); 123b01b1087SJonas Devlieghere 124b01b1087SJonas Devlieghere extern "C" void *LLDBSwigPythonCreateScriptedBreakpointResolver( 125b01b1087SJonas Devlieghere const char *python_class_name, const char *session_dictionary_name, 126b01b1087SJonas Devlieghere lldb_private::StructuredDataImpl *args, lldb::BreakpointSP &bkpt_sp); 127b01b1087SJonas Devlieghere 128b01b1087SJonas Devlieghere extern "C" unsigned int 129b01b1087SJonas Devlieghere LLDBSwigPythonCallBreakpointResolver(void *implementor, const char *method_name, 130b01b1087SJonas Devlieghere lldb_private::SymbolContext *sym_ctx); 131b01b1087SJonas Devlieghere 1321b1d9815SJim Ingham extern "C" void *LLDBSwigPythonCreateScriptedStopHook( 1331b1d9815SJim Ingham TargetSP target_sp, const char *python_class_name, 1341b1d9815SJim Ingham const char *session_dictionary_name, lldb_private::StructuredDataImpl *args, 1351b1d9815SJim Ingham lldb_private::Status &error); 1361b1d9815SJim Ingham 1371b1d9815SJim Ingham extern "C" bool 1381b1d9815SJim Ingham LLDBSwigPythonStopHookCallHandleStop(void *implementor, 1391b1d9815SJim Ingham lldb::ExecutionContextRefSP exc_ctx, 1401b1d9815SJim Ingham lldb::StreamSP stream); 1411b1d9815SJim Ingham 142b01b1087SJonas Devlieghere extern "C" size_t LLDBSwigPython_CalculateNumChildren(void *implementor, 143b01b1087SJonas Devlieghere uint32_t max); 144b01b1087SJonas Devlieghere 145b01b1087SJonas Devlieghere extern "C" void *LLDBSwigPython_GetChildAtIndex(void *implementor, 146b01b1087SJonas Devlieghere uint32_t idx); 147b01b1087SJonas Devlieghere 148b01b1087SJonas Devlieghere extern "C" int LLDBSwigPython_GetIndexOfChildWithName(void *implementor, 149b01b1087SJonas Devlieghere const char *child_name); 150b01b1087SJonas Devlieghere 151b01b1087SJonas Devlieghere extern "C" void *LLDBSWIGPython_CastPyObjectToSBValue(void *data); 152b01b1087SJonas Devlieghere 153b01b1087SJonas Devlieghere extern lldb::ValueObjectSP 154b01b1087SJonas Devlieghere LLDBSWIGPython_GetValueObjectSPFromSBValue(void *data); 155b01b1087SJonas Devlieghere 156b01b1087SJonas Devlieghere extern "C" bool LLDBSwigPython_UpdateSynthProviderInstance(void *implementor); 157b01b1087SJonas Devlieghere 158b01b1087SJonas Devlieghere extern "C" bool 159b01b1087SJonas Devlieghere LLDBSwigPython_MightHaveChildrenSynthProviderInstance(void *implementor); 160b01b1087SJonas Devlieghere 161b01b1087SJonas Devlieghere extern "C" void * 162b01b1087SJonas Devlieghere LLDBSwigPython_GetValueSynthProviderInstance(void *implementor); 163b01b1087SJonas Devlieghere 164b01b1087SJonas Devlieghere extern "C" bool 165b01b1087SJonas Devlieghere LLDBSwigPythonCallCommand(const char *python_function_name, 166b01b1087SJonas Devlieghere const char *session_dictionary_name, 167b01b1087SJonas Devlieghere lldb::DebuggerSP &debugger, const char *args, 168b01b1087SJonas Devlieghere lldb_private::CommandReturnObject &cmd_retobj, 169b01b1087SJonas Devlieghere lldb::ExecutionContextRefSP exe_ctx_ref_sp); 170b01b1087SJonas Devlieghere 171b01b1087SJonas Devlieghere extern "C" bool 172b01b1087SJonas Devlieghere LLDBSwigPythonCallCommandObject(void *implementor, lldb::DebuggerSP &debugger, 173b01b1087SJonas Devlieghere const char *args, 174b01b1087SJonas Devlieghere lldb_private::CommandReturnObject &cmd_retobj, 175b01b1087SJonas Devlieghere lldb::ExecutionContextRefSP exe_ctx_ref_sp); 176b01b1087SJonas Devlieghere 177b01b1087SJonas Devlieghere extern "C" bool 178b01b1087SJonas Devlieghere LLDBSwigPythonCallModuleInit(const char *python_module_name, 179b01b1087SJonas Devlieghere const char *session_dictionary_name, 180b01b1087SJonas Devlieghere lldb::DebuggerSP &debugger); 181b01b1087SJonas Devlieghere 182b01b1087SJonas Devlieghere extern "C" void * 183b01b1087SJonas Devlieghere LLDBSWIGPythonCreateOSPlugin(const char *python_class_name, 184b01b1087SJonas Devlieghere const char *session_dictionary_name, 185b01b1087SJonas Devlieghere const lldb::ProcessSP &process_sp); 186b01b1087SJonas Devlieghere 187b01b1087SJonas Devlieghere extern "C" void * 188b01b1087SJonas Devlieghere LLDBSWIGPython_CreateFrameRecognizer(const char *python_class_name, 189b01b1087SJonas Devlieghere const char *session_dictionary_name); 190b01b1087SJonas Devlieghere 191b01b1087SJonas Devlieghere extern "C" void * 192b01b1087SJonas Devlieghere LLDBSwigPython_GetRecognizedArguments(void *implementor, 193b01b1087SJonas Devlieghere const lldb::StackFrameSP &frame_sp); 194b01b1087SJonas Devlieghere 195b01b1087SJonas Devlieghere extern "C" bool LLDBSWIGPythonRunScriptKeywordProcess( 196b01b1087SJonas Devlieghere const char *python_function_name, const char *session_dictionary_name, 197b01b1087SJonas Devlieghere lldb::ProcessSP &process, std::string &output); 198b01b1087SJonas Devlieghere 199b01b1087SJonas Devlieghere extern "C" bool LLDBSWIGPythonRunScriptKeywordThread( 200b01b1087SJonas Devlieghere const char *python_function_name, const char *session_dictionary_name, 201b01b1087SJonas Devlieghere lldb::ThreadSP &thread, std::string &output); 202b01b1087SJonas Devlieghere 203b01b1087SJonas Devlieghere extern "C" bool LLDBSWIGPythonRunScriptKeywordTarget( 204b01b1087SJonas Devlieghere const char *python_function_name, const char *session_dictionary_name, 205b01b1087SJonas Devlieghere lldb::TargetSP &target, std::string &output); 206b01b1087SJonas Devlieghere 207b01b1087SJonas Devlieghere extern "C" bool LLDBSWIGPythonRunScriptKeywordFrame( 208b01b1087SJonas Devlieghere const char *python_function_name, const char *session_dictionary_name, 209b01b1087SJonas Devlieghere lldb::StackFrameSP &frame, std::string &output); 210b01b1087SJonas Devlieghere 211b01b1087SJonas Devlieghere extern "C" bool LLDBSWIGPythonRunScriptKeywordValue( 212b01b1087SJonas Devlieghere const char *python_function_name, const char *session_dictionary_name, 213b01b1087SJonas Devlieghere lldb::ValueObjectSP &value, std::string &output); 214b01b1087SJonas Devlieghere 215b01b1087SJonas Devlieghere extern "C" void * 216b01b1087SJonas Devlieghere LLDBSWIGPython_GetDynamicSetting(void *module, const char *setting, 217b01b1087SJonas Devlieghere const lldb::TargetSP &target_sp); 218b01b1087SJonas Devlieghere 219d055e3a0SPedro Tammela static ScriptInterpreterPythonImpl *GetPythonInterpreter(Debugger &debugger) { 220d055e3a0SPedro Tammela ScriptInterpreter *script_interpreter = 221d055e3a0SPedro Tammela debugger.GetScriptInterpreter(true, lldb::eScriptLanguagePython); 222d055e3a0SPedro Tammela return static_cast<ScriptInterpreterPythonImpl *>(script_interpreter); 223d055e3a0SPedro Tammela } 224d055e3a0SPedro Tammela 2252c1f46dcSZachary Turner static bool g_initialized = false; 2262c1f46dcSZachary Turner 227b9c1b51eSKate Stone namespace { 22822c8efcdSZachary Turner 22905097246SAdrian Prantl // Initializing Python is not a straightforward process. We cannot control 23005097246SAdrian Prantl // what external code may have done before getting to this point in LLDB, 23105097246SAdrian Prantl // including potentially having already initialized Python, so we need to do a 23205097246SAdrian Prantl // lot of work to ensure that the existing state of the system is maintained 23305097246SAdrian Prantl // across our initialization. We do this by using an RAII pattern where we 23405097246SAdrian Prantl // save off initial state at the beginning, and restore it at the end 235b9c1b51eSKate Stone struct InitializePythonRAII { 236079fe48aSZachary Turner public: 237b9c1b51eSKate Stone InitializePythonRAII() 238b9c1b51eSKate Stone : m_gil_state(PyGILState_UNLOCKED), m_was_already_initialized(false) { 239079fe48aSZachary Turner InitializePythonHome(); 240079fe48aSZachary Turner 2419357b5d0Sserge-sans-paille #ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE 2429357b5d0Sserge-sans-paille // Python's readline is incompatible with libedit being linked into lldb. 2439357b5d0Sserge-sans-paille // Provide a patched version local to the embedded interpreter. 2449357b5d0Sserge-sans-paille bool ReadlinePatched = false; 2459357b5d0Sserge-sans-paille for (auto *p = PyImport_Inittab; p->name != NULL; p++) { 2469357b5d0Sserge-sans-paille if (strcmp(p->name, "readline") == 0) { 2479357b5d0Sserge-sans-paille p->initfunc = initlldb_readline; 2489357b5d0Sserge-sans-paille break; 2499357b5d0Sserge-sans-paille } 2509357b5d0Sserge-sans-paille } 2519357b5d0Sserge-sans-paille if (!ReadlinePatched) { 2529357b5d0Sserge-sans-paille PyImport_AppendInittab("readline", initlldb_readline); 2539357b5d0Sserge-sans-paille ReadlinePatched = true; 2549357b5d0Sserge-sans-paille } 2559357b5d0Sserge-sans-paille #endif 2569357b5d0Sserge-sans-paille 25774587a0eSVadim Chugunov // Register _lldb as a built-in module. 25805495c5dSJonas Devlieghere PyImport_AppendInittab("_lldb", LLDBSwigPyInit); 25974587a0eSVadim Chugunov 260079fe48aSZachary Turner // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for 261079fe48aSZachary Turner // calling `Py_Initialize` and `PyEval_InitThreads`. < 3.2 requires that you 262079fe48aSZachary Turner // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last. 263079fe48aSZachary Turner #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3) 264079fe48aSZachary Turner Py_InitializeEx(0); 265079fe48aSZachary Turner InitializeThreadsPrivate(); 266079fe48aSZachary Turner #else 267079fe48aSZachary Turner InitializeThreadsPrivate(); 268079fe48aSZachary Turner Py_InitializeEx(0); 269079fe48aSZachary Turner #endif 270079fe48aSZachary Turner } 271079fe48aSZachary Turner 272b9c1b51eSKate Stone ~InitializePythonRAII() { 273b9c1b51eSKate Stone if (m_was_already_initialized) { 2743b7e1981SPavel Labath Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 2753b7e1981SPavel Labath LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked", 2761b6700efSTatyana Krasnukha m_gil_state == PyGILState_UNLOCKED ? "un" : ""); 277079fe48aSZachary Turner PyGILState_Release(m_gil_state); 278b9c1b51eSKate Stone } else { 279079fe48aSZachary Turner // We initialized the threads in this function, just unlock the GIL. 280079fe48aSZachary Turner PyEval_SaveThread(); 281079fe48aSZachary Turner } 282079fe48aSZachary Turner } 283079fe48aSZachary Turner 284079fe48aSZachary Turner private: 285b9c1b51eSKate Stone void InitializePythonHome() { 2863ec3f62fSHaibo Huang #if LLDB_EMBED_PYTHON_HOME 2873ec3f62fSHaibo Huang #if PY_MAJOR_VERSION >= 3 2883ec3f62fSHaibo Huang typedef wchar_t* str_type; 2893ec3f62fSHaibo Huang #else 2903ec3f62fSHaibo Huang typedef char* str_type; 2913ec3f62fSHaibo Huang #endif 2923ec3f62fSHaibo Huang static str_type g_python_home = []() -> str_type { 2933ec3f62fSHaibo Huang const char *lldb_python_home = LLDB_PYTHON_HOME; 2943ec3f62fSHaibo Huang const char *absolute_python_home = nullptr; 2953ec3f62fSHaibo Huang llvm::SmallString<64> path; 2963ec3f62fSHaibo Huang if (llvm::sys::path::is_absolute(lldb_python_home)) { 2973ec3f62fSHaibo Huang absolute_python_home = lldb_python_home; 2983ec3f62fSHaibo Huang } else { 2993ec3f62fSHaibo Huang FileSpec spec = HostInfo::GetShlibDir(); 3003ec3f62fSHaibo Huang if (!spec) 3013ec3f62fSHaibo Huang return nullptr; 3023ec3f62fSHaibo Huang spec.GetPath(path); 3033ec3f62fSHaibo Huang llvm::sys::path::append(path, lldb_python_home); 3043ec3f62fSHaibo Huang absolute_python_home = path.c_str(); 3053ec3f62fSHaibo Huang } 30622c8efcdSZachary Turner #if PY_MAJOR_VERSION >= 3 30722c8efcdSZachary Turner size_t size = 0; 3083ec3f62fSHaibo Huang return Py_DecodeLocale(absolute_python_home, &size); 30922c8efcdSZachary Turner #else 3103ec3f62fSHaibo Huang return strdup(absolute_python_home); 31122c8efcdSZachary Turner #endif 3123ec3f62fSHaibo Huang }(); 3133ec3f62fSHaibo Huang if (g_python_home != nullptr) { 314079fe48aSZachary Turner Py_SetPythonHome(g_python_home); 3153ec3f62fSHaibo Huang } 316386f00dbSDavide Italiano #else 317386f00dbSDavide Italiano #if defined(__APPLE__) && PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION == 7 31863dd5d25SJonas Devlieghere // For Darwin, the only Python version supported is the one shipped in the 31963dd5d25SJonas Devlieghere // OS OS and linked with lldb. Other installation of Python may have higher 3204f9cb260SDavide Italiano // priorities in the path, overriding PYTHONHOME and causing 3214f9cb260SDavide Italiano // problems/incompatibilities. In order to avoid confusion, always hardcode 3224f9cb260SDavide Italiano // the PythonHome to be right, as it's not going to change. 32363dd5d25SJonas Devlieghere static char path[] = 32463dd5d25SJonas Devlieghere "/System/Library/Frameworks/Python.framework/Versions/2.7"; 3254f9cb260SDavide Italiano Py_SetPythonHome(path); 326386f00dbSDavide Italiano #endif 327386f00dbSDavide Italiano #endif 32822c8efcdSZachary Turner } 32922c8efcdSZachary Turner 330b9c1b51eSKate Stone void InitializeThreadsPrivate() { 3311b6700efSTatyana Krasnukha // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself, 3321b6700efSTatyana Krasnukha // so there is no way to determine whether the embedded interpreter 3331b6700efSTatyana Krasnukha // was already initialized by some external code. `PyEval_ThreadsInitialized` 3341b6700efSTatyana Krasnukha // would always return `true` and `PyGILState_Ensure/Release` flow would be 3351b6700efSTatyana Krasnukha // executed instead of unlocking GIL with `PyEval_SaveThread`. When 3361b6700efSTatyana Krasnukha // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock. 3371b6700efSTatyana Krasnukha #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3) 3381b6700efSTatyana Krasnukha // The only case we should go further and acquire the GIL: it is unlocked. 3391b6700efSTatyana Krasnukha if (PyGILState_Check()) 3401b6700efSTatyana Krasnukha return; 3411b6700efSTatyana Krasnukha #endif 3421b6700efSTatyana Krasnukha 343b9c1b51eSKate Stone if (PyEval_ThreadsInitialized()) { 3443b7e1981SPavel Labath Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 345079fe48aSZachary Turner 346079fe48aSZachary Turner m_was_already_initialized = true; 347079fe48aSZachary Turner m_gil_state = PyGILState_Ensure(); 3483b7e1981SPavel Labath LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n", 349079fe48aSZachary Turner m_gil_state == PyGILState_UNLOCKED ? "un" : ""); 350079fe48aSZachary Turner return; 351079fe48aSZachary Turner } 352079fe48aSZachary Turner 353079fe48aSZachary Turner // InitThreads acquires the GIL if it hasn't been called before. 354079fe48aSZachary Turner PyEval_InitThreads(); 355079fe48aSZachary Turner } 356079fe48aSZachary Turner 357079fe48aSZachary Turner TerminalState m_stdin_tty_state; 358079fe48aSZachary Turner PyGILState_STATE m_gil_state; 359079fe48aSZachary Turner bool m_was_already_initialized; 360079fe48aSZachary Turner }; 36163dd5d25SJonas Devlieghere } // namespace 3622c1f46dcSZachary Turner 3632df331b0SPavel Labath void ScriptInterpreterPython::ComputePythonDirForApple( 3642df331b0SPavel Labath llvm::SmallVectorImpl<char> &path) { 3652df331b0SPavel Labath auto style = llvm::sys::path::Style::posix; 3662df331b0SPavel Labath 3672df331b0SPavel Labath llvm::StringRef path_ref(path.begin(), path.size()); 3682df331b0SPavel Labath auto rbegin = llvm::sys::path::rbegin(path_ref, style); 3692df331b0SPavel Labath auto rend = llvm::sys::path::rend(path_ref); 3702df331b0SPavel Labath auto framework = std::find(rbegin, rend, "LLDB.framework"); 3712df331b0SPavel Labath if (framework == rend) { 37261f471a7SHaibo Huang ComputePythonDir(path); 3732df331b0SPavel Labath return; 3742df331b0SPavel Labath } 3752df331b0SPavel Labath path.resize(framework - rend); 3762df331b0SPavel Labath llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python"); 3772df331b0SPavel Labath } 3782df331b0SPavel Labath 37961f471a7SHaibo Huang void ScriptInterpreterPython::ComputePythonDir( 3802df331b0SPavel Labath llvm::SmallVectorImpl<char> &path) { 3812df331b0SPavel Labath // Build the path by backing out of the lib dir, then building with whatever 3822df331b0SPavel Labath // the real python interpreter uses. (e.g. lib for most, lib64 on RHEL 38361f471a7SHaibo Huang // x86_64, or bin on Windows). 38461f471a7SHaibo Huang llvm::sys::path::remove_filename(path); 38561f471a7SHaibo Huang llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR); 3860016b450SHaibo Huang 3870016b450SHaibo Huang #if defined(_WIN32) 3880016b450SHaibo Huang // This will be injected directly through FileSpec.GetDirectory().SetString(), 3890016b450SHaibo Huang // so we need to normalize manually. 3900016b450SHaibo Huang std::replace(path.begin(), path.end(), '\\', '/'); 3910016b450SHaibo Huang #endif 3922df331b0SPavel Labath } 3932df331b0SPavel Labath 3942df331b0SPavel Labath FileSpec ScriptInterpreterPython::GetPythonDir() { 3952df331b0SPavel Labath static FileSpec g_spec = []() { 3962df331b0SPavel Labath FileSpec spec = HostInfo::GetShlibDir(); 3972df331b0SPavel Labath if (!spec) 3982df331b0SPavel Labath return FileSpec(); 3992df331b0SPavel Labath llvm::SmallString<64> path; 4002df331b0SPavel Labath spec.GetPath(path); 4012df331b0SPavel Labath 4022df331b0SPavel Labath #if defined(__APPLE__) 4032df331b0SPavel Labath ComputePythonDirForApple(path); 4042df331b0SPavel Labath #else 40561f471a7SHaibo Huang ComputePythonDir(path); 4062df331b0SPavel Labath #endif 4072df331b0SPavel Labath spec.GetDirectory().SetString(path); 4082df331b0SPavel Labath return spec; 4092df331b0SPavel Labath }(); 4102df331b0SPavel Labath return g_spec; 4112df331b0SPavel Labath } 4122df331b0SPavel Labath 413*004a264fSPavel Labath void ScriptInterpreterPython::SharedLibraryDirectoryHelper( 414*004a264fSPavel Labath FileSpec &this_file) { 415*004a264fSPavel Labath // When we're loaded from python, this_file will point to the file inside the 416*004a264fSPavel Labath // python package directory. Replace it with the one in the lib directory. 417*004a264fSPavel Labath #ifdef _WIN32 418*004a264fSPavel Labath // On windows, we need to manually back out of the python tree, and go into 419*004a264fSPavel Labath // the bin directory. This is pretty much the inverse of what ComputePythonDir 420*004a264fSPavel Labath // does. 421*004a264fSPavel Labath if (this_file.GetFileNameExtension() == ConstString(".pyd")) { 422*004a264fSPavel Labath this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd 423*004a264fSPavel Labath this_file.RemoveLastPathComponent(); // lldb 424*004a264fSPavel Labath for (auto it = llvm::sys::path::begin(LLDB_PYTHON_RELATIVE_LIBDIR), 425*004a264fSPavel Labath end = llvm::sys::path::end(LLDB_PYTHON_RELATIVE_LIBDIR); 426*004a264fSPavel Labath it != end; ++it) 427*004a264fSPavel Labath this_file.RemoveLastPathComponent(); 428*004a264fSPavel Labath this_file.AppendPathComponent("bin"); 429*004a264fSPavel Labath this_file.AppendPathComponent("liblldb.dll"); 430*004a264fSPavel Labath } 431*004a264fSPavel Labath #else 432*004a264fSPavel Labath // The python file is a symlink, so we can find the real library by resolving 433*004a264fSPavel Labath // it. We can do this unconditionally. 434*004a264fSPavel Labath FileSystem::Instance().ResolveSymbolicLink(this_file, this_file); 435*004a264fSPavel Labath #endif 436*004a264fSPavel Labath } 437*004a264fSPavel Labath 43863dd5d25SJonas Devlieghere lldb_private::ConstString ScriptInterpreterPython::GetPluginNameStatic() { 43963dd5d25SJonas Devlieghere static ConstString g_name("script-python"); 44063dd5d25SJonas Devlieghere return g_name; 44163dd5d25SJonas Devlieghere } 44263dd5d25SJonas Devlieghere 44363dd5d25SJonas Devlieghere const char *ScriptInterpreterPython::GetPluginDescriptionStatic() { 44463dd5d25SJonas Devlieghere return "Embedded Python interpreter"; 44563dd5d25SJonas Devlieghere } 44663dd5d25SJonas Devlieghere 44763dd5d25SJonas Devlieghere void ScriptInterpreterPython::Initialize() { 44863dd5d25SJonas Devlieghere static llvm::once_flag g_once_flag; 44963dd5d25SJonas Devlieghere 45063dd5d25SJonas Devlieghere llvm::call_once(g_once_flag, []() { 45163dd5d25SJonas Devlieghere PluginManager::RegisterPlugin(GetPluginNameStatic(), 45263dd5d25SJonas Devlieghere GetPluginDescriptionStatic(), 45363dd5d25SJonas Devlieghere lldb::eScriptLanguagePython, 45463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateInstance); 45563dd5d25SJonas Devlieghere }); 45663dd5d25SJonas Devlieghere } 45763dd5d25SJonas Devlieghere 45863dd5d25SJonas Devlieghere void ScriptInterpreterPython::Terminate() {} 45963dd5d25SJonas Devlieghere 46063dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::Locker( 46163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry, 462b07823f3SLawrence D'Anna uint16_t on_leave, FileSP in, FileSP out, FileSP err) 46363dd5d25SJonas Devlieghere : ScriptInterpreterLocker(), 46463dd5d25SJonas Devlieghere m_teardown_session((on_leave & TearDownSession) == TearDownSession), 46563dd5d25SJonas Devlieghere m_python_interpreter(py_interpreter) { 4665861234eSJonas Devlieghere repro::Recorder::PrivateThread(); 46763dd5d25SJonas Devlieghere DoAcquireLock(); 46863dd5d25SJonas Devlieghere if ((on_entry & InitSession) == InitSession) { 46963dd5d25SJonas Devlieghere if (!DoInitSession(on_entry, in, out, err)) { 47063dd5d25SJonas Devlieghere // Don't teardown the session if we didn't init it. 47163dd5d25SJonas Devlieghere m_teardown_session = false; 47263dd5d25SJonas Devlieghere } 47363dd5d25SJonas Devlieghere } 47463dd5d25SJonas Devlieghere } 47563dd5d25SJonas Devlieghere 47663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() { 47763dd5d25SJonas Devlieghere Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 47863dd5d25SJonas Devlieghere m_GILState = PyGILState_Ensure(); 47963dd5d25SJonas Devlieghere LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked", 48063dd5d25SJonas Devlieghere m_GILState == PyGILState_UNLOCKED ? "un" : ""); 48163dd5d25SJonas Devlieghere 48263dd5d25SJonas Devlieghere // we need to save the thread state when we first start the command because 48363dd5d25SJonas Devlieghere // we might decide to interrupt it while some action is taking place outside 48463dd5d25SJonas Devlieghere // of Python (e.g. printing to screen, waiting for the network, ...) in that 48563dd5d25SJonas Devlieghere // case, _PyThreadState_Current will be NULL - and we would be unable to set 48663dd5d25SJonas Devlieghere // the asynchronous exception - not a desirable situation 48763dd5d25SJonas Devlieghere m_python_interpreter->SetThreadState(PyThreadState_Get()); 48863dd5d25SJonas Devlieghere m_python_interpreter->IncrementLockCount(); 48963dd5d25SJonas Devlieghere return true; 49063dd5d25SJonas Devlieghere } 49163dd5d25SJonas Devlieghere 49263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags, 493b07823f3SLawrence D'Anna FileSP in, FileSP out, 494b07823f3SLawrence D'Anna FileSP err) { 49563dd5d25SJonas Devlieghere if (!m_python_interpreter) 49663dd5d25SJonas Devlieghere return false; 49763dd5d25SJonas Devlieghere return m_python_interpreter->EnterSession(on_entry_flags, in, out, err); 49863dd5d25SJonas Devlieghere } 49963dd5d25SJonas Devlieghere 50063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() { 50163dd5d25SJonas Devlieghere Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 50263dd5d25SJonas Devlieghere LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked", 50363dd5d25SJonas Devlieghere m_GILState == PyGILState_UNLOCKED ? "un" : ""); 50463dd5d25SJonas Devlieghere PyGILState_Release(m_GILState); 50563dd5d25SJonas Devlieghere m_python_interpreter->DecrementLockCount(); 50663dd5d25SJonas Devlieghere return true; 50763dd5d25SJonas Devlieghere } 50863dd5d25SJonas Devlieghere 50963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() { 51063dd5d25SJonas Devlieghere if (!m_python_interpreter) 51163dd5d25SJonas Devlieghere return false; 51263dd5d25SJonas Devlieghere m_python_interpreter->LeaveSession(); 51363dd5d25SJonas Devlieghere return true; 51463dd5d25SJonas Devlieghere } 51563dd5d25SJonas Devlieghere 51663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::Locker::~Locker() { 51763dd5d25SJonas Devlieghere if (m_teardown_session) 51863dd5d25SJonas Devlieghere DoTearDownSession(); 51963dd5d25SJonas Devlieghere DoFreeLock(); 52063dd5d25SJonas Devlieghere } 52163dd5d25SJonas Devlieghere 5228d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger) 5238d1fb843SJonas Devlieghere : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(), 52463dd5d25SJonas Devlieghere m_saved_stderr(), m_main_module(), 52563dd5d25SJonas Devlieghere m_session_dict(PyInitialValue::Invalid), 52663dd5d25SJonas Devlieghere m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(), 52763dd5d25SJonas Devlieghere m_run_one_line_str_global(), 5288d1fb843SJonas Devlieghere m_dictionary_name(m_debugger.GetInstanceName().AsCString()), 529ea1752a7SJonas Devlieghere m_active_io_handler(eIOHandlerNone), m_session_is_active(false), 53064ec505dSJonas Devlieghere m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0), 531ea1752a7SJonas Devlieghere m_command_thread_state(nullptr) { 53263dd5d25SJonas Devlieghere InitializePrivate(); 53363dd5d25SJonas Devlieghere 53463dd5d25SJonas Devlieghere m_dictionary_name.append("_dict"); 53563dd5d25SJonas Devlieghere StreamString run_string; 53663dd5d25SJonas Devlieghere run_string.Printf("%s = dict()", m_dictionary_name.c_str()); 53763dd5d25SJonas Devlieghere 53863dd5d25SJonas Devlieghere Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock); 53963dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData()); 54063dd5d25SJonas Devlieghere 54163dd5d25SJonas Devlieghere run_string.Clear(); 54263dd5d25SJonas Devlieghere run_string.Printf( 54363dd5d25SJonas Devlieghere "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')", 54463dd5d25SJonas Devlieghere m_dictionary_name.c_str()); 54563dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData()); 54663dd5d25SJonas Devlieghere 54763dd5d25SJonas Devlieghere // Reloading modules requires a different syntax in Python 2 and Python 3. 54863dd5d25SJonas Devlieghere // This provides a consistent syntax no matter what version of Python. 54963dd5d25SJonas Devlieghere run_string.Clear(); 55063dd5d25SJonas Devlieghere run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')", 55163dd5d25SJonas Devlieghere m_dictionary_name.c_str()); 55263dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData()); 55363dd5d25SJonas Devlieghere 55463dd5d25SJonas Devlieghere // WARNING: temporary code that loads Cocoa formatters - this should be done 55563dd5d25SJonas Devlieghere // on a per-platform basis rather than loading the whole set and letting the 55663dd5d25SJonas Devlieghere // individual formatter classes exploit APIs to check whether they can/cannot 55763dd5d25SJonas Devlieghere // do their task 55863dd5d25SJonas Devlieghere run_string.Clear(); 55963dd5d25SJonas Devlieghere run_string.Printf( 56063dd5d25SJonas Devlieghere "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')", 56163dd5d25SJonas Devlieghere m_dictionary_name.c_str()); 56263dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData()); 56363dd5d25SJonas Devlieghere run_string.Clear(); 56463dd5d25SJonas Devlieghere 56563dd5d25SJonas Devlieghere run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from " 56663dd5d25SJonas Devlieghere "lldb.embedded_interpreter import run_python_interpreter; " 56763dd5d25SJonas Devlieghere "from lldb.embedded_interpreter import run_one_line')", 56863dd5d25SJonas Devlieghere m_dictionary_name.c_str()); 56963dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData()); 57063dd5d25SJonas Devlieghere run_string.Clear(); 57163dd5d25SJonas Devlieghere 57263dd5d25SJonas Devlieghere run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64 57363dd5d25SJonas Devlieghere "; pydoc.pager = pydoc.plainpager')", 5748d1fb843SJonas Devlieghere m_dictionary_name.c_str(), m_debugger.GetID()); 57563dd5d25SJonas Devlieghere PyRun_SimpleString(run_string.GetData()); 57663dd5d25SJonas Devlieghere } 57763dd5d25SJonas Devlieghere 57863dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() { 57963dd5d25SJonas Devlieghere // the session dictionary may hold objects with complex state which means 58063dd5d25SJonas Devlieghere // that they may need to be torn down with some level of smarts and that, in 58163dd5d25SJonas Devlieghere // turn, requires a valid thread state force Python to procure itself such a 58263dd5d25SJonas Devlieghere // thread state, nuke the session dictionary and then release it for others 58363dd5d25SJonas Devlieghere // to use and proceed with the rest of the shutdown 58463dd5d25SJonas Devlieghere auto gil_state = PyGILState_Ensure(); 58563dd5d25SJonas Devlieghere m_session_dict.Reset(); 58663dd5d25SJonas Devlieghere PyGILState_Release(gil_state); 58763dd5d25SJonas Devlieghere } 58863dd5d25SJonas Devlieghere 58963dd5d25SJonas Devlieghere lldb_private::ConstString ScriptInterpreterPythonImpl::GetPluginName() { 5902c1f46dcSZachary Turner return GetPluginNameStatic(); 5912c1f46dcSZachary Turner } 5922c1f46dcSZachary Turner 59363dd5d25SJonas Devlieghere uint32_t ScriptInterpreterPythonImpl::GetPluginVersion() { return 1; } 5942c1f46dcSZachary Turner 59563dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler, 59663dd5d25SJonas Devlieghere bool interactive) { 5972c1f46dcSZachary Turner const char *instructions = nullptr; 5982c1f46dcSZachary Turner 599b9c1b51eSKate Stone switch (m_active_io_handler) { 6002c1f46dcSZachary Turner case eIOHandlerNone: 6012c1f46dcSZachary Turner break; 6022c1f46dcSZachary Turner case eIOHandlerBreakpoint: 6032c1f46dcSZachary Turner instructions = R"(Enter your Python command(s). Type 'DONE' to end. 6042c1f46dcSZachary Turner def function (frame, bp_loc, internal_dict): 6052c1f46dcSZachary Turner """frame: the lldb.SBFrame for the location at which you stopped 6062c1f46dcSZachary Turner bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information 6072c1f46dcSZachary Turner internal_dict: an LLDB support object not to be used""" 6082c1f46dcSZachary Turner )"; 6092c1f46dcSZachary Turner break; 6102c1f46dcSZachary Turner case eIOHandlerWatchpoint: 6112c1f46dcSZachary Turner instructions = "Enter your Python command(s). Type 'DONE' to end.\n"; 6122c1f46dcSZachary Turner break; 6132c1f46dcSZachary Turner } 6142c1f46dcSZachary Turner 615b9c1b51eSKate Stone if (instructions) { 6167ca15ba7SLawrence D'Anna StreamFileSP output_sp(io_handler.GetOutputStreamFileSP()); 6170affb582SDave Lee if (output_sp && interactive) { 6182c1f46dcSZachary Turner output_sp->PutCString(instructions); 6192c1f46dcSZachary Turner output_sp->Flush(); 6202c1f46dcSZachary Turner } 6212c1f46dcSZachary Turner } 6222c1f46dcSZachary Turner } 6232c1f46dcSZachary Turner 62463dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler, 625b9c1b51eSKate Stone std::string &data) { 6262c1f46dcSZachary Turner io_handler.SetIsDone(true); 6278d1fb843SJonas Devlieghere bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode(); 6282c1f46dcSZachary Turner 629b9c1b51eSKate Stone switch (m_active_io_handler) { 6302c1f46dcSZachary Turner case eIOHandlerNone: 6312c1f46dcSZachary Turner break; 632b9c1b51eSKate Stone case eIOHandlerBreakpoint: { 633b9c1b51eSKate Stone std::vector<BreakpointOptions *> *bp_options_vec = 634b9c1b51eSKate Stone (std::vector<BreakpointOptions *> *)io_handler.GetUserData(); 635b9c1b51eSKate Stone for (auto bp_options : *bp_options_vec) { 6362c1f46dcSZachary Turner if (!bp_options) 6372c1f46dcSZachary Turner continue; 6382c1f46dcSZachary Turner 639a8f3ae7cSJonas Devlieghere auto data_up = std::make_unique<CommandDataPython>(); 640d5b44036SJonas Devlieghere if (!data_up) 6414e4fbe82SZachary Turner break; 642d5b44036SJonas Devlieghere data_up->user_source.SplitIntoLines(data); 6432c1f46dcSZachary Turner 644738af7a6SJim Ingham StructuredData::ObjectSP empty_args_sp; 645d5b44036SJonas Devlieghere if (GenerateBreakpointCommandCallbackData(data_up->user_source, 646738af7a6SJim Ingham data_up->script_source, 647738af7a6SJim Ingham false) 648b9c1b51eSKate Stone .Success()) { 6494e4fbe82SZachary Turner auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>( 650d5b44036SJonas Devlieghere std::move(data_up)); 651b9c1b51eSKate Stone bp_options->SetCallback( 65263dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); 653b9c1b51eSKate Stone } else if (!batch_mode) { 6547ca15ba7SLawrence D'Anna StreamFileSP error_sp = io_handler.GetErrorStreamFileSP(); 655b9c1b51eSKate Stone if (error_sp) { 6562c1f46dcSZachary Turner error_sp->Printf("Warning: No command attached to breakpoint.\n"); 6572c1f46dcSZachary Turner error_sp->Flush(); 6582c1f46dcSZachary Turner } 6592c1f46dcSZachary Turner } 6602c1f46dcSZachary Turner } 6612c1f46dcSZachary Turner m_active_io_handler = eIOHandlerNone; 662b9c1b51eSKate Stone } break; 663b9c1b51eSKate Stone case eIOHandlerWatchpoint: { 664b9c1b51eSKate Stone WatchpointOptions *wp_options = 665b9c1b51eSKate Stone (WatchpointOptions *)io_handler.GetUserData(); 666a8f3ae7cSJonas Devlieghere auto data_up = std::make_unique<WatchpointOptions::CommandData>(); 667d5b44036SJonas Devlieghere data_up->user_source.SplitIntoLines(data); 6682c1f46dcSZachary Turner 669d5b44036SJonas Devlieghere if (GenerateWatchpointCommandCallbackData(data_up->user_source, 670d5b44036SJonas Devlieghere data_up->script_source)) { 6714e4fbe82SZachary Turner auto baton_sp = 672d5b44036SJonas Devlieghere std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up)); 673b9c1b51eSKate Stone wp_options->SetCallback( 67463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp); 675b9c1b51eSKate Stone } else if (!batch_mode) { 6767ca15ba7SLawrence D'Anna StreamFileSP error_sp = io_handler.GetErrorStreamFileSP(); 677b9c1b51eSKate Stone if (error_sp) { 6782c1f46dcSZachary Turner error_sp->Printf("Warning: No command attached to breakpoint.\n"); 6792c1f46dcSZachary Turner error_sp->Flush(); 6802c1f46dcSZachary Turner } 6812c1f46dcSZachary Turner } 6822c1f46dcSZachary Turner m_active_io_handler = eIOHandlerNone; 683b9c1b51eSKate Stone } break; 6842c1f46dcSZachary Turner } 6852c1f46dcSZachary Turner } 6862c1f46dcSZachary Turner 68763dd5d25SJonas Devlieghere lldb::ScriptInterpreterSP 6888d1fb843SJonas Devlieghere ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) { 6898d1fb843SJonas Devlieghere return std::make_shared<ScriptInterpreterPythonImpl>(debugger); 69063dd5d25SJonas Devlieghere } 6912c1f46dcSZachary Turner 69263dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::LeaveSession() { 6932c1f46dcSZachary Turner Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 6942c1f46dcSZachary Turner if (log) 69563dd5d25SJonas Devlieghere log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()"); 6962c1f46dcSZachary Turner 69720b52c33SJonas Devlieghere // Unset the LLDB global variables. 69820b52c33SJonas Devlieghere PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process " 69920b52c33SJonas Devlieghere "= None; lldb.thread = None; lldb.frame = None"); 70020b52c33SJonas Devlieghere 70105097246SAdrian Prantl // checking that we have a valid thread state - since we use our own 70205097246SAdrian Prantl // threading and locking in some (rare) cases during cleanup Python may end 70305097246SAdrian Prantl // up believing we have no thread state and PyImport_AddModule will crash if 70405097246SAdrian Prantl // that is the case - since that seems to only happen when destroying the 70505097246SAdrian Prantl // SBDebugger, we can make do without clearing up stdout and stderr 7062c1f46dcSZachary Turner 7072c1f46dcSZachary Turner // rdar://problem/11292882 708b9c1b51eSKate Stone // When the current thread state is NULL, PyThreadState_Get() issues a fatal 709b9c1b51eSKate Stone // error. 710b9c1b51eSKate Stone if (PyThreadState_GetDict()) { 7112c1f46dcSZachary Turner PythonDictionary &sys_module_dict = GetSysModuleDictionary(); 712b9c1b51eSKate Stone if (sys_module_dict.IsValid()) { 713b9c1b51eSKate Stone if (m_saved_stdin.IsValid()) { 714f8b22f8fSZachary Turner sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin); 7152c1f46dcSZachary Turner m_saved_stdin.Reset(); 7162c1f46dcSZachary Turner } 717b9c1b51eSKate Stone if (m_saved_stdout.IsValid()) { 718f8b22f8fSZachary Turner sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout); 7192c1f46dcSZachary Turner m_saved_stdout.Reset(); 7202c1f46dcSZachary Turner } 721b9c1b51eSKate Stone if (m_saved_stderr.IsValid()) { 722f8b22f8fSZachary Turner sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr); 7232c1f46dcSZachary Turner m_saved_stderr.Reset(); 7242c1f46dcSZachary Turner } 7252c1f46dcSZachary Turner } 7262c1f46dcSZachary Turner } 7272c1f46dcSZachary Turner 7282c1f46dcSZachary Turner m_session_is_active = false; 7292c1f46dcSZachary Turner } 7302c1f46dcSZachary Turner 731b07823f3SLawrence D'Anna bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp, 732b07823f3SLawrence D'Anna const char *py_name, 733b07823f3SLawrence D'Anna PythonObject &save_file, 734b9c1b51eSKate Stone const char *mode) { 735b07823f3SLawrence D'Anna if (!file_sp || !*file_sp) { 736b07823f3SLawrence D'Anna save_file.Reset(); 737b07823f3SLawrence D'Anna return false; 738b07823f3SLawrence D'Anna } 739b07823f3SLawrence D'Anna File &file = *file_sp; 740b07823f3SLawrence D'Anna 741a31baf08SGreg Clayton // Flush the file before giving it to python to avoid interleaved output. 742a31baf08SGreg Clayton file.Flush(); 743a31baf08SGreg Clayton 744a31baf08SGreg Clayton PythonDictionary &sys_module_dict = GetSysModuleDictionary(); 745a31baf08SGreg Clayton 7460f783599SLawrence D'Anna auto new_file = PythonFile::FromFile(file, mode); 7470f783599SLawrence D'Anna if (!new_file) { 7480f783599SLawrence D'Anna llvm::consumeError(new_file.takeError()); 7490f783599SLawrence D'Anna return false; 7500f783599SLawrence D'Anna } 7510f783599SLawrence D'Anna 752b07823f3SLawrence D'Anna save_file = sys_module_dict.GetItemForKey(PythonString(py_name)); 753a31baf08SGreg Clayton 7540f783599SLawrence D'Anna sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get()); 755a31baf08SGreg Clayton return true; 756a31baf08SGreg Clayton } 757a31baf08SGreg Clayton 75863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags, 759b07823f3SLawrence D'Anna FileSP in_sp, FileSP out_sp, 760b07823f3SLawrence D'Anna FileSP err_sp) { 761b9c1b51eSKate Stone // If we have already entered the session, without having officially 'left' 76205097246SAdrian Prantl // it, then there is no need to 'enter' it again. 7632c1f46dcSZachary Turner Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 764b9c1b51eSKate Stone if (m_session_is_active) { 76563e5fb76SJonas Devlieghere LLDB_LOGF( 76663e5fb76SJonas Devlieghere log, 76763dd5d25SJonas Devlieghere "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 768b9c1b51eSKate Stone ") session is already active, returning without doing anything", 769b9c1b51eSKate Stone on_entry_flags); 7702c1f46dcSZachary Turner return false; 7712c1f46dcSZachary Turner } 7722c1f46dcSZachary Turner 77363e5fb76SJonas Devlieghere LLDB_LOGF( 77463e5fb76SJonas Devlieghere log, 77563e5fb76SJonas Devlieghere "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")", 776b9c1b51eSKate Stone on_entry_flags); 7772c1f46dcSZachary Turner 7782c1f46dcSZachary Turner m_session_is_active = true; 7792c1f46dcSZachary Turner 7802c1f46dcSZachary Turner StreamString run_string; 7812c1f46dcSZachary Turner 782b9c1b51eSKate Stone if (on_entry_flags & Locker::InitGlobals) { 783b9c1b51eSKate Stone run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, 7848d1fb843SJonas Devlieghere m_dictionary_name.c_str(), m_debugger.GetID()); 785b9c1b51eSKate Stone run_string.Printf( 786b9c1b51eSKate Stone "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", 7878d1fb843SJonas Devlieghere m_debugger.GetID()); 7882c1f46dcSZachary Turner run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()"); 7892c1f46dcSZachary Turner run_string.PutCString("; lldb.process = lldb.target.GetProcess()"); 7902c1f46dcSZachary Turner run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()"); 7912c1f46dcSZachary Turner run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()"); 7922c1f46dcSZachary Turner run_string.PutCString("')"); 793b9c1b51eSKate Stone } else { 79405097246SAdrian Prantl // If we aren't initing the globals, we should still always set the 79505097246SAdrian Prantl // debugger (since that is always unique.) 796b9c1b51eSKate Stone run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, 7978d1fb843SJonas Devlieghere m_dictionary_name.c_str(), m_debugger.GetID()); 798b9c1b51eSKate Stone run_string.Printf( 799b9c1b51eSKate Stone "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", 8008d1fb843SJonas Devlieghere m_debugger.GetID()); 8012c1f46dcSZachary Turner run_string.PutCString("')"); 8022c1f46dcSZachary Turner } 8032c1f46dcSZachary Turner 8042c1f46dcSZachary Turner PyRun_SimpleString(run_string.GetData()); 8052c1f46dcSZachary Turner run_string.Clear(); 8062c1f46dcSZachary Turner 8072c1f46dcSZachary Turner PythonDictionary &sys_module_dict = GetSysModuleDictionary(); 808b9c1b51eSKate Stone if (sys_module_dict.IsValid()) { 809b07823f3SLawrence D'Anna lldb::FileSP top_in_sp; 810b07823f3SLawrence D'Anna lldb::StreamFileSP top_out_sp, top_err_sp; 811b07823f3SLawrence D'Anna if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp) 812b07823f3SLawrence D'Anna m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp, 813b07823f3SLawrence D'Anna top_err_sp); 8142c1f46dcSZachary Turner 815b9c1b51eSKate Stone if (on_entry_flags & Locker::NoSTDIN) { 8162c1f46dcSZachary Turner m_saved_stdin.Reset(); 817b9c1b51eSKate Stone } else { 818b07823f3SLawrence D'Anna if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) { 819b07823f3SLawrence D'Anna if (top_in_sp) 820b07823f3SLawrence D'Anna SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r"); 8212c1f46dcSZachary Turner } 822a31baf08SGreg Clayton } 823a31baf08SGreg Clayton 824b07823f3SLawrence D'Anna if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) { 825b07823f3SLawrence D'Anna if (top_out_sp) 826b07823f3SLawrence D'Anna SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w"); 827a31baf08SGreg Clayton } 828a31baf08SGreg Clayton 829b07823f3SLawrence D'Anna if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) { 830b07823f3SLawrence D'Anna if (top_err_sp) 831b07823f3SLawrence D'Anna SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w"); 832a31baf08SGreg Clayton } 8332c1f46dcSZachary Turner } 8342c1f46dcSZachary Turner 8352c1f46dcSZachary Turner if (PyErr_Occurred()) 8362c1f46dcSZachary Turner PyErr_Clear(); 8372c1f46dcSZachary Turner 8382c1f46dcSZachary Turner return true; 8392c1f46dcSZachary Turner } 8402c1f46dcSZachary Turner 84104edd189SLawrence D'Anna PythonModule &ScriptInterpreterPythonImpl::GetMainModule() { 842f8b22f8fSZachary Turner if (!m_main_module.IsValid()) 84304edd189SLawrence D'Anna m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__")); 8442c1f46dcSZachary Turner return m_main_module; 8452c1f46dcSZachary Turner } 8462c1f46dcSZachary Turner 84763dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() { 848f8b22f8fSZachary Turner if (m_session_dict.IsValid()) 849f8b22f8fSZachary Turner return m_session_dict; 850f8b22f8fSZachary Turner 8512c1f46dcSZachary Turner PythonObject &main_module = GetMainModule(); 852f8b22f8fSZachary Turner if (!main_module.IsValid()) 853f8b22f8fSZachary Turner return m_session_dict; 854f8b22f8fSZachary Turner 855b9c1b51eSKate Stone PythonDictionary main_dict(PyRefType::Borrowed, 856b9c1b51eSKate Stone PyModule_GetDict(main_module.get())); 857f8b22f8fSZachary Turner if (!main_dict.IsValid()) 858f8b22f8fSZachary Turner return m_session_dict; 859f8b22f8fSZachary Turner 860722b6189SLawrence D'Anna m_session_dict = unwrapIgnoringErrors( 861722b6189SLawrence D'Anna As<PythonDictionary>(main_dict.GetItem(m_dictionary_name))); 8622c1f46dcSZachary Turner return m_session_dict; 8632c1f46dcSZachary Turner } 8642c1f46dcSZachary Turner 86563dd5d25SJonas Devlieghere PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() { 866f8b22f8fSZachary Turner if (m_sys_module_dict.IsValid()) 867f8b22f8fSZachary Turner return m_sys_module_dict; 868722b6189SLawrence D'Anna PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys")); 869722b6189SLawrence D'Anna m_sys_module_dict = sys_module.GetDictionary(); 8702c1f46dcSZachary Turner return m_sys_module_dict; 8712c1f46dcSZachary Turner } 8722c1f46dcSZachary Turner 873a69bbe02SLawrence D'Anna llvm::Expected<unsigned> 874a69bbe02SLawrence D'Anna ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable( 875a69bbe02SLawrence D'Anna const llvm::StringRef &callable_name) { 876738af7a6SJim Ingham if (callable_name.empty()) { 877738af7a6SJim Ingham return llvm::createStringError( 878738af7a6SJim Ingham llvm::inconvertibleErrorCode(), 879738af7a6SJim Ingham "called with empty callable name."); 880738af7a6SJim Ingham } 881738af7a6SJim Ingham Locker py_lock(this, Locker::AcquireLock | 882738af7a6SJim Ingham Locker::InitSession | 883738af7a6SJim Ingham Locker::NoSTDIN); 884738af7a6SJim Ingham auto dict = PythonModule::MainModule() 885738af7a6SJim Ingham .ResolveName<PythonDictionary>(m_dictionary_name); 886a69bbe02SLawrence D'Anna auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>( 887a69bbe02SLawrence D'Anna callable_name, dict); 888738af7a6SJim Ingham if (!pfunc.IsAllocated()) { 889738af7a6SJim Ingham return llvm::createStringError( 890738af7a6SJim Ingham llvm::inconvertibleErrorCode(), 891738af7a6SJim Ingham "can't find callable: %s", callable_name.str().c_str()); 892738af7a6SJim Ingham } 893adbf64ccSLawrence D'Anna llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo(); 894adbf64ccSLawrence D'Anna if (!arg_info) 895adbf64ccSLawrence D'Anna return arg_info.takeError(); 896adbf64ccSLawrence D'Anna return arg_info.get().max_positional_args; 897738af7a6SJim Ingham } 898738af7a6SJim Ingham 899b9c1b51eSKate Stone static std::string GenerateUniqueName(const char *base_name_wanted, 9002c1f46dcSZachary Turner uint32_t &functions_counter, 901b9c1b51eSKate Stone const void *name_token = nullptr) { 9022c1f46dcSZachary Turner StreamString sstr; 9032c1f46dcSZachary Turner 9042c1f46dcSZachary Turner if (!base_name_wanted) 9052c1f46dcSZachary Turner return std::string(); 9062c1f46dcSZachary Turner 9072c1f46dcSZachary Turner if (!name_token) 9082c1f46dcSZachary Turner sstr.Printf("%s_%d", base_name_wanted, functions_counter++); 9092c1f46dcSZachary Turner else 9102c1f46dcSZachary Turner sstr.Printf("%s_%p", base_name_wanted, name_token); 9112c1f46dcSZachary Turner 912adcd0268SBenjamin Kramer return std::string(sstr.GetString()); 9132c1f46dcSZachary Turner } 9142c1f46dcSZachary Turner 91563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() { 916f8b22f8fSZachary Turner if (m_run_one_line_function.IsValid()) 917f8b22f8fSZachary Turner return true; 918f8b22f8fSZachary Turner 919b9c1b51eSKate Stone PythonObject module(PyRefType::Borrowed, 920b9c1b51eSKate Stone PyImport_AddModule("lldb.embedded_interpreter")); 921f8b22f8fSZachary Turner if (!module.IsValid()) 922f8b22f8fSZachary Turner return false; 923f8b22f8fSZachary Turner 924b9c1b51eSKate Stone PythonDictionary module_dict(PyRefType::Borrowed, 925b9c1b51eSKate Stone PyModule_GetDict(module.get())); 926f8b22f8fSZachary Turner if (!module_dict.IsValid()) 927f8b22f8fSZachary Turner return false; 928f8b22f8fSZachary Turner 929b9c1b51eSKate Stone m_run_one_line_function = 930b9c1b51eSKate Stone module_dict.GetItemForKey(PythonString("run_one_line")); 931b9c1b51eSKate Stone m_run_one_line_str_global = 932b9c1b51eSKate Stone module_dict.GetItemForKey(PythonString("g_run_one_line_str")); 933f8b22f8fSZachary Turner return m_run_one_line_function.IsValid(); 9342c1f46dcSZachary Turner } 9352c1f46dcSZachary Turner 93663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLine( 9374d51a902SRaphael Isemann llvm::StringRef command, CommandReturnObject *result, 938b9c1b51eSKate Stone const ExecuteScriptOptions &options) { 939d6c062bcSRaphael Isemann std::string command_str = command.str(); 940d6c062bcSRaphael Isemann 9412c1f46dcSZachary Turner if (!m_valid_session) 9422c1f46dcSZachary Turner return false; 9432c1f46dcSZachary Turner 9444d51a902SRaphael Isemann if (!command.empty()) { 945b9c1b51eSKate Stone // We want to call run_one_line, passing in the dictionary and the command 94605097246SAdrian Prantl // string. We cannot do this through PyRun_SimpleString here because the 94705097246SAdrian Prantl // command string may contain escaped characters, and putting it inside 948b9c1b51eSKate Stone // another string to pass to PyRun_SimpleString messes up the escaping. So 94905097246SAdrian Prantl // we use the following more complicated method to pass the command string 95005097246SAdrian Prantl // directly down to Python. 951d79273c9SJonas Devlieghere llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>> 95284228365SJonas Devlieghere io_redirect_or_error = ScriptInterpreterIORedirect::Create( 95384228365SJonas Devlieghere options.GetEnableIO(), m_debugger, result); 954d79273c9SJonas Devlieghere if (!io_redirect_or_error) { 955d79273c9SJonas Devlieghere if (result) 956d79273c9SJonas Devlieghere result->AppendErrorWithFormatv( 957d79273c9SJonas Devlieghere "failed to redirect I/O: {0}\n", 958d79273c9SJonas Devlieghere llvm::fmt_consume(io_redirect_or_error.takeError())); 959d79273c9SJonas Devlieghere else 960d79273c9SJonas Devlieghere llvm::consumeError(io_redirect_or_error.takeError()); 9612fce1137SLawrence D'Anna return false; 9622fce1137SLawrence D'Anna } 963d79273c9SJonas Devlieghere 964d79273c9SJonas Devlieghere ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error; 9652c1f46dcSZachary Turner 96632064024SZachary Turner bool success = false; 96732064024SZachary Turner { 96805097246SAdrian Prantl // WARNING! It's imperative that this RAII scope be as tight as 96905097246SAdrian Prantl // possible. In particular, the scope must end *before* we try to join 97005097246SAdrian Prantl // the read thread. The reason for this is that a pre-requisite for 97105097246SAdrian Prantl // joining the read thread is that we close the write handle (to break 97205097246SAdrian Prantl // the pipe and cause it to wake up and exit). But acquiring the GIL as 97305097246SAdrian Prantl // below will redirect Python's stdio to use this same handle. If we 97405097246SAdrian Prantl // close the handle while Python is still using it, bad things will 97505097246SAdrian Prantl // happen. 976b9c1b51eSKate Stone Locker locker( 977b9c1b51eSKate Stone this, 97863dd5d25SJonas Devlieghere Locker::AcquireLock | Locker::InitSession | 97963dd5d25SJonas Devlieghere (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) | 9802c1f46dcSZachary Turner ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN), 981d79273c9SJonas Devlieghere Locker::FreeAcquiredLock | Locker::TearDownSession, 982d79273c9SJonas Devlieghere io_redirect.GetInputFile(), io_redirect.GetOutputFile(), 983d79273c9SJonas Devlieghere io_redirect.GetErrorFile()); 9842c1f46dcSZachary Turner 9852c1f46dcSZachary Turner // Find the correct script interpreter dictionary in the main module. 9862c1f46dcSZachary Turner PythonDictionary &session_dict = GetSessionDictionary(); 987b9c1b51eSKate Stone if (session_dict.IsValid()) { 988b9c1b51eSKate Stone if (GetEmbeddedInterpreterModuleObjects()) { 989b9c1b51eSKate Stone if (PyCallable_Check(m_run_one_line_function.get())) { 990b9c1b51eSKate Stone PythonObject pargs( 991b9c1b51eSKate Stone PyRefType::Owned, 992d6c062bcSRaphael Isemann Py_BuildValue("(Os)", session_dict.get(), command_str.c_str())); 993b9c1b51eSKate Stone if (pargs.IsValid()) { 994b9c1b51eSKate Stone PythonObject return_value( 995b9c1b51eSKate Stone PyRefType::Owned, 996b9c1b51eSKate Stone PyObject_CallObject(m_run_one_line_function.get(), 997b9c1b51eSKate Stone pargs.get())); 998f8b22f8fSZachary Turner if (return_value.IsValid()) 9992c1f46dcSZachary Turner success = true; 1000b9c1b51eSKate Stone else if (options.GetMaskoutErrors() && PyErr_Occurred()) { 10012c1f46dcSZachary Turner PyErr_Print(); 10022c1f46dcSZachary Turner PyErr_Clear(); 10032c1f46dcSZachary Turner } 10042c1f46dcSZachary Turner } 10052c1f46dcSZachary Turner } 10062c1f46dcSZachary Turner } 10072c1f46dcSZachary Turner } 10082c1f46dcSZachary Turner 1009d79273c9SJonas Devlieghere io_redirect.Flush(); 10102c1f46dcSZachary Turner } 10112c1f46dcSZachary Turner 10122c1f46dcSZachary Turner if (success) 10132c1f46dcSZachary Turner return true; 10142c1f46dcSZachary Turner 10152c1f46dcSZachary Turner // The one-liner failed. Append the error message. 10164d51a902SRaphael Isemann if (result) { 1017b9c1b51eSKate Stone result->AppendErrorWithFormat( 10184d51a902SRaphael Isemann "python failed attempting to evaluate '%s'\n", command_str.c_str()); 10194d51a902SRaphael Isemann } 10202c1f46dcSZachary Turner return false; 10212c1f46dcSZachary Turner } 10222c1f46dcSZachary Turner 10232c1f46dcSZachary Turner if (result) 10242c1f46dcSZachary Turner result->AppendError("empty command passed to python\n"); 10252c1f46dcSZachary Turner return false; 10262c1f46dcSZachary Turner } 10272c1f46dcSZachary Turner 102863dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() { 10295c1c8443SJonas Devlieghere LLDB_SCOPED_TIMER(); 10302c1f46dcSZachary Turner 10318d1fb843SJonas Devlieghere Debugger &debugger = m_debugger; 10322c1f46dcSZachary Turner 1033b9c1b51eSKate Stone // At the moment, the only time the debugger does not have an input file 103405097246SAdrian Prantl // handle is when this is called directly from Python, in which case it is 103505097246SAdrian Prantl // both dangerous and unnecessary (not to mention confusing) to try to embed 103605097246SAdrian Prantl // a running interpreter loop inside the already running Python interpreter 103705097246SAdrian Prantl // loop, so we won't do it. 10382c1f46dcSZachary Turner 10397ca15ba7SLawrence D'Anna if (!debugger.GetInputFile().IsValid()) 10402c1f46dcSZachary Turner return; 10412c1f46dcSZachary Turner 10422c1f46dcSZachary Turner IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this)); 1043b9c1b51eSKate Stone if (io_handler_sp) { 10447ce2de2cSJonas Devlieghere debugger.RunIOHandlerAsync(io_handler_sp); 10452c1f46dcSZachary Turner } 10462c1f46dcSZachary Turner } 10472c1f46dcSZachary Turner 104863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::Interrupt() { 10492c1f46dcSZachary Turner Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 10502c1f46dcSZachary Turner 1051b9c1b51eSKate Stone if (IsExecutingPython()) { 1052b1cf558dSEnrico Granata PyThreadState *state = PyThreadState_GET(); 10532c1f46dcSZachary Turner if (!state) 10542c1f46dcSZachary Turner state = GetThreadState(); 1055b9c1b51eSKate Stone if (state) { 10562c1f46dcSZachary Turner long tid = state->thread_id; 105722c8efcdSZachary Turner PyThreadState_Swap(state); 10582c1f46dcSZachary Turner int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt); 105963e5fb76SJonas Devlieghere LLDB_LOGF(log, 106063e5fb76SJonas Devlieghere "ScriptInterpreterPythonImpl::Interrupt() sending " 1061b9c1b51eSKate Stone "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...", 1062b9c1b51eSKate Stone tid, num_threads); 10632c1f46dcSZachary Turner return true; 10642c1f46dcSZachary Turner } 10652c1f46dcSZachary Turner } 106663e5fb76SJonas Devlieghere LLDB_LOGF(log, 106763dd5d25SJonas Devlieghere "ScriptInterpreterPythonImpl::Interrupt() python code not running, " 1068b9c1b51eSKate Stone "can't interrupt"); 10692c1f46dcSZachary Turner return false; 10702c1f46dcSZachary Turner } 107104edd189SLawrence D'Anna 107263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn( 10734d51a902SRaphael Isemann llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type, 1074b9c1b51eSKate Stone void *ret_value, const ExecuteScriptOptions &options) { 10752c1f46dcSZachary Turner 107663dd5d25SJonas Devlieghere Locker locker(this, 107763dd5d25SJonas Devlieghere Locker::AcquireLock | Locker::InitSession | 107863dd5d25SJonas Devlieghere (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) | 1079b9c1b51eSKate Stone Locker::NoSTDIN, 108063dd5d25SJonas Devlieghere Locker::FreeAcquiredLock | Locker::TearDownSession); 10812c1f46dcSZachary Turner 108204edd189SLawrence D'Anna PythonModule &main_module = GetMainModule(); 108304edd189SLawrence D'Anna PythonDictionary globals = main_module.GetDictionary(); 10842c1f46dcSZachary Turner 10852c1f46dcSZachary Turner PythonDictionary locals = GetSessionDictionary(); 108604edd189SLawrence D'Anna if (!locals.IsValid()) 1087722b6189SLawrence D'Anna locals = unwrapIgnoringErrors( 1088722b6189SLawrence D'Anna As<PythonDictionary>(globals.GetAttribute(m_dictionary_name))); 1089f8b22f8fSZachary Turner if (!locals.IsValid()) 10902c1f46dcSZachary Turner locals = globals; 10912c1f46dcSZachary Turner 109204edd189SLawrence D'Anna Expected<PythonObject> maybe_py_return = 109304edd189SLawrence D'Anna runStringOneLine(in_string, globals, locals); 10942c1f46dcSZachary Turner 109504edd189SLawrence D'Anna if (!maybe_py_return) { 109604edd189SLawrence D'Anna llvm::handleAllErrors( 109704edd189SLawrence D'Anna maybe_py_return.takeError(), 109804edd189SLawrence D'Anna [&](PythonException &E) { 109904edd189SLawrence D'Anna E.Restore(); 110004edd189SLawrence D'Anna if (options.GetMaskoutErrors()) { 110104edd189SLawrence D'Anna if (E.Matches(PyExc_SyntaxError)) { 110204edd189SLawrence D'Anna PyErr_Print(); 11032c1f46dcSZachary Turner } 110404edd189SLawrence D'Anna PyErr_Clear(); 110504edd189SLawrence D'Anna } 110604edd189SLawrence D'Anna }, 110704edd189SLawrence D'Anna [](const llvm::ErrorInfoBase &E) {}); 110804edd189SLawrence D'Anna return false; 11092c1f46dcSZachary Turner } 11102c1f46dcSZachary Turner 111104edd189SLawrence D'Anna PythonObject py_return = std::move(maybe_py_return.get()); 111204edd189SLawrence D'Anna assert(py_return.IsValid()); 111304edd189SLawrence D'Anna 1114b9c1b51eSKate Stone switch (return_type) { 11152c1f46dcSZachary Turner case eScriptReturnTypeCharPtr: // "char *" 11162c1f46dcSZachary Turner { 11172c1f46dcSZachary Turner const char format[3] = "s#"; 111804edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (char **)ret_value); 11192c1f46dcSZachary Turner } 1120b9c1b51eSKate Stone case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == 1121b9c1b51eSKate Stone // Py_None 11222c1f46dcSZachary Turner { 11232c1f46dcSZachary Turner const char format[3] = "z"; 112404edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (char **)ret_value); 11252c1f46dcSZachary Turner } 1126b9c1b51eSKate Stone case eScriptReturnTypeBool: { 11272c1f46dcSZachary Turner const char format[2] = "b"; 112804edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (bool *)ret_value); 11292c1f46dcSZachary Turner } 1130b9c1b51eSKate Stone case eScriptReturnTypeShortInt: { 11312c1f46dcSZachary Turner const char format[2] = "h"; 113204edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (short *)ret_value); 11332c1f46dcSZachary Turner } 1134b9c1b51eSKate Stone case eScriptReturnTypeShortIntUnsigned: { 11352c1f46dcSZachary Turner const char format[2] = "H"; 113604edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value); 11372c1f46dcSZachary Turner } 1138b9c1b51eSKate Stone case eScriptReturnTypeInt: { 11392c1f46dcSZachary Turner const char format[2] = "i"; 114004edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (int *)ret_value); 11412c1f46dcSZachary Turner } 1142b9c1b51eSKate Stone case eScriptReturnTypeIntUnsigned: { 11432c1f46dcSZachary Turner const char format[2] = "I"; 114404edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value); 11452c1f46dcSZachary Turner } 1146b9c1b51eSKate Stone case eScriptReturnTypeLongInt: { 11472c1f46dcSZachary Turner const char format[2] = "l"; 114804edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (long *)ret_value); 11492c1f46dcSZachary Turner } 1150b9c1b51eSKate Stone case eScriptReturnTypeLongIntUnsigned: { 11512c1f46dcSZachary Turner const char format[2] = "k"; 115204edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value); 11532c1f46dcSZachary Turner } 1154b9c1b51eSKate Stone case eScriptReturnTypeLongLong: { 11552c1f46dcSZachary Turner const char format[2] = "L"; 115604edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (long long *)ret_value); 11572c1f46dcSZachary Turner } 1158b9c1b51eSKate Stone case eScriptReturnTypeLongLongUnsigned: { 11592c1f46dcSZachary Turner const char format[2] = "K"; 116004edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, 116104edd189SLawrence D'Anna (unsigned long long *)ret_value); 11622c1f46dcSZachary Turner } 1163b9c1b51eSKate Stone case eScriptReturnTypeFloat: { 11642c1f46dcSZachary Turner const char format[2] = "f"; 116504edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (float *)ret_value); 11662c1f46dcSZachary Turner } 1167b9c1b51eSKate Stone case eScriptReturnTypeDouble: { 11682c1f46dcSZachary Turner const char format[2] = "d"; 116904edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (double *)ret_value); 11702c1f46dcSZachary Turner } 1171b9c1b51eSKate Stone case eScriptReturnTypeChar: { 11722c1f46dcSZachary Turner const char format[2] = "c"; 117304edd189SLawrence D'Anna return PyArg_Parse(py_return.get(), format, (char *)ret_value); 11742c1f46dcSZachary Turner } 1175b9c1b51eSKate Stone case eScriptReturnTypeOpaqueObject: { 117604edd189SLawrence D'Anna *((PyObject **)ret_value) = py_return.release(); 117704edd189SLawrence D'Anna return true; 11782c1f46dcSZachary Turner } 11792c1f46dcSZachary Turner } 11801dfb1a85SPavel Labath llvm_unreachable("Fully covered switch!"); 11812c1f46dcSZachary Turner } 11822c1f46dcSZachary Turner 118363dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExecuteMultipleLines( 1184b9c1b51eSKate Stone const char *in_string, const ExecuteScriptOptions &options) { 118504edd189SLawrence D'Anna 118604edd189SLawrence D'Anna if (in_string == nullptr) 118704edd189SLawrence D'Anna return Status(); 11882c1f46dcSZachary Turner 118963dd5d25SJonas Devlieghere Locker locker(this, 119063dd5d25SJonas Devlieghere Locker::AcquireLock | Locker::InitSession | 119163dd5d25SJonas Devlieghere (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) | 1192b9c1b51eSKate Stone Locker::NoSTDIN, 119363dd5d25SJonas Devlieghere Locker::FreeAcquiredLock | Locker::TearDownSession); 11942c1f46dcSZachary Turner 119504edd189SLawrence D'Anna PythonModule &main_module = GetMainModule(); 119604edd189SLawrence D'Anna PythonDictionary globals = main_module.GetDictionary(); 11972c1f46dcSZachary Turner 11982c1f46dcSZachary Turner PythonDictionary locals = GetSessionDictionary(); 1199f8b22f8fSZachary Turner if (!locals.IsValid()) 1200722b6189SLawrence D'Anna locals = unwrapIgnoringErrors( 1201722b6189SLawrence D'Anna As<PythonDictionary>(globals.GetAttribute(m_dictionary_name))); 1202f8b22f8fSZachary Turner if (!locals.IsValid()) 12032c1f46dcSZachary Turner locals = globals; 12042c1f46dcSZachary Turner 120504edd189SLawrence D'Anna Expected<PythonObject> return_value = 120604edd189SLawrence D'Anna runStringMultiLine(in_string, globals, locals); 12072c1f46dcSZachary Turner 120804edd189SLawrence D'Anna if (!return_value) { 120904edd189SLawrence D'Anna llvm::Error error = 121004edd189SLawrence D'Anna llvm::handleErrors(return_value.takeError(), [&](PythonException &E) { 121104edd189SLawrence D'Anna llvm::Error error = llvm::createStringError( 121204edd189SLawrence D'Anna llvm::inconvertibleErrorCode(), E.ReadBacktrace()); 121304edd189SLawrence D'Anna if (!options.GetMaskoutErrors()) 121404edd189SLawrence D'Anna E.Restore(); 12152c1f46dcSZachary Turner return error; 121604edd189SLawrence D'Anna }); 121704edd189SLawrence D'Anna return Status(std::move(error)); 121804edd189SLawrence D'Anna } 121904edd189SLawrence D'Anna 122004edd189SLawrence D'Anna return Status(); 12212c1f46dcSZachary Turner } 12222c1f46dcSZachary Turner 122363dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback( 1224b9c1b51eSKate Stone std::vector<BreakpointOptions *> &bp_options_vec, 1225b9c1b51eSKate Stone CommandReturnObject &result) { 12262c1f46dcSZachary Turner m_active_io_handler = eIOHandlerBreakpoint; 12278d1fb843SJonas Devlieghere m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler( 1228a6faf851SJonas Devlieghere " ", *this, &bp_options_vec); 12292c1f46dcSZachary Turner } 12302c1f46dcSZachary Turner 123163dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback( 1232b9c1b51eSKate Stone WatchpointOptions *wp_options, CommandReturnObject &result) { 12332c1f46dcSZachary Turner m_active_io_handler = eIOHandlerWatchpoint; 12348d1fb843SJonas Devlieghere m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler( 1235a6faf851SJonas Devlieghere " ", *this, wp_options); 12362c1f46dcSZachary Turner } 12372c1f46dcSZachary Turner 1238738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction( 1239738af7a6SJim Ingham BreakpointOptions *bp_options, const char *function_name, 1240738af7a6SJim Ingham StructuredData::ObjectSP extra_args_sp) { 1241738af7a6SJim Ingham Status error; 12422c1f46dcSZachary Turner // For now just cons up a oneliner that calls the provided function. 12432c1f46dcSZachary Turner std::string oneliner("return "); 12442c1f46dcSZachary Turner oneliner += function_name; 1245738af7a6SJim Ingham 1246a69bbe02SLawrence D'Anna llvm::Expected<unsigned> maybe_args = 1247a69bbe02SLawrence D'Anna GetMaxPositionalArgumentsForCallable(function_name); 1248738af7a6SJim Ingham if (!maybe_args) { 1249a69bbe02SLawrence D'Anna error.SetErrorStringWithFormat( 1250a69bbe02SLawrence D'Anna "could not get num args: %s", 1251738af7a6SJim Ingham llvm::toString(maybe_args.takeError()).c_str()); 1252738af7a6SJim Ingham return error; 1253738af7a6SJim Ingham } 1254a69bbe02SLawrence D'Anna size_t max_args = *maybe_args; 1255738af7a6SJim Ingham 1256738af7a6SJim Ingham bool uses_extra_args = false; 1257a69bbe02SLawrence D'Anna if (max_args >= 4) { 1258738af7a6SJim Ingham uses_extra_args = true; 1259738af7a6SJim Ingham oneliner += "(frame, bp_loc, extra_args, internal_dict)"; 1260a69bbe02SLawrence D'Anna } else if (max_args >= 3) { 1261738af7a6SJim Ingham if (extra_args_sp) { 1262738af7a6SJim Ingham error.SetErrorString("cannot pass extra_args to a three argument callback" 1263738af7a6SJim Ingham ); 1264738af7a6SJim Ingham return error; 1265738af7a6SJim Ingham } 1266738af7a6SJim Ingham uses_extra_args = false; 12672c1f46dcSZachary Turner oneliner += "(frame, bp_loc, internal_dict)"; 1268738af7a6SJim Ingham } else { 1269738af7a6SJim Ingham error.SetErrorStringWithFormat("expected 3 or 4 argument " 1270a69bbe02SLawrence D'Anna "function, %s can only take %zu", 1271a69bbe02SLawrence D'Anna function_name, max_args); 1272738af7a6SJim Ingham return error; 1273738af7a6SJim Ingham } 1274738af7a6SJim Ingham 1275738af7a6SJim Ingham SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp, 1276738af7a6SJim Ingham uses_extra_args); 1277738af7a6SJim Ingham return error; 12782c1f46dcSZachary Turner } 12792c1f46dcSZachary Turner 128063dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( 1281f7e07256SJim Ingham BreakpointOptions *bp_options, 1282f7e07256SJim Ingham std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) { 128397206d57SZachary Turner Status error; 1284f7e07256SJim Ingham error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source, 1285738af7a6SJim Ingham cmd_data_up->script_source, 1286738af7a6SJim Ingham false); 1287f7e07256SJim Ingham if (error.Fail()) { 1288f7e07256SJim Ingham return error; 1289f7e07256SJim Ingham } 1290f7e07256SJim Ingham auto baton_sp = 1291f7e07256SJim Ingham std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up)); 129263dd5d25SJonas Devlieghere bp_options->SetCallback( 129363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); 1294f7e07256SJim Ingham return error; 1295f7e07256SJim Ingham } 1296f7e07256SJim Ingham 129763dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( 1298b9c1b51eSKate Stone BreakpointOptions *bp_options, const char *command_body_text) { 1299738af7a6SJim Ingham return SetBreakpointCommandCallback(bp_options, command_body_text, {},false); 1300738af7a6SJim Ingham } 13012c1f46dcSZachary Turner 1302738af7a6SJim Ingham // Set a Python one-liner as the callback for the breakpoint. 1303738af7a6SJim Ingham Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( 1304738af7a6SJim Ingham BreakpointOptions *bp_options, const char *command_body_text, 1305738af7a6SJim Ingham StructuredData::ObjectSP extra_args_sp, 1306738af7a6SJim Ingham bool uses_extra_args) { 1307738af7a6SJim Ingham auto data_up = std::make_unique<CommandDataPython>(extra_args_sp); 1308b9c1b51eSKate Stone // Split the command_body_text into lines, and pass that to 130905097246SAdrian Prantl // GenerateBreakpointCommandCallbackData. That will wrap the body in an 131005097246SAdrian Prantl // auto-generated function, and return the function name in script_source. 131105097246SAdrian Prantl // That is what the callback will actually invoke. 13122c1f46dcSZachary Turner 1313d5b44036SJonas Devlieghere data_up->user_source.SplitIntoLines(command_body_text); 1314d5b44036SJonas Devlieghere Status error = GenerateBreakpointCommandCallbackData(data_up->user_source, 1315738af7a6SJim Ingham data_up->script_source, 1316738af7a6SJim Ingham uses_extra_args); 1317b9c1b51eSKate Stone if (error.Success()) { 13184e4fbe82SZachary Turner auto baton_sp = 1319d5b44036SJonas Devlieghere std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up)); 132063dd5d25SJonas Devlieghere bp_options->SetCallback( 132163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); 13222c1f46dcSZachary Turner return error; 132393571c3cSJonas Devlieghere } 13242c1f46dcSZachary Turner return error; 13252c1f46dcSZachary Turner } 13262c1f46dcSZachary Turner 13272c1f46dcSZachary Turner // Set a Python one-liner as the callback for the watchpoint. 132863dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback( 1329b9c1b51eSKate Stone WatchpointOptions *wp_options, const char *oneliner) { 1330a8f3ae7cSJonas Devlieghere auto data_up = std::make_unique<WatchpointOptions::CommandData>(); 13312c1f46dcSZachary Turner 13322c1f46dcSZachary Turner // It's necessary to set both user_source and script_source to the oneliner. 1333b9c1b51eSKate Stone // The former is used to generate callback description (as in watchpoint 133405097246SAdrian Prantl // command list) while the latter is used for Python to interpret during the 133505097246SAdrian Prantl // actual callback. 13362c1f46dcSZachary Turner 1337d5b44036SJonas Devlieghere data_up->user_source.AppendString(oneliner); 1338d5b44036SJonas Devlieghere data_up->script_source.assign(oneliner); 13392c1f46dcSZachary Turner 1340d5b44036SJonas Devlieghere if (GenerateWatchpointCommandCallbackData(data_up->user_source, 1341d5b44036SJonas Devlieghere data_up->script_source)) { 13424e4fbe82SZachary Turner auto baton_sp = 1343d5b44036SJonas Devlieghere std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up)); 134463dd5d25SJonas Devlieghere wp_options->SetCallback( 134563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp); 13462c1f46dcSZachary Turner } 13472c1f46dcSZachary Turner 13482c1f46dcSZachary Turner return; 13492c1f46dcSZachary Turner } 13502c1f46dcSZachary Turner 135163dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter( 1352b9c1b51eSKate Stone StringList &function_def) { 13532c1f46dcSZachary Turner // Convert StringList to one long, newline delimited, const char *. 13542c1f46dcSZachary Turner std::string function_def_string(function_def.CopyList()); 13552c1f46dcSZachary Turner 135697206d57SZachary Turner Status error = ExecuteMultipleLines( 1357b9c1b51eSKate Stone function_def_string.c_str(), 1358b9c1b51eSKate Stone ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false)); 13592c1f46dcSZachary Turner return error; 13602c1f46dcSZachary Turner } 13612c1f46dcSZachary Turner 136263dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature, 1363b9c1b51eSKate Stone const StringList &input) { 136497206d57SZachary Turner Status error; 13652c1f46dcSZachary Turner int num_lines = input.GetSize(); 1366b9c1b51eSKate Stone if (num_lines == 0) { 13672c1f46dcSZachary Turner error.SetErrorString("No input data."); 13682c1f46dcSZachary Turner return error; 13692c1f46dcSZachary Turner } 13702c1f46dcSZachary Turner 1371b9c1b51eSKate Stone if (!signature || *signature == 0) { 13722c1f46dcSZachary Turner error.SetErrorString("No output function name."); 13732c1f46dcSZachary Turner return error; 13742c1f46dcSZachary Turner } 13752c1f46dcSZachary Turner 13762c1f46dcSZachary Turner StreamString sstr; 13772c1f46dcSZachary Turner StringList auto_generated_function; 13782c1f46dcSZachary Turner auto_generated_function.AppendString(signature); 1379b9c1b51eSKate Stone auto_generated_function.AppendString( 1380b9c1b51eSKate Stone " global_dict = globals()"); // Grab the global dictionary 1381b9c1b51eSKate Stone auto_generated_function.AppendString( 1382b9c1b51eSKate Stone " new_keys = internal_dict.keys()"); // Make a list of keys in the 1383b9c1b51eSKate Stone // session dict 1384b9c1b51eSKate Stone auto_generated_function.AppendString( 1385b9c1b51eSKate Stone " old_keys = global_dict.keys()"); // Save list of keys in global dict 1386b9c1b51eSKate Stone auto_generated_function.AppendString( 1387b9c1b51eSKate Stone " global_dict.update (internal_dict)"); // Add the session dictionary 1388b9c1b51eSKate Stone // to the 13892c1f46dcSZachary Turner // global dictionary. 13902c1f46dcSZachary Turner 13912c1f46dcSZachary Turner // Wrap everything up inside the function, increasing the indentation. 13922c1f46dcSZachary Turner 13932c1f46dcSZachary Turner auto_generated_function.AppendString(" if True:"); 1394b9c1b51eSKate Stone for (int i = 0; i < num_lines; ++i) { 13952c1f46dcSZachary Turner sstr.Clear(); 13962c1f46dcSZachary Turner sstr.Printf(" %s", input.GetStringAtIndex(i)); 13972c1f46dcSZachary Turner auto_generated_function.AppendString(sstr.GetData()); 13982c1f46dcSZachary Turner } 1399b9c1b51eSKate Stone auto_generated_function.AppendString( 1400b9c1b51eSKate Stone " for key in new_keys:"); // Iterate over all the keys from session 1401b9c1b51eSKate Stone // dict 1402b9c1b51eSKate Stone auto_generated_function.AppendString( 1403b9c1b51eSKate Stone " internal_dict[key] = global_dict[key]"); // Update session dict 1404b9c1b51eSKate Stone // values 1405b9c1b51eSKate Stone auto_generated_function.AppendString( 1406b9c1b51eSKate Stone " if key not in old_keys:"); // If key was not originally in 1407b9c1b51eSKate Stone // global dict 1408b9c1b51eSKate Stone auto_generated_function.AppendString( 1409b9c1b51eSKate Stone " del global_dict[key]"); // ...then remove key/value from 1410b9c1b51eSKate Stone // global dict 14112c1f46dcSZachary Turner 14122c1f46dcSZachary Turner // Verify that the results are valid Python. 14132c1f46dcSZachary Turner 14142c1f46dcSZachary Turner error = ExportFunctionDefinitionToInterpreter(auto_generated_function); 14152c1f46dcSZachary Turner 14162c1f46dcSZachary Turner return error; 14172c1f46dcSZachary Turner } 14182c1f46dcSZachary Turner 141963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction( 1420b9c1b51eSKate Stone StringList &user_input, std::string &output, const void *name_token) { 14212c1f46dcSZachary Turner static uint32_t num_created_functions = 0; 14222c1f46dcSZachary Turner user_input.RemoveBlankLines(); 14232c1f46dcSZachary Turner StreamString sstr; 14242c1f46dcSZachary Turner 14252c1f46dcSZachary Turner // Check to see if we have any data; if not, just return. 14262c1f46dcSZachary Turner if (user_input.GetSize() == 0) 14272c1f46dcSZachary Turner return false; 14282c1f46dcSZachary Turner 1429b9c1b51eSKate Stone // Take what the user wrote, wrap it all up inside one big auto-generated 143005097246SAdrian Prantl // Python function, passing in the ValueObject as parameter to the function. 14312c1f46dcSZachary Turner 1432b9c1b51eSKate Stone std::string auto_generated_function_name( 1433b9c1b51eSKate Stone GenerateUniqueName("lldb_autogen_python_type_print_func", 1434b9c1b51eSKate Stone num_created_functions, name_token)); 1435b9c1b51eSKate Stone sstr.Printf("def %s (valobj, internal_dict):", 1436b9c1b51eSKate Stone auto_generated_function_name.c_str()); 14372c1f46dcSZachary Turner 14382c1f46dcSZachary Turner if (!GenerateFunction(sstr.GetData(), user_input).Success()) 14392c1f46dcSZachary Turner return false; 14402c1f46dcSZachary Turner 14412c1f46dcSZachary Turner // Store the name of the auto-generated function to be called. 14422c1f46dcSZachary Turner output.assign(auto_generated_function_name); 14432c1f46dcSZachary Turner return true; 14442c1f46dcSZachary Turner } 14452c1f46dcSZachary Turner 144663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction( 1447b9c1b51eSKate Stone StringList &user_input, std::string &output) { 14482c1f46dcSZachary Turner static uint32_t num_created_functions = 0; 14492c1f46dcSZachary Turner user_input.RemoveBlankLines(); 14502c1f46dcSZachary Turner StreamString sstr; 14512c1f46dcSZachary Turner 14522c1f46dcSZachary Turner // Check to see if we have any data; if not, just return. 14532c1f46dcSZachary Turner if (user_input.GetSize() == 0) 14542c1f46dcSZachary Turner return false; 14552c1f46dcSZachary Turner 1456b9c1b51eSKate Stone std::string auto_generated_function_name(GenerateUniqueName( 1457b9c1b51eSKate Stone "lldb_autogen_python_cmd_alias_func", num_created_functions)); 14582c1f46dcSZachary Turner 1459b9c1b51eSKate Stone sstr.Printf("def %s (debugger, args, result, internal_dict):", 1460b9c1b51eSKate Stone auto_generated_function_name.c_str()); 14612c1f46dcSZachary Turner 14622c1f46dcSZachary Turner if (!GenerateFunction(sstr.GetData(), user_input).Success()) 14632c1f46dcSZachary Turner return false; 14642c1f46dcSZachary Turner 14652c1f46dcSZachary Turner // Store the name of the auto-generated function to be called. 14662c1f46dcSZachary Turner output.assign(auto_generated_function_name); 14672c1f46dcSZachary Turner return true; 14682c1f46dcSZachary Turner } 14692c1f46dcSZachary Turner 147063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass( 147163dd5d25SJonas Devlieghere StringList &user_input, std::string &output, const void *name_token) { 14722c1f46dcSZachary Turner static uint32_t num_created_classes = 0; 14732c1f46dcSZachary Turner user_input.RemoveBlankLines(); 14742c1f46dcSZachary Turner int num_lines = user_input.GetSize(); 14752c1f46dcSZachary Turner StreamString sstr; 14762c1f46dcSZachary Turner 14772c1f46dcSZachary Turner // Check to see if we have any data; if not, just return. 14782c1f46dcSZachary Turner if (user_input.GetSize() == 0) 14792c1f46dcSZachary Turner return false; 14802c1f46dcSZachary Turner 14812c1f46dcSZachary Turner // Wrap all user input into a Python class 14822c1f46dcSZachary Turner 1483b9c1b51eSKate Stone std::string auto_generated_class_name(GenerateUniqueName( 1484b9c1b51eSKate Stone "lldb_autogen_python_type_synth_class", num_created_classes, name_token)); 14852c1f46dcSZachary Turner 14862c1f46dcSZachary Turner StringList auto_generated_class; 14872c1f46dcSZachary Turner 14882c1f46dcSZachary Turner // Create the function name & definition string. 14892c1f46dcSZachary Turner 14902c1f46dcSZachary Turner sstr.Printf("class %s:", auto_generated_class_name.c_str()); 1491c156427dSZachary Turner auto_generated_class.AppendString(sstr.GetString()); 14922c1f46dcSZachary Turner 149305097246SAdrian Prantl // Wrap everything up inside the class, increasing the indentation. we don't 149405097246SAdrian Prantl // need to play any fancy indentation tricks here because there is no 14952c1f46dcSZachary Turner // surrounding code whose indentation we need to honor 1496b9c1b51eSKate Stone for (int i = 0; i < num_lines; ++i) { 14972c1f46dcSZachary Turner sstr.Clear(); 14982c1f46dcSZachary Turner sstr.Printf(" %s", user_input.GetStringAtIndex(i)); 1499c156427dSZachary Turner auto_generated_class.AppendString(sstr.GetString()); 15002c1f46dcSZachary Turner } 15012c1f46dcSZachary Turner 150205097246SAdrian Prantl // Verify that the results are valid Python. (even though the method is 150305097246SAdrian Prantl // ExportFunctionDefinitionToInterpreter, a class will actually be exported) 15042c1f46dcSZachary Turner // (TODO: rename that method to ExportDefinitionToInterpreter) 15052c1f46dcSZachary Turner if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success()) 15062c1f46dcSZachary Turner return false; 15072c1f46dcSZachary Turner 15082c1f46dcSZachary Turner // Store the name of the auto-generated class 15092c1f46dcSZachary Turner 15102c1f46dcSZachary Turner output.assign(auto_generated_class_name); 15112c1f46dcSZachary Turner return true; 15122c1f46dcSZachary Turner } 15132c1f46dcSZachary Turner 151463dd5d25SJonas Devlieghere StructuredData::GenericSP 151563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) { 151641ae8e74SKuba Mracek if (class_name == nullptr || class_name[0] == '\0') 151741ae8e74SKuba Mracek return StructuredData::GenericSP(); 151841ae8e74SKuba Mracek 151941ae8e74SKuba Mracek void *ret_val; 152041ae8e74SKuba Mracek 152141ae8e74SKuba Mracek { 152241ae8e74SKuba Mracek Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, 152341ae8e74SKuba Mracek Locker::FreeLock); 152405495c5dSJonas Devlieghere ret_val = LLDBSWIGPython_CreateFrameRecognizer(class_name, 152505495c5dSJonas Devlieghere m_dictionary_name.c_str()); 152641ae8e74SKuba Mracek } 152741ae8e74SKuba Mracek 152841ae8e74SKuba Mracek return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 152941ae8e74SKuba Mracek } 153041ae8e74SKuba Mracek 153163dd5d25SJonas Devlieghere lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments( 153241ae8e74SKuba Mracek const StructuredData::ObjectSP &os_plugin_object_sp, 153341ae8e74SKuba Mracek lldb::StackFrameSP frame_sp) { 153441ae8e74SKuba Mracek Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 153541ae8e74SKuba Mracek 153663dd5d25SJonas Devlieghere if (!os_plugin_object_sp) 153763dd5d25SJonas Devlieghere return ValueObjectListSP(); 153841ae8e74SKuba Mracek 153941ae8e74SKuba Mracek StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 154063dd5d25SJonas Devlieghere if (!generic) 154163dd5d25SJonas Devlieghere return nullptr; 154241ae8e74SKuba Mracek 154341ae8e74SKuba Mracek PythonObject implementor(PyRefType::Borrowed, 154441ae8e74SKuba Mracek (PyObject *)generic->GetValue()); 154541ae8e74SKuba Mracek 154663dd5d25SJonas Devlieghere if (!implementor.IsAllocated()) 154763dd5d25SJonas Devlieghere return ValueObjectListSP(); 154841ae8e74SKuba Mracek 154905495c5dSJonas Devlieghere PythonObject py_return(PyRefType::Owned, 155005495c5dSJonas Devlieghere (PyObject *)LLDBSwigPython_GetRecognizedArguments( 155105495c5dSJonas Devlieghere implementor.get(), frame_sp)); 155241ae8e74SKuba Mracek 155341ae8e74SKuba Mracek // if it fails, print the error but otherwise go on 155441ae8e74SKuba Mracek if (PyErr_Occurred()) { 155541ae8e74SKuba Mracek PyErr_Print(); 155641ae8e74SKuba Mracek PyErr_Clear(); 155741ae8e74SKuba Mracek } 155841ae8e74SKuba Mracek if (py_return.get()) { 155941ae8e74SKuba Mracek PythonList result_list(PyRefType::Borrowed, py_return.get()); 156041ae8e74SKuba Mracek ValueObjectListSP result = ValueObjectListSP(new ValueObjectList()); 15618f81aed1SDavid Bolvansky for (size_t i = 0; i < result_list.GetSize(); i++) { 156241ae8e74SKuba Mracek PyObject *item = result_list.GetItemAtIndex(i).get(); 156341ae8e74SKuba Mracek lldb::SBValue *sb_value_ptr = 156405495c5dSJonas Devlieghere (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item); 156505495c5dSJonas Devlieghere auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); 156663dd5d25SJonas Devlieghere if (valobj_sp) 156763dd5d25SJonas Devlieghere result->Append(valobj_sp); 156841ae8e74SKuba Mracek } 156941ae8e74SKuba Mracek return result; 157041ae8e74SKuba Mracek } 157141ae8e74SKuba Mracek return ValueObjectListSP(); 157241ae8e74SKuba Mracek } 157341ae8e74SKuba Mracek 157463dd5d25SJonas Devlieghere StructuredData::GenericSP 157563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject( 1576b9c1b51eSKate Stone const char *class_name, lldb::ProcessSP process_sp) { 15772c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0') 15782c1f46dcSZachary Turner return StructuredData::GenericSP(); 15792c1f46dcSZachary Turner 15802c1f46dcSZachary Turner if (!process_sp) 15812c1f46dcSZachary Turner return StructuredData::GenericSP(); 15822c1f46dcSZachary Turner 15832c1f46dcSZachary Turner void *ret_val; 15842c1f46dcSZachary Turner 15852c1f46dcSZachary Turner { 1586b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, 15872c1f46dcSZachary Turner Locker::FreeLock); 158805495c5dSJonas Devlieghere ret_val = LLDBSWIGPythonCreateOSPlugin( 158905495c5dSJonas Devlieghere class_name, m_dictionary_name.c_str(), process_sp); 15902c1f46dcSZachary Turner } 15912c1f46dcSZachary Turner 15922c1f46dcSZachary Turner return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 15932c1f46dcSZachary Turner } 15942c1f46dcSZachary Turner 159563dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo( 1596b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp) { 1597b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 15982c1f46dcSZachary Turner 15992c1f46dcSZachary Turner static char callee_name[] = "get_register_info"; 16002c1f46dcSZachary Turner 16012c1f46dcSZachary Turner if (!os_plugin_object_sp) 16022c1f46dcSZachary Turner return StructuredData::DictionarySP(); 16032c1f46dcSZachary Turner 16042c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 16052c1f46dcSZachary Turner if (!generic) 16062c1f46dcSZachary Turner return nullptr; 16072c1f46dcSZachary Turner 1608b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 1609b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 16102c1f46dcSZachary Turner 1611f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 16122c1f46dcSZachary Turner return StructuredData::DictionarySP(); 16132c1f46dcSZachary Turner 1614b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 1615b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 16162c1f46dcSZachary Turner 16172c1f46dcSZachary Turner if (PyErr_Occurred()) 16182c1f46dcSZachary Turner PyErr_Clear(); 16192c1f46dcSZachary Turner 1620f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 16212c1f46dcSZachary Turner return StructuredData::DictionarySP(); 16222c1f46dcSZachary Turner 1623b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 16242c1f46dcSZachary Turner if (PyErr_Occurred()) 16252c1f46dcSZachary Turner PyErr_Clear(); 16262c1f46dcSZachary Turner 16272c1f46dcSZachary Turner return StructuredData::DictionarySP(); 16282c1f46dcSZachary Turner } 16292c1f46dcSZachary Turner 16302c1f46dcSZachary Turner if (PyErr_Occurred()) 16312c1f46dcSZachary Turner PyErr_Clear(); 16322c1f46dcSZachary Turner 16332c1f46dcSZachary Turner // right now we know this function exists and is callable.. 1634b9c1b51eSKate Stone PythonObject py_return( 1635b9c1b51eSKate Stone PyRefType::Owned, 1636b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 16372c1f46dcSZachary Turner 16382c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 1639b9c1b51eSKate Stone if (PyErr_Occurred()) { 16402c1f46dcSZachary Turner PyErr_Print(); 16412c1f46dcSZachary Turner PyErr_Clear(); 16422c1f46dcSZachary Turner } 1643b9c1b51eSKate Stone if (py_return.get()) { 1644f8b22f8fSZachary Turner PythonDictionary result_dict(PyRefType::Borrowed, py_return.get()); 16452c1f46dcSZachary Turner return result_dict.CreateStructuredDictionary(); 16462c1f46dcSZachary Turner } 164758b794aeSGreg Clayton return StructuredData::DictionarySP(); 164858b794aeSGreg Clayton } 16492c1f46dcSZachary Turner 165063dd5d25SJonas Devlieghere StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo( 1651b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp) { 1652b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 16532c1f46dcSZachary Turner 16542c1f46dcSZachary Turner static char callee_name[] = "get_thread_info"; 16552c1f46dcSZachary Turner 16562c1f46dcSZachary Turner if (!os_plugin_object_sp) 16572c1f46dcSZachary Turner return StructuredData::ArraySP(); 16582c1f46dcSZachary Turner 16592c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 16602c1f46dcSZachary Turner if (!generic) 16612c1f46dcSZachary Turner return nullptr; 16622c1f46dcSZachary Turner 1663b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 1664b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 1665f8b22f8fSZachary Turner 1666f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 16672c1f46dcSZachary Turner return StructuredData::ArraySP(); 16682c1f46dcSZachary Turner 1669b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 1670b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 16712c1f46dcSZachary Turner 16722c1f46dcSZachary Turner if (PyErr_Occurred()) 16732c1f46dcSZachary Turner PyErr_Clear(); 16742c1f46dcSZachary Turner 1675f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 16762c1f46dcSZachary Turner return StructuredData::ArraySP(); 16772c1f46dcSZachary Turner 1678b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 16792c1f46dcSZachary Turner if (PyErr_Occurred()) 16802c1f46dcSZachary Turner PyErr_Clear(); 16812c1f46dcSZachary Turner 16822c1f46dcSZachary Turner return StructuredData::ArraySP(); 16832c1f46dcSZachary Turner } 16842c1f46dcSZachary Turner 16852c1f46dcSZachary Turner if (PyErr_Occurred()) 16862c1f46dcSZachary Turner PyErr_Clear(); 16872c1f46dcSZachary Turner 16882c1f46dcSZachary Turner // right now we know this function exists and is callable.. 1689b9c1b51eSKate Stone PythonObject py_return( 1690b9c1b51eSKate Stone PyRefType::Owned, 1691b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 16922c1f46dcSZachary Turner 16932c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 1694b9c1b51eSKate Stone if (PyErr_Occurred()) { 16952c1f46dcSZachary Turner PyErr_Print(); 16962c1f46dcSZachary Turner PyErr_Clear(); 16972c1f46dcSZachary Turner } 16982c1f46dcSZachary Turner 1699b9c1b51eSKate Stone if (py_return.get()) { 1700f8b22f8fSZachary Turner PythonList result_list(PyRefType::Borrowed, py_return.get()); 1701f8b22f8fSZachary Turner return result_list.CreateStructuredArray(); 17022c1f46dcSZachary Turner } 170358b794aeSGreg Clayton return StructuredData::ArraySP(); 170458b794aeSGreg Clayton } 17052c1f46dcSZachary Turner 17062c1f46dcSZachary Turner // GetPythonValueFormatString provides a system independent type safe way to 17072c1f46dcSZachary Turner // convert a variable's type into a python value format. Python value formats 170805097246SAdrian Prantl // are defined in terms of builtin C types and could change from system to as 170905097246SAdrian Prantl // the underlying typedef for uint* types, size_t, off_t and other values 17102c1f46dcSZachary Turner // change. 17112c1f46dcSZachary Turner 1712684c2c93SPavel Labath template <typename T> const char *GetPythonValueFormatString(T t); 17132c1f46dcSZachary Turner template <> const char *GetPythonValueFormatString(char *) { return "s"; } 17142c1f46dcSZachary Turner template <> const char *GetPythonValueFormatString(char) { return "b"; } 1715b9c1b51eSKate Stone template <> const char *GetPythonValueFormatString(unsigned char) { 1716b9c1b51eSKate Stone return "B"; 1717b9c1b51eSKate Stone } 17182c1f46dcSZachary Turner template <> const char *GetPythonValueFormatString(short) { return "h"; } 1719b9c1b51eSKate Stone template <> const char *GetPythonValueFormatString(unsigned short) { 1720b9c1b51eSKate Stone return "H"; 1721b9c1b51eSKate Stone } 17222c1f46dcSZachary Turner template <> const char *GetPythonValueFormatString(int) { return "i"; } 17232c1f46dcSZachary Turner template <> const char *GetPythonValueFormatString(unsigned int) { return "I"; } 17242c1f46dcSZachary Turner template <> const char *GetPythonValueFormatString(long) { return "l"; } 1725b9c1b51eSKate Stone template <> const char *GetPythonValueFormatString(unsigned long) { 1726b9c1b51eSKate Stone return "k"; 1727b9c1b51eSKate Stone } 17282c1f46dcSZachary Turner template <> const char *GetPythonValueFormatString(long long) { return "L"; } 1729b9c1b51eSKate Stone template <> const char *GetPythonValueFormatString(unsigned long long) { 1730b9c1b51eSKate Stone return "K"; 1731b9c1b51eSKate Stone } 17322c1f46dcSZachary Turner template <> const char *GetPythonValueFormatString(float t) { return "f"; } 17332c1f46dcSZachary Turner template <> const char *GetPythonValueFormatString(double t) { return "d"; } 17342c1f46dcSZachary Turner 173563dd5d25SJonas Devlieghere StructuredData::StringSP 173663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData( 1737b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) { 1738b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 17392c1f46dcSZachary Turner 17402c1f46dcSZachary Turner static char callee_name[] = "get_register_data"; 1741b9c1b51eSKate Stone static char *param_format = 1742b9c1b51eSKate Stone const_cast<char *>(GetPythonValueFormatString(tid)); 17432c1f46dcSZachary Turner 17442c1f46dcSZachary Turner if (!os_plugin_object_sp) 17452c1f46dcSZachary Turner return StructuredData::StringSP(); 17462c1f46dcSZachary Turner 17472c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 17482c1f46dcSZachary Turner if (!generic) 17492c1f46dcSZachary Turner return nullptr; 1750b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 1751b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 17522c1f46dcSZachary Turner 1753f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 17542c1f46dcSZachary Turner return StructuredData::StringSP(); 17552c1f46dcSZachary Turner 1756b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 1757b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 17582c1f46dcSZachary Turner 17592c1f46dcSZachary Turner if (PyErr_Occurred()) 17602c1f46dcSZachary Turner PyErr_Clear(); 17612c1f46dcSZachary Turner 1762f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 17632c1f46dcSZachary Turner return StructuredData::StringSP(); 17642c1f46dcSZachary Turner 1765b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 17662c1f46dcSZachary Turner if (PyErr_Occurred()) 17672c1f46dcSZachary Turner PyErr_Clear(); 17682c1f46dcSZachary Turner return StructuredData::StringSP(); 17692c1f46dcSZachary Turner } 17702c1f46dcSZachary Turner 17712c1f46dcSZachary Turner if (PyErr_Occurred()) 17722c1f46dcSZachary Turner PyErr_Clear(); 17732c1f46dcSZachary Turner 17742c1f46dcSZachary Turner // right now we know this function exists and is callable.. 1775b9c1b51eSKate Stone PythonObject py_return( 1776b9c1b51eSKate Stone PyRefType::Owned, 1777b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, param_format, tid)); 17782c1f46dcSZachary Turner 17792c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 1780b9c1b51eSKate Stone if (PyErr_Occurred()) { 17812c1f46dcSZachary Turner PyErr_Print(); 17822c1f46dcSZachary Turner PyErr_Clear(); 17832c1f46dcSZachary Turner } 1784f8b22f8fSZachary Turner 1785b9c1b51eSKate Stone if (py_return.get()) { 17867a76845cSZachary Turner PythonBytes result(PyRefType::Borrowed, py_return.get()); 17877a76845cSZachary Turner return result.CreateStructuredString(); 17882c1f46dcSZachary Turner } 178958b794aeSGreg Clayton return StructuredData::StringSP(); 179058b794aeSGreg Clayton } 17912c1f46dcSZachary Turner 179263dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread( 1793b9c1b51eSKate Stone StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid, 1794b9c1b51eSKate Stone lldb::addr_t context) { 1795b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 17962c1f46dcSZachary Turner 17972c1f46dcSZachary Turner static char callee_name[] = "create_thread"; 17982c1f46dcSZachary Turner std::string param_format; 17992c1f46dcSZachary Turner param_format += GetPythonValueFormatString(tid); 18002c1f46dcSZachary Turner param_format += GetPythonValueFormatString(context); 18012c1f46dcSZachary Turner 18022c1f46dcSZachary Turner if (!os_plugin_object_sp) 18032c1f46dcSZachary Turner return StructuredData::DictionarySP(); 18042c1f46dcSZachary Turner 18052c1f46dcSZachary Turner StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 18062c1f46dcSZachary Turner if (!generic) 18072c1f46dcSZachary Turner return nullptr; 18082c1f46dcSZachary Turner 1809b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 1810b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 1811f8b22f8fSZachary Turner 1812f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 18132c1f46dcSZachary Turner return StructuredData::DictionarySP(); 18142c1f46dcSZachary Turner 1815b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 1816b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 18172c1f46dcSZachary Turner 18182c1f46dcSZachary Turner if (PyErr_Occurred()) 18192c1f46dcSZachary Turner PyErr_Clear(); 18202c1f46dcSZachary Turner 1821f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 18222c1f46dcSZachary Turner return StructuredData::DictionarySP(); 18232c1f46dcSZachary Turner 1824b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 18252c1f46dcSZachary Turner if (PyErr_Occurred()) 18262c1f46dcSZachary Turner PyErr_Clear(); 18272c1f46dcSZachary Turner return StructuredData::DictionarySP(); 18282c1f46dcSZachary Turner } 18292c1f46dcSZachary Turner 18302c1f46dcSZachary Turner if (PyErr_Occurred()) 18312c1f46dcSZachary Turner PyErr_Clear(); 18322c1f46dcSZachary Turner 18332c1f46dcSZachary Turner // right now we know this function exists and is callable.. 1834b9c1b51eSKate Stone PythonObject py_return(PyRefType::Owned, 1835b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, 1836b9c1b51eSKate Stone ¶m_format[0], tid, context)); 18372c1f46dcSZachary Turner 18382c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 1839b9c1b51eSKate Stone if (PyErr_Occurred()) { 18402c1f46dcSZachary Turner PyErr_Print(); 18412c1f46dcSZachary Turner PyErr_Clear(); 18422c1f46dcSZachary Turner } 18432c1f46dcSZachary Turner 1844b9c1b51eSKate Stone if (py_return.get()) { 1845f8b22f8fSZachary Turner PythonDictionary result_dict(PyRefType::Borrowed, py_return.get()); 18462c1f46dcSZachary Turner return result_dict.CreateStructuredDictionary(); 18472c1f46dcSZachary Turner } 184858b794aeSGreg Clayton return StructuredData::DictionarySP(); 184958b794aeSGreg Clayton } 18502c1f46dcSZachary Turner 185163dd5d25SJonas Devlieghere StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan( 185227a14f19SJim Ingham const char *class_name, StructuredDataImpl *args_data, 1853a69bbe02SLawrence D'Anna std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) { 18542c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0') 18552c1f46dcSZachary Turner return StructuredData::ObjectSP(); 18562c1f46dcSZachary Turner 18572c1f46dcSZachary Turner if (!thread_plan_sp.get()) 185893c98346SJim Ingham return {}; 18592c1f46dcSZachary Turner 18602c1f46dcSZachary Turner Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger(); 186163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 1862d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 18632c1f46dcSZachary Turner 1864d055e3a0SPedro Tammela if (!python_interpreter) 186593c98346SJim Ingham return {}; 18662c1f46dcSZachary Turner 18672c1f46dcSZachary Turner void *ret_val; 18682c1f46dcSZachary Turner 18692c1f46dcSZachary Turner { 1870b9c1b51eSKate Stone Locker py_lock(this, 1871b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 187205495c5dSJonas Devlieghere ret_val = LLDBSwigPythonCreateScriptedThreadPlan( 1873b9c1b51eSKate Stone class_name, python_interpreter->m_dictionary_name.c_str(), 187427a14f19SJim Ingham args_data, error_str, thread_plan_sp); 187593c98346SJim Ingham if (!ret_val) 187693c98346SJim Ingham return {}; 18772c1f46dcSZachary Turner } 18782c1f46dcSZachary Turner 18792c1f46dcSZachary Turner return StructuredData::ObjectSP(new StructuredPythonObject(ret_val)); 18802c1f46dcSZachary Turner } 18812c1f46dcSZachary Turner 188263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop( 1883b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) { 18842c1f46dcSZachary Turner bool explains_stop = true; 18852c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr; 18862c1f46dcSZachary Turner if (implementor_sp) 18872c1f46dcSZachary Turner generic = implementor_sp->GetAsGeneric(); 1888b9c1b51eSKate Stone if (generic) { 1889b9c1b51eSKate Stone Locker py_lock(this, 1890b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 189105495c5dSJonas Devlieghere explains_stop = LLDBSWIGPythonCallThreadPlan( 1892b9c1b51eSKate Stone generic->GetValue(), "explains_stop", event, script_error); 18932c1f46dcSZachary Turner if (script_error) 18942c1f46dcSZachary Turner return true; 18952c1f46dcSZachary Turner } 18962c1f46dcSZachary Turner return explains_stop; 18972c1f46dcSZachary Turner } 18982c1f46dcSZachary Turner 189963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop( 1900b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) { 19012c1f46dcSZachary Turner bool should_stop = true; 19022c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr; 19032c1f46dcSZachary Turner if (implementor_sp) 19042c1f46dcSZachary Turner generic = implementor_sp->GetAsGeneric(); 1905b9c1b51eSKate Stone if (generic) { 1906b9c1b51eSKate Stone Locker py_lock(this, 1907b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 190805495c5dSJonas Devlieghere should_stop = LLDBSWIGPythonCallThreadPlan( 190905495c5dSJonas Devlieghere generic->GetValue(), "should_stop", event, script_error); 19102c1f46dcSZachary Turner if (script_error) 19112c1f46dcSZachary Turner return true; 19122c1f46dcSZachary Turner } 19132c1f46dcSZachary Turner return should_stop; 19142c1f46dcSZachary Turner } 19152c1f46dcSZachary Turner 191663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale( 1917b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, bool &script_error) { 1918c915a7d2SJim Ingham bool is_stale = true; 1919c915a7d2SJim Ingham StructuredData::Generic *generic = nullptr; 1920c915a7d2SJim Ingham if (implementor_sp) 1921c915a7d2SJim Ingham generic = implementor_sp->GetAsGeneric(); 1922b9c1b51eSKate Stone if (generic) { 1923b9c1b51eSKate Stone Locker py_lock(this, 1924b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 192505495c5dSJonas Devlieghere is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale", 192605495c5dSJonas Devlieghere nullptr, script_error); 1927c915a7d2SJim Ingham if (script_error) 1928c915a7d2SJim Ingham return true; 1929c915a7d2SJim Ingham } 1930c915a7d2SJim Ingham return is_stale; 1931c915a7d2SJim Ingham } 1932c915a7d2SJim Ingham 193363dd5d25SJonas Devlieghere lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState( 1934b9c1b51eSKate Stone StructuredData::ObjectSP implementor_sp, bool &script_error) { 19352c1f46dcSZachary Turner bool should_step = false; 19362c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr; 19372c1f46dcSZachary Turner if (implementor_sp) 19382c1f46dcSZachary Turner generic = implementor_sp->GetAsGeneric(); 1939b9c1b51eSKate Stone if (generic) { 1940b9c1b51eSKate Stone Locker py_lock(this, 1941b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 194205495c5dSJonas Devlieghere should_step = LLDBSWIGPythonCallThreadPlan( 1943248a1305SKonrad Kleine generic->GetValue(), "should_step", nullptr, script_error); 19442c1f46dcSZachary Turner if (script_error) 19452c1f46dcSZachary Turner should_step = true; 19462c1f46dcSZachary Turner } 19472c1f46dcSZachary Turner if (should_step) 19482c1f46dcSZachary Turner return lldb::eStateStepping; 19492c1f46dcSZachary Turner return lldb::eStateRunning; 19502c1f46dcSZachary Turner } 19512c1f46dcSZachary Turner 19523815e702SJim Ingham StructuredData::GenericSP 195363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver( 195463dd5d25SJonas Devlieghere const char *class_name, StructuredDataImpl *args_data, 19553815e702SJim Ingham lldb::BreakpointSP &bkpt_sp) { 19563815e702SJim Ingham 19573815e702SJim Ingham if (class_name == nullptr || class_name[0] == '\0') 19583815e702SJim Ingham return StructuredData::GenericSP(); 19593815e702SJim Ingham 19603815e702SJim Ingham if (!bkpt_sp.get()) 19613815e702SJim Ingham return StructuredData::GenericSP(); 19623815e702SJim Ingham 19633815e702SJim Ingham Debugger &debugger = bkpt_sp->GetTarget().GetDebugger(); 196463dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 1965d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 19663815e702SJim Ingham 1967d055e3a0SPedro Tammela if (!python_interpreter) 19683815e702SJim Ingham return StructuredData::GenericSP(); 19693815e702SJim Ingham 19703815e702SJim Ingham void *ret_val; 19713815e702SJim Ingham 19723815e702SJim Ingham { 19733815e702SJim Ingham Locker py_lock(this, 19743815e702SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 19753815e702SJim Ingham 197605495c5dSJonas Devlieghere ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver( 197705495c5dSJonas Devlieghere class_name, python_interpreter->m_dictionary_name.c_str(), args_data, 197805495c5dSJonas Devlieghere bkpt_sp); 19793815e702SJim Ingham } 19803815e702SJim Ingham 19813815e702SJim Ingham return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 19823815e702SJim Ingham } 19833815e702SJim Ingham 198463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback( 198563dd5d25SJonas Devlieghere StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) { 19863815e702SJim Ingham bool should_continue = false; 19873815e702SJim Ingham 19883815e702SJim Ingham if (implementor_sp) { 19893815e702SJim Ingham Locker py_lock(this, 19903815e702SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 199105495c5dSJonas Devlieghere should_continue = LLDBSwigPythonCallBreakpointResolver( 199205495c5dSJonas Devlieghere implementor_sp->GetValue(), "__callback__", sym_ctx); 19933815e702SJim Ingham if (PyErr_Occurred()) { 19943815e702SJim Ingham PyErr_Print(); 19953815e702SJim Ingham PyErr_Clear(); 19963815e702SJim Ingham } 19973815e702SJim Ingham } 19983815e702SJim Ingham return should_continue; 19993815e702SJim Ingham } 20003815e702SJim Ingham 20013815e702SJim Ingham lldb::SearchDepth 200263dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth( 20033815e702SJim Ingham StructuredData::GenericSP implementor_sp) { 20043815e702SJim Ingham int depth_as_int = lldb::eSearchDepthModule; 20053815e702SJim Ingham if (implementor_sp) { 20063815e702SJim Ingham Locker py_lock(this, 20073815e702SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 200805495c5dSJonas Devlieghere depth_as_int = LLDBSwigPythonCallBreakpointResolver( 200905495c5dSJonas Devlieghere implementor_sp->GetValue(), "__get_depth__", nullptr); 20103815e702SJim Ingham if (PyErr_Occurred()) { 20113815e702SJim Ingham PyErr_Print(); 20123815e702SJim Ingham PyErr_Clear(); 20133815e702SJim Ingham } 20143815e702SJim Ingham } 20153815e702SJim Ingham if (depth_as_int == lldb::eSearchDepthInvalid) 20163815e702SJim Ingham return lldb::eSearchDepthModule; 20173815e702SJim Ingham 20183815e702SJim Ingham if (depth_as_int <= lldb::kLastSearchDepthKind) 20193815e702SJim Ingham return (lldb::SearchDepth)depth_as_int; 20203815e702SJim Ingham return lldb::eSearchDepthModule; 20213815e702SJim Ingham } 20223815e702SJim Ingham 20231b1d9815SJim Ingham StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook( 20241b1d9815SJim Ingham TargetSP target_sp, const char *class_name, StructuredDataImpl *args_data, 20251b1d9815SJim Ingham Status &error) { 20261b1d9815SJim Ingham 20271b1d9815SJim Ingham if (!target_sp) { 20281b1d9815SJim Ingham error.SetErrorString("No target for scripted stop-hook."); 20291b1d9815SJim Ingham return StructuredData::GenericSP(); 20301b1d9815SJim Ingham } 20311b1d9815SJim Ingham 20321b1d9815SJim Ingham if (class_name == nullptr || class_name[0] == '\0') { 20331b1d9815SJim Ingham error.SetErrorString("No class name for scripted stop-hook."); 20341b1d9815SJim Ingham return StructuredData::GenericSP(); 20351b1d9815SJim Ingham } 20361b1d9815SJim Ingham 20371b1d9815SJim Ingham ScriptInterpreterPythonImpl *python_interpreter = 2038d055e3a0SPedro Tammela GetPythonInterpreter(m_debugger); 20391b1d9815SJim Ingham 2040d055e3a0SPedro Tammela if (!python_interpreter) { 20411b1d9815SJim Ingham error.SetErrorString("No script interpreter for scripted stop-hook."); 20421b1d9815SJim Ingham return StructuredData::GenericSP(); 20431b1d9815SJim Ingham } 20441b1d9815SJim Ingham 20451b1d9815SJim Ingham void *ret_val; 20461b1d9815SJim Ingham 20471b1d9815SJim Ingham { 20481b1d9815SJim Ingham Locker py_lock(this, 20491b1d9815SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 20501b1d9815SJim Ingham 20511b1d9815SJim Ingham ret_val = LLDBSwigPythonCreateScriptedStopHook( 20521b1d9815SJim Ingham target_sp, class_name, python_interpreter->m_dictionary_name.c_str(), 20531b1d9815SJim Ingham args_data, error); 20541b1d9815SJim Ingham } 20551b1d9815SJim Ingham 20561b1d9815SJim Ingham return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 20571b1d9815SJim Ingham } 20581b1d9815SJim Ingham 20591b1d9815SJim Ingham bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop( 20601b1d9815SJim Ingham StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx, 20611b1d9815SJim Ingham lldb::StreamSP stream_sp) { 20621b1d9815SJim Ingham assert(implementor_sp && 20631b1d9815SJim Ingham "can't call a stop hook with an invalid implementor"); 20641b1d9815SJim Ingham assert(stream_sp && "can't call a stop hook with an invalid stream"); 20651b1d9815SJim Ingham 20661b1d9815SJim Ingham Locker py_lock(this, 20671b1d9815SJim Ingham Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 20681b1d9815SJim Ingham 20691b1d9815SJim Ingham lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx)); 20701b1d9815SJim Ingham 20711b1d9815SJim Ingham bool ret_val = LLDBSwigPythonStopHookCallHandleStop( 20721b1d9815SJim Ingham implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp); 20731b1d9815SJim Ingham return ret_val; 20741b1d9815SJim Ingham } 20751b1d9815SJim Ingham 20762c1f46dcSZachary Turner StructuredData::ObjectSP 207763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec, 207897206d57SZachary Turner lldb_private::Status &error) { 2079dbd7fabaSJonas Devlieghere if (!FileSystem::Instance().Exists(file_spec)) { 20802c1f46dcSZachary Turner error.SetErrorString("no such file"); 20812c1f46dcSZachary Turner return StructuredData::ObjectSP(); 20822c1f46dcSZachary Turner } 20832c1f46dcSZachary Turner 20842c1f46dcSZachary Turner StructuredData::ObjectSP module_sp; 20852c1f46dcSZachary Turner 208615625112SJonas Devlieghere if (LoadScriptingModule(file_spec.GetPath().c_str(), true, error, &module_sp)) 20872c1f46dcSZachary Turner return module_sp; 20882c1f46dcSZachary Turner 20892c1f46dcSZachary Turner return StructuredData::ObjectSP(); 20902c1f46dcSZachary Turner } 20912c1f46dcSZachary Turner 209263dd5d25SJonas Devlieghere StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings( 2093b9c1b51eSKate Stone StructuredData::ObjectSP plugin_module_sp, Target *target, 209497206d57SZachary Turner const char *setting_name, lldb_private::Status &error) { 209505495c5dSJonas Devlieghere if (!plugin_module_sp || !target || !setting_name || !setting_name[0]) 20962c1f46dcSZachary Turner return StructuredData::DictionarySP(); 20972c1f46dcSZachary Turner StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric(); 20982c1f46dcSZachary Turner if (!generic) 20992c1f46dcSZachary Turner return StructuredData::DictionarySP(); 21002c1f46dcSZachary Turner 2101b9c1b51eSKate Stone Locker py_lock(this, 2102b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 21032c1f46dcSZachary Turner TargetSP target_sp(target->shared_from_this()); 21042c1f46dcSZachary Turner 210504edd189SLawrence D'Anna auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting( 210604edd189SLawrence D'Anna generic->GetValue(), setting_name, target_sp); 210704edd189SLawrence D'Anna 210804edd189SLawrence D'Anna if (!setting) 210904edd189SLawrence D'Anna return StructuredData::DictionarySP(); 211004edd189SLawrence D'Anna 211104edd189SLawrence D'Anna PythonDictionary py_dict = 211204edd189SLawrence D'Anna unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting))); 211304edd189SLawrence D'Anna 211404edd189SLawrence D'Anna if (!py_dict) 211504edd189SLawrence D'Anna return StructuredData::DictionarySP(); 211604edd189SLawrence D'Anna 21172c1f46dcSZachary Turner return py_dict.CreateStructuredDictionary(); 21182c1f46dcSZachary Turner } 21192c1f46dcSZachary Turner 21202c1f46dcSZachary Turner StructuredData::ObjectSP 212163dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider( 2122b9c1b51eSKate Stone const char *class_name, lldb::ValueObjectSP valobj) { 21232c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0') 21242c1f46dcSZachary Turner return StructuredData::ObjectSP(); 21252c1f46dcSZachary Turner 21262c1f46dcSZachary Turner if (!valobj.get()) 21272c1f46dcSZachary Turner return StructuredData::ObjectSP(); 21282c1f46dcSZachary Turner 21292c1f46dcSZachary Turner ExecutionContext exe_ctx(valobj->GetExecutionContextRef()); 21302c1f46dcSZachary Turner Target *target = exe_ctx.GetTargetPtr(); 21312c1f46dcSZachary Turner 21322c1f46dcSZachary Turner if (!target) 21332c1f46dcSZachary Turner return StructuredData::ObjectSP(); 21342c1f46dcSZachary Turner 21352c1f46dcSZachary Turner Debugger &debugger = target->GetDebugger(); 213663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 2137d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 21382c1f46dcSZachary Turner 2139d055e3a0SPedro Tammela if (!python_interpreter) 21402c1f46dcSZachary Turner return StructuredData::ObjectSP(); 21412c1f46dcSZachary Turner 21422c1f46dcSZachary Turner void *ret_val = nullptr; 21432c1f46dcSZachary Turner 21442c1f46dcSZachary Turner { 2145b9c1b51eSKate Stone Locker py_lock(this, 2146b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 214705495c5dSJonas Devlieghere ret_val = LLDBSwigPythonCreateSyntheticProvider( 2148b9c1b51eSKate Stone class_name, python_interpreter->m_dictionary_name.c_str(), valobj); 21492c1f46dcSZachary Turner } 21502c1f46dcSZachary Turner 21512c1f46dcSZachary Turner return StructuredData::ObjectSP(new StructuredPythonObject(ret_val)); 21522c1f46dcSZachary Turner } 21532c1f46dcSZachary Turner 21542c1f46dcSZachary Turner StructuredData::GenericSP 215563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) { 21568d1fb843SJonas Devlieghere DebuggerSP debugger_sp(m_debugger.shared_from_this()); 21572c1f46dcSZachary Turner 21582c1f46dcSZachary Turner if (class_name == nullptr || class_name[0] == '\0') 21592c1f46dcSZachary Turner return StructuredData::GenericSP(); 21602c1f46dcSZachary Turner 21612c1f46dcSZachary Turner if (!debugger_sp.get()) 21622c1f46dcSZachary Turner return StructuredData::GenericSP(); 21632c1f46dcSZachary Turner 21642c1f46dcSZachary Turner void *ret_val; 21652c1f46dcSZachary Turner 21662c1f46dcSZachary Turner { 2167b9c1b51eSKate Stone Locker py_lock(this, 2168b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 216905495c5dSJonas Devlieghere ret_val = LLDBSwigPythonCreateCommandObject( 217005495c5dSJonas Devlieghere class_name, m_dictionary_name.c_str(), debugger_sp); 21712c1f46dcSZachary Turner } 21722c1f46dcSZachary Turner 21732c1f46dcSZachary Turner return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 21742c1f46dcSZachary Turner } 21752c1f46dcSZachary Turner 217663dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction( 2177b9c1b51eSKate Stone const char *oneliner, std::string &output, const void *name_token) { 21782c1f46dcSZachary Turner StringList input; 21792c1f46dcSZachary Turner input.SplitIntoLines(oneliner, strlen(oneliner)); 21802c1f46dcSZachary Turner return GenerateTypeScriptFunction(input, output, name_token); 21812c1f46dcSZachary Turner } 21822c1f46dcSZachary Turner 218363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass( 218463dd5d25SJonas Devlieghere const char *oneliner, std::string &output, const void *name_token) { 21852c1f46dcSZachary Turner StringList input; 21862c1f46dcSZachary Turner input.SplitIntoLines(oneliner, strlen(oneliner)); 21872c1f46dcSZachary Turner return GenerateTypeSynthClass(input, output, name_token); 21882c1f46dcSZachary Turner } 21892c1f46dcSZachary Turner 219063dd5d25SJonas Devlieghere Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData( 2191738af7a6SJim Ingham StringList &user_input, std::string &output, 2192738af7a6SJim Ingham bool has_extra_args) { 21932c1f46dcSZachary Turner static uint32_t num_created_functions = 0; 21942c1f46dcSZachary Turner user_input.RemoveBlankLines(); 21952c1f46dcSZachary Turner StreamString sstr; 219697206d57SZachary Turner Status error; 2197b9c1b51eSKate Stone if (user_input.GetSize() == 0) { 21982c1f46dcSZachary Turner error.SetErrorString("No input data."); 21992c1f46dcSZachary Turner return error; 22002c1f46dcSZachary Turner } 22012c1f46dcSZachary Turner 2202b9c1b51eSKate Stone std::string auto_generated_function_name(GenerateUniqueName( 2203b9c1b51eSKate Stone "lldb_autogen_python_bp_callback_func_", num_created_functions)); 2204738af7a6SJim Ingham if (has_extra_args) 2205738af7a6SJim Ingham sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):", 2206738af7a6SJim Ingham auto_generated_function_name.c_str()); 2207738af7a6SJim Ingham else 2208b9c1b51eSKate Stone sstr.Printf("def %s (frame, bp_loc, internal_dict):", 2209b9c1b51eSKate Stone auto_generated_function_name.c_str()); 22102c1f46dcSZachary Turner 22112c1f46dcSZachary Turner error = GenerateFunction(sstr.GetData(), user_input); 22122c1f46dcSZachary Turner if (!error.Success()) 22132c1f46dcSZachary Turner return error; 22142c1f46dcSZachary Turner 22152c1f46dcSZachary Turner // Store the name of the auto-generated function to be called. 22162c1f46dcSZachary Turner output.assign(auto_generated_function_name); 22172c1f46dcSZachary Turner return error; 22182c1f46dcSZachary Turner } 22192c1f46dcSZachary Turner 222063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData( 2221b9c1b51eSKate Stone StringList &user_input, std::string &output) { 22222c1f46dcSZachary Turner static uint32_t num_created_functions = 0; 22232c1f46dcSZachary Turner user_input.RemoveBlankLines(); 22242c1f46dcSZachary Turner StreamString sstr; 22252c1f46dcSZachary Turner 22262c1f46dcSZachary Turner if (user_input.GetSize() == 0) 22272c1f46dcSZachary Turner return false; 22282c1f46dcSZachary Turner 2229b9c1b51eSKate Stone std::string auto_generated_function_name(GenerateUniqueName( 2230b9c1b51eSKate Stone "lldb_autogen_python_wp_callback_func_", num_created_functions)); 2231b9c1b51eSKate Stone sstr.Printf("def %s (frame, wp, internal_dict):", 2232b9c1b51eSKate Stone auto_generated_function_name.c_str()); 22332c1f46dcSZachary Turner 22342c1f46dcSZachary Turner if (!GenerateFunction(sstr.GetData(), user_input).Success()) 22352c1f46dcSZachary Turner return false; 22362c1f46dcSZachary Turner 22372c1f46dcSZachary Turner // Store the name of the auto-generated function to be called. 22382c1f46dcSZachary Turner output.assign(auto_generated_function_name); 22392c1f46dcSZachary Turner return true; 22402c1f46dcSZachary Turner } 22412c1f46dcSZachary Turner 224263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetScriptedSummary( 2243b9c1b51eSKate Stone const char *python_function_name, lldb::ValueObjectSP valobj, 2244b9c1b51eSKate Stone StructuredData::ObjectSP &callee_wrapper_sp, 2245b9c1b51eSKate Stone const TypeSummaryOptions &options, std::string &retval) { 22462c1f46dcSZachary Turner 22475c1c8443SJonas Devlieghere LLDB_SCOPED_TIMER(); 22482c1f46dcSZachary Turner 2249b9c1b51eSKate Stone if (!valobj.get()) { 22502c1f46dcSZachary Turner retval.assign("<no object>"); 22512c1f46dcSZachary Turner return false; 22522c1f46dcSZachary Turner } 22532c1f46dcSZachary Turner 22542c1f46dcSZachary Turner void *old_callee = nullptr; 22552c1f46dcSZachary Turner StructuredData::Generic *generic = nullptr; 2256b9c1b51eSKate Stone if (callee_wrapper_sp) { 22572c1f46dcSZachary Turner generic = callee_wrapper_sp->GetAsGeneric(); 22582c1f46dcSZachary Turner if (generic) 22592c1f46dcSZachary Turner old_callee = generic->GetValue(); 22602c1f46dcSZachary Turner } 22612c1f46dcSZachary Turner void *new_callee = old_callee; 22622c1f46dcSZachary Turner 22632c1f46dcSZachary Turner bool ret_val; 2264b9c1b51eSKate Stone if (python_function_name && *python_function_name) { 22652c1f46dcSZachary Turner { 2266b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | 2267b9c1b51eSKate Stone Locker::NoSTDIN); 22682c1f46dcSZachary Turner { 22692c1f46dcSZachary Turner TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options)); 22702c1f46dcSZachary Turner 227105495c5dSJonas Devlieghere static Timer::Category func_cat("LLDBSwigPythonCallTypeScript"); 227205495c5dSJonas Devlieghere Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript"); 227305495c5dSJonas Devlieghere ret_val = LLDBSwigPythonCallTypeScript( 2274b9c1b51eSKate Stone python_function_name, GetSessionDictionary().get(), valobj, 2275b9c1b51eSKate Stone &new_callee, options_sp, retval); 22762c1f46dcSZachary Turner } 22772c1f46dcSZachary Turner } 2278b9c1b51eSKate Stone } else { 22792c1f46dcSZachary Turner retval.assign("<no function name>"); 22802c1f46dcSZachary Turner return false; 22812c1f46dcSZachary Turner } 22822c1f46dcSZachary Turner 22832c1f46dcSZachary Turner if (new_callee && old_callee != new_callee) 2284796ac80bSJonas Devlieghere callee_wrapper_sp = std::make_shared<StructuredPythonObject>(new_callee); 22852c1f46dcSZachary Turner 22862c1f46dcSZachary Turner return ret_val; 22872c1f46dcSZachary Turner } 22882c1f46dcSZachary Turner 228963dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction( 2290b9c1b51eSKate Stone void *baton, StoppointCallbackContext *context, user_id_t break_id, 2291b9c1b51eSKate Stone user_id_t break_loc_id) { 2292f7e07256SJim Ingham CommandDataPython *bp_option_data = (CommandDataPython *)baton; 22932c1f46dcSZachary Turner const char *python_function_name = bp_option_data->script_source.c_str(); 22942c1f46dcSZachary Turner 22952c1f46dcSZachary Turner if (!context) 22962c1f46dcSZachary Turner return true; 22972c1f46dcSZachary Turner 22982c1f46dcSZachary Turner ExecutionContext exe_ctx(context->exe_ctx_ref); 22992c1f46dcSZachary Turner Target *target = exe_ctx.GetTargetPtr(); 23002c1f46dcSZachary Turner 23012c1f46dcSZachary Turner if (!target) 23022c1f46dcSZachary Turner return true; 23032c1f46dcSZachary Turner 23042c1f46dcSZachary Turner Debugger &debugger = target->GetDebugger(); 230563dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 2306d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 23072c1f46dcSZachary Turner 2308d055e3a0SPedro Tammela if (!python_interpreter) 23092c1f46dcSZachary Turner return true; 23102c1f46dcSZachary Turner 2311b9c1b51eSKate Stone if (python_function_name && python_function_name[0]) { 23122c1f46dcSZachary Turner const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP()); 23132c1f46dcSZachary Turner BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id); 2314b9c1b51eSKate Stone if (breakpoint_sp) { 2315b9c1b51eSKate Stone const BreakpointLocationSP bp_loc_sp( 2316b9c1b51eSKate Stone breakpoint_sp->FindLocationByID(break_loc_id)); 23172c1f46dcSZachary Turner 2318b9c1b51eSKate Stone if (stop_frame_sp && bp_loc_sp) { 23192c1f46dcSZachary Turner bool ret_val = true; 23202c1f46dcSZachary Turner { 2321b9c1b51eSKate Stone Locker py_lock(python_interpreter, Locker::AcquireLock | 2322b9c1b51eSKate Stone Locker::InitSession | 2323b9c1b51eSKate Stone Locker::NoSTDIN); 2324a69bbe02SLawrence D'Anna Expected<bool> maybe_ret_val = 2325a69bbe02SLawrence D'Anna LLDBSwigPythonBreakpointCallbackFunction( 2326b9c1b51eSKate Stone python_function_name, 2327b9c1b51eSKate Stone python_interpreter->m_dictionary_name.c_str(), stop_frame_sp, 2328a69bbe02SLawrence D'Anna bp_loc_sp, bp_option_data->m_extra_args_up.get()); 2329a69bbe02SLawrence D'Anna 2330a69bbe02SLawrence D'Anna if (!maybe_ret_val) { 2331a69bbe02SLawrence D'Anna 2332a69bbe02SLawrence D'Anna llvm::handleAllErrors( 2333a69bbe02SLawrence D'Anna maybe_ret_val.takeError(), 2334a69bbe02SLawrence D'Anna [&](PythonException &E) { 2335a69bbe02SLawrence D'Anna debugger.GetErrorStream() << E.ReadBacktrace(); 2336a69bbe02SLawrence D'Anna }, 2337a69bbe02SLawrence D'Anna [&](const llvm::ErrorInfoBase &E) { 2338a69bbe02SLawrence D'Anna debugger.GetErrorStream() << E.message(); 2339a69bbe02SLawrence D'Anna }); 2340a69bbe02SLawrence D'Anna 2341a69bbe02SLawrence D'Anna } else { 2342a69bbe02SLawrence D'Anna ret_val = maybe_ret_val.get(); 2343a69bbe02SLawrence D'Anna } 23442c1f46dcSZachary Turner } 23452c1f46dcSZachary Turner return ret_val; 23462c1f46dcSZachary Turner } 23472c1f46dcSZachary Turner } 23482c1f46dcSZachary Turner } 23492c1f46dcSZachary Turner // We currently always true so we stop in case anything goes wrong when 23502c1f46dcSZachary Turner // trying to call the script function 23512c1f46dcSZachary Turner return true; 23522c1f46dcSZachary Turner } 23532c1f46dcSZachary Turner 235463dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction( 2355b9c1b51eSKate Stone void *baton, StoppointCallbackContext *context, user_id_t watch_id) { 2356b9c1b51eSKate Stone WatchpointOptions::CommandData *wp_option_data = 2357b9c1b51eSKate Stone (WatchpointOptions::CommandData *)baton; 23582c1f46dcSZachary Turner const char *python_function_name = wp_option_data->script_source.c_str(); 23592c1f46dcSZachary Turner 23602c1f46dcSZachary Turner if (!context) 23612c1f46dcSZachary Turner return true; 23622c1f46dcSZachary Turner 23632c1f46dcSZachary Turner ExecutionContext exe_ctx(context->exe_ctx_ref); 23642c1f46dcSZachary Turner Target *target = exe_ctx.GetTargetPtr(); 23652c1f46dcSZachary Turner 23662c1f46dcSZachary Turner if (!target) 23672c1f46dcSZachary Turner return true; 23682c1f46dcSZachary Turner 23692c1f46dcSZachary Turner Debugger &debugger = target->GetDebugger(); 237063dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl *python_interpreter = 2371d055e3a0SPedro Tammela GetPythonInterpreter(debugger); 23722c1f46dcSZachary Turner 2373d055e3a0SPedro Tammela if (!python_interpreter) 23742c1f46dcSZachary Turner return true; 23752c1f46dcSZachary Turner 2376b9c1b51eSKate Stone if (python_function_name && python_function_name[0]) { 23772c1f46dcSZachary Turner const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP()); 23782c1f46dcSZachary Turner WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id); 2379b9c1b51eSKate Stone if (wp_sp) { 2380b9c1b51eSKate Stone if (stop_frame_sp && wp_sp) { 23812c1f46dcSZachary Turner bool ret_val = true; 23822c1f46dcSZachary Turner { 2383b9c1b51eSKate Stone Locker py_lock(python_interpreter, Locker::AcquireLock | 2384b9c1b51eSKate Stone Locker::InitSession | 2385b9c1b51eSKate Stone Locker::NoSTDIN); 238605495c5dSJonas Devlieghere ret_val = LLDBSwigPythonWatchpointCallbackFunction( 2387b9c1b51eSKate Stone python_function_name, 2388b9c1b51eSKate Stone python_interpreter->m_dictionary_name.c_str(), stop_frame_sp, 23892c1f46dcSZachary Turner wp_sp); 23902c1f46dcSZachary Turner } 23912c1f46dcSZachary Turner return ret_val; 23922c1f46dcSZachary Turner } 23932c1f46dcSZachary Turner } 23942c1f46dcSZachary Turner } 23952c1f46dcSZachary Turner // We currently always true so we stop in case anything goes wrong when 23962c1f46dcSZachary Turner // trying to call the script function 23972c1f46dcSZachary Turner return true; 23982c1f46dcSZachary Turner } 23992c1f46dcSZachary Turner 240063dd5d25SJonas Devlieghere size_t ScriptInterpreterPythonImpl::CalculateNumChildren( 2401b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp, uint32_t max) { 24022c1f46dcSZachary Turner if (!implementor_sp) 24032c1f46dcSZachary Turner return 0; 24042c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 24052c1f46dcSZachary Turner if (!generic) 24062c1f46dcSZachary Turner return 0; 24072c1f46dcSZachary Turner void *implementor = generic->GetValue(); 24082c1f46dcSZachary Turner if (!implementor) 24092c1f46dcSZachary Turner return 0; 24102c1f46dcSZachary Turner 24112c1f46dcSZachary Turner size_t ret_val = 0; 24122c1f46dcSZachary Turner 24132c1f46dcSZachary Turner { 2414b9c1b51eSKate Stone Locker py_lock(this, 2415b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 241605495c5dSJonas Devlieghere ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max); 24172c1f46dcSZachary Turner } 24182c1f46dcSZachary Turner 24192c1f46dcSZachary Turner return ret_val; 24202c1f46dcSZachary Turner } 24212c1f46dcSZachary Turner 242263dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex( 2423b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp, uint32_t idx) { 24242c1f46dcSZachary Turner if (!implementor_sp) 24252c1f46dcSZachary Turner return lldb::ValueObjectSP(); 24262c1f46dcSZachary Turner 24272c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 24282c1f46dcSZachary Turner if (!generic) 24292c1f46dcSZachary Turner return lldb::ValueObjectSP(); 24302c1f46dcSZachary Turner void *implementor = generic->GetValue(); 24312c1f46dcSZachary Turner if (!implementor) 24322c1f46dcSZachary Turner return lldb::ValueObjectSP(); 24332c1f46dcSZachary Turner 24342c1f46dcSZachary Turner lldb::ValueObjectSP ret_val; 24352c1f46dcSZachary Turner { 2436b9c1b51eSKate Stone Locker py_lock(this, 2437b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 243805495c5dSJonas Devlieghere void *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx); 2439b9c1b51eSKate Stone if (child_ptr != nullptr && child_ptr != Py_None) { 2440b9c1b51eSKate Stone lldb::SBValue *sb_value_ptr = 244105495c5dSJonas Devlieghere (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr); 24422c1f46dcSZachary Turner if (sb_value_ptr == nullptr) 24432c1f46dcSZachary Turner Py_XDECREF(child_ptr); 24442c1f46dcSZachary Turner else 244505495c5dSJonas Devlieghere ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); 2446b9c1b51eSKate Stone } else { 24472c1f46dcSZachary Turner Py_XDECREF(child_ptr); 24482c1f46dcSZachary Turner } 24492c1f46dcSZachary Turner } 24502c1f46dcSZachary Turner 24512c1f46dcSZachary Turner return ret_val; 24522c1f46dcSZachary Turner } 24532c1f46dcSZachary Turner 245463dd5d25SJonas Devlieghere int ScriptInterpreterPythonImpl::GetIndexOfChildWithName( 2455b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp, const char *child_name) { 24562c1f46dcSZachary Turner if (!implementor_sp) 24572c1f46dcSZachary Turner return UINT32_MAX; 24582c1f46dcSZachary Turner 24592c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 24602c1f46dcSZachary Turner if (!generic) 24612c1f46dcSZachary Turner return UINT32_MAX; 24622c1f46dcSZachary Turner void *implementor = generic->GetValue(); 24632c1f46dcSZachary Turner if (!implementor) 24642c1f46dcSZachary Turner return UINT32_MAX; 24652c1f46dcSZachary Turner 24662c1f46dcSZachary Turner int ret_val = UINT32_MAX; 24672c1f46dcSZachary Turner 24682c1f46dcSZachary Turner { 2469b9c1b51eSKate Stone Locker py_lock(this, 2470b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 247105495c5dSJonas Devlieghere ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name); 24722c1f46dcSZachary Turner } 24732c1f46dcSZachary Turner 24742c1f46dcSZachary Turner return ret_val; 24752c1f46dcSZachary Turner } 24762c1f46dcSZachary Turner 247763dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance( 2478b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) { 24792c1f46dcSZachary Turner bool ret_val = false; 24802c1f46dcSZachary Turner 24812c1f46dcSZachary Turner if (!implementor_sp) 24822c1f46dcSZachary Turner return ret_val; 24832c1f46dcSZachary Turner 24842c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 24852c1f46dcSZachary Turner if (!generic) 24862c1f46dcSZachary Turner return ret_val; 24872c1f46dcSZachary Turner void *implementor = generic->GetValue(); 24882c1f46dcSZachary Turner if (!implementor) 24892c1f46dcSZachary Turner return ret_val; 24902c1f46dcSZachary Turner 24912c1f46dcSZachary Turner { 2492b9c1b51eSKate Stone Locker py_lock(this, 2493b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 249405495c5dSJonas Devlieghere ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor); 24952c1f46dcSZachary Turner } 24962c1f46dcSZachary Turner 24972c1f46dcSZachary Turner return ret_val; 24982c1f46dcSZachary Turner } 24992c1f46dcSZachary Turner 250063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance( 2501b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) { 25022c1f46dcSZachary Turner bool ret_val = false; 25032c1f46dcSZachary Turner 25042c1f46dcSZachary Turner if (!implementor_sp) 25052c1f46dcSZachary Turner return ret_val; 25062c1f46dcSZachary Turner 25072c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 25082c1f46dcSZachary Turner if (!generic) 25092c1f46dcSZachary Turner return ret_val; 25102c1f46dcSZachary Turner void *implementor = generic->GetValue(); 25112c1f46dcSZachary Turner if (!implementor) 25122c1f46dcSZachary Turner return ret_val; 25132c1f46dcSZachary Turner 25142c1f46dcSZachary Turner { 2515b9c1b51eSKate Stone Locker py_lock(this, 2516b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 251705495c5dSJonas Devlieghere ret_val = 251805495c5dSJonas Devlieghere LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor); 25192c1f46dcSZachary Turner } 25202c1f46dcSZachary Turner 25212c1f46dcSZachary Turner return ret_val; 25222c1f46dcSZachary Turner } 25232c1f46dcSZachary Turner 252463dd5d25SJonas Devlieghere lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue( 2525b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) { 25262c1f46dcSZachary Turner lldb::ValueObjectSP ret_val(nullptr); 25272c1f46dcSZachary Turner 25282c1f46dcSZachary Turner if (!implementor_sp) 25292c1f46dcSZachary Turner return ret_val; 25302c1f46dcSZachary Turner 25312c1f46dcSZachary Turner StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 25322c1f46dcSZachary Turner if (!generic) 25332c1f46dcSZachary Turner return ret_val; 25342c1f46dcSZachary Turner void *implementor = generic->GetValue(); 25352c1f46dcSZachary Turner if (!implementor) 25362c1f46dcSZachary Turner return ret_val; 25372c1f46dcSZachary Turner 25382c1f46dcSZachary Turner { 2539b9c1b51eSKate Stone Locker py_lock(this, 2540b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 254105495c5dSJonas Devlieghere void *child_ptr = LLDBSwigPython_GetValueSynthProviderInstance(implementor); 2542b9c1b51eSKate Stone if (child_ptr != nullptr && child_ptr != Py_None) { 2543b9c1b51eSKate Stone lldb::SBValue *sb_value_ptr = 254405495c5dSJonas Devlieghere (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr); 25452c1f46dcSZachary Turner if (sb_value_ptr == nullptr) 25462c1f46dcSZachary Turner Py_XDECREF(child_ptr); 25472c1f46dcSZachary Turner else 254805495c5dSJonas Devlieghere ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); 2549b9c1b51eSKate Stone } else { 25502c1f46dcSZachary Turner Py_XDECREF(child_ptr); 25512c1f46dcSZachary Turner } 25522c1f46dcSZachary Turner } 25532c1f46dcSZachary Turner 25542c1f46dcSZachary Turner return ret_val; 25552c1f46dcSZachary Turner } 25562c1f46dcSZachary Turner 255763dd5d25SJonas Devlieghere ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName( 2558b9c1b51eSKate Stone const StructuredData::ObjectSP &implementor_sp) { 2559b9c1b51eSKate Stone Locker py_lock(this, 2560b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 25616eec8d6cSEnrico Granata 25626eec8d6cSEnrico Granata static char callee_name[] = "get_type_name"; 25636eec8d6cSEnrico Granata 25646eec8d6cSEnrico Granata ConstString ret_val; 25656eec8d6cSEnrico Granata bool got_string = false; 25666eec8d6cSEnrico Granata std::string buffer; 25676eec8d6cSEnrico Granata 25686eec8d6cSEnrico Granata if (!implementor_sp) 25696eec8d6cSEnrico Granata return ret_val; 25706eec8d6cSEnrico Granata 25716eec8d6cSEnrico Granata StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 25726eec8d6cSEnrico Granata if (!generic) 25736eec8d6cSEnrico Granata return ret_val; 2574b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 2575b9c1b51eSKate Stone (PyObject *)generic->GetValue()); 25766eec8d6cSEnrico Granata if (!implementor.IsAllocated()) 25776eec8d6cSEnrico Granata return ret_val; 25786eec8d6cSEnrico Granata 2579b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 2580b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 25816eec8d6cSEnrico Granata 25826eec8d6cSEnrico Granata if (PyErr_Occurred()) 25836eec8d6cSEnrico Granata PyErr_Clear(); 25846eec8d6cSEnrico Granata 25856eec8d6cSEnrico Granata if (!pmeth.IsAllocated()) 25866eec8d6cSEnrico Granata return ret_val; 25876eec8d6cSEnrico Granata 2588b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 25896eec8d6cSEnrico Granata if (PyErr_Occurred()) 25906eec8d6cSEnrico Granata PyErr_Clear(); 25916eec8d6cSEnrico Granata return ret_val; 25926eec8d6cSEnrico Granata } 25936eec8d6cSEnrico Granata 25946eec8d6cSEnrico Granata if (PyErr_Occurred()) 25956eec8d6cSEnrico Granata PyErr_Clear(); 25966eec8d6cSEnrico Granata 25976eec8d6cSEnrico Granata // right now we know this function exists and is callable.. 2598b9c1b51eSKate Stone PythonObject py_return( 2599b9c1b51eSKate Stone PyRefType::Owned, 2600b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 26016eec8d6cSEnrico Granata 26026eec8d6cSEnrico Granata // if it fails, print the error but otherwise go on 2603b9c1b51eSKate Stone if (PyErr_Occurred()) { 26046eec8d6cSEnrico Granata PyErr_Print(); 26056eec8d6cSEnrico Granata PyErr_Clear(); 26066eec8d6cSEnrico Granata } 26076eec8d6cSEnrico Granata 2608b9c1b51eSKate Stone if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { 26096eec8d6cSEnrico Granata PythonString py_string(PyRefType::Borrowed, py_return.get()); 26106eec8d6cSEnrico Granata llvm::StringRef return_data(py_string.GetString()); 2611b9c1b51eSKate Stone if (!return_data.empty()) { 26126eec8d6cSEnrico Granata buffer.assign(return_data.data(), return_data.size()); 26136eec8d6cSEnrico Granata got_string = true; 26146eec8d6cSEnrico Granata } 26156eec8d6cSEnrico Granata } 26166eec8d6cSEnrico Granata 26176eec8d6cSEnrico Granata if (got_string) 26186eec8d6cSEnrico Granata ret_val.SetCStringWithLength(buffer.c_str(), buffer.size()); 26196eec8d6cSEnrico Granata 26206eec8d6cSEnrico Granata return ret_val; 26216eec8d6cSEnrico Granata } 26226eec8d6cSEnrico Granata 262363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 262463dd5d25SJonas Devlieghere const char *impl_function, Process *process, std::string &output, 262597206d57SZachary Turner Status &error) { 26262c1f46dcSZachary Turner bool ret_val; 2627b9c1b51eSKate Stone if (!process) { 26282c1f46dcSZachary Turner error.SetErrorString("no process"); 26292c1f46dcSZachary Turner return false; 26302c1f46dcSZachary Turner } 2631b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 26322c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 26332c1f46dcSZachary Turner return false; 26342c1f46dcSZachary Turner } 263505495c5dSJonas Devlieghere 26362c1f46dcSZachary Turner { 26372c1f46dcSZachary Turner ProcessSP process_sp(process->shared_from_this()); 2638b9c1b51eSKate Stone Locker py_lock(this, 2639b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 264005495c5dSJonas Devlieghere ret_val = LLDBSWIGPythonRunScriptKeywordProcess( 2641b9c1b51eSKate Stone impl_function, m_dictionary_name.c_str(), process_sp, output); 26422c1f46dcSZachary Turner if (!ret_val) 26432c1f46dcSZachary Turner error.SetErrorString("python script evaluation failed"); 26442c1f46dcSZachary Turner } 26452c1f46dcSZachary Turner return ret_val; 26462c1f46dcSZachary Turner } 26472c1f46dcSZachary Turner 264863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 264963dd5d25SJonas Devlieghere const char *impl_function, Thread *thread, std::string &output, 265097206d57SZachary Turner Status &error) { 26512c1f46dcSZachary Turner bool ret_val; 2652b9c1b51eSKate Stone if (!thread) { 26532c1f46dcSZachary Turner error.SetErrorString("no thread"); 26542c1f46dcSZachary Turner return false; 26552c1f46dcSZachary Turner } 2656b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 26572c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 26582c1f46dcSZachary Turner return false; 26592c1f46dcSZachary Turner } 266005495c5dSJonas Devlieghere 26612c1f46dcSZachary Turner { 26622c1f46dcSZachary Turner ThreadSP thread_sp(thread->shared_from_this()); 2663b9c1b51eSKate Stone Locker py_lock(this, 2664b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 266505495c5dSJonas Devlieghere ret_val = LLDBSWIGPythonRunScriptKeywordThread( 2666b9c1b51eSKate Stone impl_function, m_dictionary_name.c_str(), thread_sp, output); 26672c1f46dcSZachary Turner if (!ret_val) 26682c1f46dcSZachary Turner error.SetErrorString("python script evaluation failed"); 26692c1f46dcSZachary Turner } 26702c1f46dcSZachary Turner return ret_val; 26712c1f46dcSZachary Turner } 26722c1f46dcSZachary Turner 267363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 267463dd5d25SJonas Devlieghere const char *impl_function, Target *target, std::string &output, 267597206d57SZachary Turner Status &error) { 26762c1f46dcSZachary Turner bool ret_val; 2677b9c1b51eSKate Stone if (!target) { 26782c1f46dcSZachary Turner error.SetErrorString("no thread"); 26792c1f46dcSZachary Turner return false; 26802c1f46dcSZachary Turner } 2681b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 26822c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 26832c1f46dcSZachary Turner return false; 26842c1f46dcSZachary Turner } 268505495c5dSJonas Devlieghere 26862c1f46dcSZachary Turner { 26872c1f46dcSZachary Turner TargetSP target_sp(target->shared_from_this()); 2688b9c1b51eSKate Stone Locker py_lock(this, 2689b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 269005495c5dSJonas Devlieghere ret_val = LLDBSWIGPythonRunScriptKeywordTarget( 2691b9c1b51eSKate Stone impl_function, m_dictionary_name.c_str(), target_sp, output); 26922c1f46dcSZachary Turner if (!ret_val) 26932c1f46dcSZachary Turner error.SetErrorString("python script evaluation failed"); 26942c1f46dcSZachary Turner } 26952c1f46dcSZachary Turner return ret_val; 26962c1f46dcSZachary Turner } 26972c1f46dcSZachary Turner 269863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 269963dd5d25SJonas Devlieghere const char *impl_function, StackFrame *frame, std::string &output, 270097206d57SZachary Turner Status &error) { 27012c1f46dcSZachary Turner bool ret_val; 2702b9c1b51eSKate Stone if (!frame) { 27032c1f46dcSZachary Turner error.SetErrorString("no frame"); 27042c1f46dcSZachary Turner return false; 27052c1f46dcSZachary Turner } 2706b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 27072c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 27082c1f46dcSZachary Turner return false; 27092c1f46dcSZachary Turner } 271005495c5dSJonas Devlieghere 27112c1f46dcSZachary Turner { 27122c1f46dcSZachary Turner StackFrameSP frame_sp(frame->shared_from_this()); 2713b9c1b51eSKate Stone Locker py_lock(this, 2714b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 271505495c5dSJonas Devlieghere ret_val = LLDBSWIGPythonRunScriptKeywordFrame( 2716b9c1b51eSKate Stone impl_function, m_dictionary_name.c_str(), frame_sp, output); 27172c1f46dcSZachary Turner if (!ret_val) 27182c1f46dcSZachary Turner error.SetErrorString("python script evaluation failed"); 27192c1f46dcSZachary Turner } 27202c1f46dcSZachary Turner return ret_val; 27212c1f46dcSZachary Turner } 27222c1f46dcSZachary Turner 272363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 272463dd5d25SJonas Devlieghere const char *impl_function, ValueObject *value, std::string &output, 272597206d57SZachary Turner Status &error) { 27262c1f46dcSZachary Turner bool ret_val; 2727b9c1b51eSKate Stone if (!value) { 27282c1f46dcSZachary Turner error.SetErrorString("no value"); 27292c1f46dcSZachary Turner return false; 27302c1f46dcSZachary Turner } 2731b9c1b51eSKate Stone if (!impl_function || !impl_function[0]) { 27322c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 27332c1f46dcSZachary Turner return false; 27342c1f46dcSZachary Turner } 273505495c5dSJonas Devlieghere 27362c1f46dcSZachary Turner { 27372c1f46dcSZachary Turner ValueObjectSP value_sp(value->GetSP()); 2738b9c1b51eSKate Stone Locker py_lock(this, 2739b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 274005495c5dSJonas Devlieghere ret_val = LLDBSWIGPythonRunScriptKeywordValue( 2741b9c1b51eSKate Stone impl_function, m_dictionary_name.c_str(), value_sp, output); 27422c1f46dcSZachary Turner if (!ret_val) 27432c1f46dcSZachary Turner error.SetErrorString("python script evaluation failed"); 27442c1f46dcSZachary Turner } 27452c1f46dcSZachary Turner return ret_val; 27462c1f46dcSZachary Turner } 27472c1f46dcSZachary Turner 2748b9c1b51eSKate Stone uint64_t replace_all(std::string &str, const std::string &oldStr, 2749b9c1b51eSKate Stone const std::string &newStr) { 27502c1f46dcSZachary Turner size_t pos = 0; 27512c1f46dcSZachary Turner uint64_t matches = 0; 2752b9c1b51eSKate Stone while ((pos = str.find(oldStr, pos)) != std::string::npos) { 27532c1f46dcSZachary Turner matches++; 27542c1f46dcSZachary Turner str.replace(pos, oldStr.length(), newStr); 27552c1f46dcSZachary Turner pos += newStr.length(); 27562c1f46dcSZachary Turner } 27572c1f46dcSZachary Turner return matches; 27582c1f46dcSZachary Turner } 27592c1f46dcSZachary Turner 276063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::LoadScriptingModule( 276115625112SJonas Devlieghere const char *pathname, bool init_session, lldb_private::Status &error, 276200bb397bSJonas Devlieghere StructuredData::ObjectSP *module_sp, FileSpec extra_search_dir) { 27633b33b416SJonas Devlieghere namespace fs = llvm::sys::fs; 276400bb397bSJonas Devlieghere namespace path = llvm::sys::path; 27653b33b416SJonas Devlieghere 2766b9c1b51eSKate Stone if (!pathname || !pathname[0]) { 27672c1f46dcSZachary Turner error.SetErrorString("invalid pathname"); 27682c1f46dcSZachary Turner return false; 27692c1f46dcSZachary Turner } 27702c1f46dcSZachary Turner 27718d1fb843SJonas Devlieghere lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); 27722c1f46dcSZachary Turner 2773f9f36097SAdrian McCarthy // Before executing Python code, lock the GIL. 277420b52c33SJonas Devlieghere Locker py_lock(this, 277520b52c33SJonas Devlieghere Locker::AcquireLock | 27763b33b416SJonas Devlieghere (init_session ? Locker::InitSession : 0) | Locker::NoSTDIN, 2777b9c1b51eSKate Stone Locker::FreeAcquiredLock | 2778b9c1b51eSKate Stone (init_session ? Locker::TearDownSession : 0)); 27792c1f46dcSZachary Turner 278000bb397bSJonas Devlieghere auto ExtendSysPath = [this](std::string directory) -> llvm::Error { 278100bb397bSJonas Devlieghere if (directory.empty()) { 278200bb397bSJonas Devlieghere return llvm::make_error<llvm::StringError>( 278300bb397bSJonas Devlieghere "invalid directory name", llvm::inconvertibleErrorCode()); 278442a9da7bSStefan Granitz } 278542a9da7bSStefan Granitz 2786f9f36097SAdrian McCarthy replace_all(directory, "\\", "\\\\"); 27872c1f46dcSZachary Turner replace_all(directory, "'", "\\'"); 27882c1f46dcSZachary Turner 278900bb397bSJonas Devlieghere // Make sure that Python has "directory" in the search path. 27902c1f46dcSZachary Turner StreamString command_stream; 2791b9c1b51eSKate Stone command_stream.Printf("if not (sys.path.__contains__('%s')):\n " 2792b9c1b51eSKate Stone "sys.path.insert(1,'%s');\n\n", 2793b9c1b51eSKate Stone directory.c_str(), directory.c_str()); 2794b9c1b51eSKate Stone bool syspath_retval = 2795b9c1b51eSKate Stone ExecuteMultipleLines(command_stream.GetData(), 2796b9c1b51eSKate Stone ScriptInterpreter::ExecuteScriptOptions() 2797b9c1b51eSKate Stone .SetEnableIO(false) 2798b9c1b51eSKate Stone .SetSetLLDBGlobals(false)) 2799b9c1b51eSKate Stone .Success(); 2800b9c1b51eSKate Stone if (!syspath_retval) { 280100bb397bSJonas Devlieghere return llvm::make_error<llvm::StringError>( 280200bb397bSJonas Devlieghere "Python sys.path handling failed", llvm::inconvertibleErrorCode()); 28032c1f46dcSZachary Turner } 28042c1f46dcSZachary Turner 280500bb397bSJonas Devlieghere return llvm::Error::success(); 280600bb397bSJonas Devlieghere }; 280700bb397bSJonas Devlieghere 280800bb397bSJonas Devlieghere std::string module_name(pathname); 2809d6e80578SJonas Devlieghere bool possible_package = false; 281000bb397bSJonas Devlieghere 281100bb397bSJonas Devlieghere if (extra_search_dir) { 281200bb397bSJonas Devlieghere if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) { 281300bb397bSJonas Devlieghere error = std::move(e); 281400bb397bSJonas Devlieghere return false; 281500bb397bSJonas Devlieghere } 281600bb397bSJonas Devlieghere } else { 281700bb397bSJonas Devlieghere FileSpec module_file(pathname); 281800bb397bSJonas Devlieghere FileSystem::Instance().Resolve(module_file); 281900bb397bSJonas Devlieghere FileSystem::Instance().Collect(module_file); 282000bb397bSJonas Devlieghere 282100bb397bSJonas Devlieghere fs::file_status st; 282200bb397bSJonas Devlieghere std::error_code ec = status(module_file.GetPath(), st); 282300bb397bSJonas Devlieghere 282400bb397bSJonas Devlieghere if (ec || st.type() == fs::file_type::status_error || 282500bb397bSJonas Devlieghere st.type() == fs::file_type::type_unknown || 282600bb397bSJonas Devlieghere st.type() == fs::file_type::file_not_found) { 282700bb397bSJonas Devlieghere // if not a valid file of any sort, check if it might be a filename still 282800bb397bSJonas Devlieghere // dot can't be used but / and \ can, and if either is found, reject 282900bb397bSJonas Devlieghere if (strchr(pathname, '\\') || strchr(pathname, '/')) { 283000bb397bSJonas Devlieghere error.SetErrorString("invalid pathname"); 283100bb397bSJonas Devlieghere return false; 283200bb397bSJonas Devlieghere } 283300bb397bSJonas Devlieghere // Not a filename, probably a package of some sort, let it go through. 2834d6e80578SJonas Devlieghere possible_package = true; 283500bb397bSJonas Devlieghere } else if (is_directory(st) || is_regular_file(st)) { 283600bb397bSJonas Devlieghere if (module_file.GetDirectory().IsEmpty()) { 283700bb397bSJonas Devlieghere error.SetErrorString("invalid directory name"); 283800bb397bSJonas Devlieghere return false; 283900bb397bSJonas Devlieghere } 284000bb397bSJonas Devlieghere if (llvm::Error e = 284100bb397bSJonas Devlieghere ExtendSysPath(module_file.GetDirectory().GetCString())) { 284200bb397bSJonas Devlieghere error = std::move(e); 284300bb397bSJonas Devlieghere return false; 284400bb397bSJonas Devlieghere } 284500bb397bSJonas Devlieghere module_name = module_file.GetFilename().GetCString(); 2846b9c1b51eSKate Stone } else { 28472c1f46dcSZachary Turner error.SetErrorString("no known way to import this module specification"); 28482c1f46dcSZachary Turner return false; 28492c1f46dcSZachary Turner } 285000bb397bSJonas Devlieghere } 28512c1f46dcSZachary Turner 28521197ee35SJonas Devlieghere // Strip .py or .pyc extension 285300bb397bSJonas Devlieghere llvm::StringRef extension = llvm::sys::path::extension(module_name); 28541197ee35SJonas Devlieghere if (!extension.empty()) { 28551197ee35SJonas Devlieghere if (extension == ".py") 285600bb397bSJonas Devlieghere module_name.resize(module_name.length() - 3); 28571197ee35SJonas Devlieghere else if (extension == ".pyc") 285800bb397bSJonas Devlieghere module_name.resize(module_name.length() - 4); 28591197ee35SJonas Devlieghere } 28601197ee35SJonas Devlieghere 2861d6e80578SJonas Devlieghere if (!possible_package && module_name.find('.') != llvm::StringRef::npos) { 2862d6e80578SJonas Devlieghere error.SetErrorStringWithFormat( 2863d6e80578SJonas Devlieghere "Python does not allow dots in module names: %s", module_name.c_str()); 2864d6e80578SJonas Devlieghere return false; 2865d6e80578SJonas Devlieghere } 2866d6e80578SJonas Devlieghere 2867d6e80578SJonas Devlieghere if (module_name.find('-') != llvm::StringRef::npos) { 2868d6e80578SJonas Devlieghere error.SetErrorStringWithFormat( 2869d6e80578SJonas Devlieghere "Python discourages dashes in module names: %s", module_name.c_str()); 2870d6e80578SJonas Devlieghere return false; 2871d6e80578SJonas Devlieghere } 2872d6e80578SJonas Devlieghere 28732c1f46dcSZachary Turner // check if the module is already import-ed 287400bb397bSJonas Devlieghere StreamString command_stream; 28752c1f46dcSZachary Turner command_stream.Clear(); 287600bb397bSJonas Devlieghere command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str()); 28772c1f46dcSZachary Turner bool does_contain = false; 287805097246SAdrian Prantl // this call will succeed if the module was ever imported in any Debugger 287905097246SAdrian Prantl // in the lifetime of the process in which this LLDB framework is living 2880b9c1b51eSKate Stone bool was_imported_globally = 2881b9c1b51eSKate Stone (ExecuteOneLineWithReturn( 2882b9c1b51eSKate Stone command_stream.GetData(), 288363dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, 2884b9c1b51eSKate Stone ScriptInterpreter::ExecuteScriptOptions() 2885b9c1b51eSKate Stone .SetEnableIO(false) 2886b9c1b51eSKate Stone .SetSetLLDBGlobals(false)) && 2887b9c1b51eSKate Stone does_contain); 2888b9c1b51eSKate Stone // this call will fail if the module was not imported in this Debugger 2889b9c1b51eSKate Stone // before 28902c1f46dcSZachary Turner command_stream.Clear(); 289100bb397bSJonas Devlieghere command_stream.Printf("sys.getrefcount(%s)", module_name.c_str()); 2892b9c1b51eSKate Stone bool was_imported_locally = GetSessionDictionary() 289300bb397bSJonas Devlieghere .GetItemForKey(PythonString(module_name)) 2894b9c1b51eSKate Stone .IsAllocated(); 28952c1f46dcSZachary Turner 28962c1f46dcSZachary Turner bool was_imported = (was_imported_globally || was_imported_locally); 28972c1f46dcSZachary Turner 28982c1f46dcSZachary Turner // now actually do the import 28992c1f46dcSZachary Turner command_stream.Clear(); 29002c1f46dcSZachary Turner 2901b9c1b51eSKate Stone if (was_imported) { 29022c1f46dcSZachary Turner if (!was_imported_locally) 290300bb397bSJonas Devlieghere command_stream.Printf("import %s ; reload_module(%s)", 290400bb397bSJonas Devlieghere module_name.c_str(), module_name.c_str()); 29052c1f46dcSZachary Turner else 290600bb397bSJonas Devlieghere command_stream.Printf("reload_module(%s)", module_name.c_str()); 2907b9c1b51eSKate Stone } else 290800bb397bSJonas Devlieghere command_stream.Printf("import %s", module_name.c_str()); 29092c1f46dcSZachary Turner 2910b9c1b51eSKate Stone error = ExecuteMultipleLines(command_stream.GetData(), 2911b9c1b51eSKate Stone ScriptInterpreter::ExecuteScriptOptions() 2912b9c1b51eSKate Stone .SetEnableIO(false) 2913b9c1b51eSKate Stone .SetSetLLDBGlobals(false)); 29142c1f46dcSZachary Turner if (error.Fail()) 29152c1f46dcSZachary Turner return false; 29162c1f46dcSZachary Turner 29172c1f46dcSZachary Turner // if we are here, everything worked 29182c1f46dcSZachary Turner // call __lldb_init_module(debugger,dict) 291900bb397bSJonas Devlieghere if (!LLDBSwigPythonCallModuleInit(module_name.c_str(), 292000bb397bSJonas Devlieghere m_dictionary_name.c_str(), debugger_sp)) { 29212c1f46dcSZachary Turner error.SetErrorString("calling __lldb_init_module failed"); 29222c1f46dcSZachary Turner return false; 29232c1f46dcSZachary Turner } 29242c1f46dcSZachary Turner 2925b9c1b51eSKate Stone if (module_sp) { 29262c1f46dcSZachary Turner // everything went just great, now set the module object 29272c1f46dcSZachary Turner command_stream.Clear(); 292800bb397bSJonas Devlieghere command_stream.Printf("%s", module_name.c_str()); 29292c1f46dcSZachary Turner void *module_pyobj = nullptr; 2930b9c1b51eSKate Stone if (ExecuteOneLineWithReturn( 2931b9c1b51eSKate Stone command_stream.GetData(), 29323b33b416SJonas Devlieghere ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj) && 2933b9c1b51eSKate Stone module_pyobj) 2934796ac80bSJonas Devlieghere *module_sp = std::make_shared<StructuredPythonObject>(module_pyobj); 29352c1f46dcSZachary Turner } 29362c1f46dcSZachary Turner 29372c1f46dcSZachary Turner return true; 29382c1f46dcSZachary Turner } 29392c1f46dcSZachary Turner 294063dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) { 29412c1f46dcSZachary Turner if (!word || !word[0]) 29422c1f46dcSZachary Turner return false; 29432c1f46dcSZachary Turner 29442c1f46dcSZachary Turner llvm::StringRef word_sr(word); 29452c1f46dcSZachary Turner 294605097246SAdrian Prantl // filter out a few characters that would just confuse us and that are 294705097246SAdrian Prantl // clearly not keyword material anyway 294810b113e8SJonas Devlieghere if (word_sr.find('"') != llvm::StringRef::npos || 294910b113e8SJonas Devlieghere word_sr.find('\'') != llvm::StringRef::npos) 29502c1f46dcSZachary Turner return false; 29512c1f46dcSZachary Turner 29522c1f46dcSZachary Turner StreamString command_stream; 29532c1f46dcSZachary Turner command_stream.Printf("keyword.iskeyword('%s')", word); 29542c1f46dcSZachary Turner bool result; 29552c1f46dcSZachary Turner ExecuteScriptOptions options; 29562c1f46dcSZachary Turner options.SetEnableIO(false); 29572c1f46dcSZachary Turner options.SetMaskoutErrors(true); 29582c1f46dcSZachary Turner options.SetSetLLDBGlobals(false); 2959b9c1b51eSKate Stone if (ExecuteOneLineWithReturn(command_stream.GetData(), 2960b9c1b51eSKate Stone ScriptInterpreter::eScriptReturnTypeBool, 2961b9c1b51eSKate Stone &result, options)) 29622c1f46dcSZachary Turner return result; 29632c1f46dcSZachary Turner return false; 29642c1f46dcSZachary Turner } 29652c1f46dcSZachary Turner 296663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler( 2967b9c1b51eSKate Stone lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro) 2968b9c1b51eSKate Stone : m_debugger_sp(debugger_sp), m_synch_wanted(synchro), 2969b9c1b51eSKate Stone m_old_asynch(debugger_sp->GetAsyncExecution()) { 29702c1f46dcSZachary Turner if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous) 29712c1f46dcSZachary Turner m_debugger_sp->SetAsyncExecution(false); 29722c1f46dcSZachary Turner else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous) 29732c1f46dcSZachary Turner m_debugger_sp->SetAsyncExecution(true); 29742c1f46dcSZachary Turner } 29752c1f46dcSZachary Turner 297663dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() { 29772c1f46dcSZachary Turner if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue) 29782c1f46dcSZachary Turner m_debugger_sp->SetAsyncExecution(m_old_asynch); 29792c1f46dcSZachary Turner } 29802c1f46dcSZachary Turner 298163dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand( 29824d51a902SRaphael Isemann const char *impl_function, llvm::StringRef args, 29832c1f46dcSZachary Turner ScriptedCommandSynchronicity synchronicity, 298497206d57SZachary Turner lldb_private::CommandReturnObject &cmd_retobj, Status &error, 2985b9c1b51eSKate Stone const lldb_private::ExecutionContext &exe_ctx) { 2986b9c1b51eSKate Stone if (!impl_function) { 29872c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 29882c1f46dcSZachary Turner return false; 29892c1f46dcSZachary Turner } 29902c1f46dcSZachary Turner 29918d1fb843SJonas Devlieghere lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); 29922c1f46dcSZachary Turner lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); 29932c1f46dcSZachary Turner 2994b9c1b51eSKate Stone if (!debugger_sp.get()) { 29952c1f46dcSZachary Turner error.SetErrorString("invalid Debugger pointer"); 29962c1f46dcSZachary Turner return false; 29972c1f46dcSZachary Turner } 29982c1f46dcSZachary Turner 29992c1f46dcSZachary Turner bool ret_val = false; 30002c1f46dcSZachary Turner 30012c1f46dcSZachary Turner std::string err_msg; 30022c1f46dcSZachary Turner 30032c1f46dcSZachary Turner { 30042c1f46dcSZachary Turner Locker py_lock(this, 3005b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | 3006b9c1b51eSKate Stone (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN), 30072c1f46dcSZachary Turner Locker::FreeLock | Locker::TearDownSession); 30082c1f46dcSZachary Turner 3009b9c1b51eSKate Stone SynchronicityHandler synch_handler(debugger_sp, synchronicity); 30102c1f46dcSZachary Turner 30114d51a902SRaphael Isemann std::string args_str = args.str(); 301205495c5dSJonas Devlieghere ret_val = LLDBSwigPythonCallCommand( 301305495c5dSJonas Devlieghere impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(), 301405495c5dSJonas Devlieghere cmd_retobj, exe_ctx_ref_sp); 30152c1f46dcSZachary Turner } 30162c1f46dcSZachary Turner 30172c1f46dcSZachary Turner if (!ret_val) 30182c1f46dcSZachary Turner error.SetErrorString("unable to execute script function"); 30192c1f46dcSZachary Turner else 30202c1f46dcSZachary Turner error.Clear(); 30212c1f46dcSZachary Turner 30222c1f46dcSZachary Turner return ret_val; 30232c1f46dcSZachary Turner } 30242c1f46dcSZachary Turner 302563dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::RunScriptBasedCommand( 30264d51a902SRaphael Isemann StructuredData::GenericSP impl_obj_sp, llvm::StringRef args, 30272c1f46dcSZachary Turner ScriptedCommandSynchronicity synchronicity, 302897206d57SZachary Turner lldb_private::CommandReturnObject &cmd_retobj, Status &error, 3029b9c1b51eSKate Stone const lldb_private::ExecutionContext &exe_ctx) { 3030b9c1b51eSKate Stone if (!impl_obj_sp || !impl_obj_sp->IsValid()) { 30312c1f46dcSZachary Turner error.SetErrorString("no function to execute"); 30322c1f46dcSZachary Turner return false; 30332c1f46dcSZachary Turner } 30342c1f46dcSZachary Turner 30358d1fb843SJonas Devlieghere lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); 30362c1f46dcSZachary Turner lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); 30372c1f46dcSZachary Turner 3038b9c1b51eSKate Stone if (!debugger_sp.get()) { 30392c1f46dcSZachary Turner error.SetErrorString("invalid Debugger pointer"); 30402c1f46dcSZachary Turner return false; 30412c1f46dcSZachary Turner } 30422c1f46dcSZachary Turner 30432c1f46dcSZachary Turner bool ret_val = false; 30442c1f46dcSZachary Turner 30452c1f46dcSZachary Turner std::string err_msg; 30462c1f46dcSZachary Turner 30472c1f46dcSZachary Turner { 30482c1f46dcSZachary Turner Locker py_lock(this, 3049b9c1b51eSKate Stone Locker::AcquireLock | Locker::InitSession | 3050b9c1b51eSKate Stone (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN), 30512c1f46dcSZachary Turner Locker::FreeLock | Locker::TearDownSession); 30522c1f46dcSZachary Turner 3053b9c1b51eSKate Stone SynchronicityHandler synch_handler(debugger_sp, synchronicity); 30542c1f46dcSZachary Turner 30554d51a902SRaphael Isemann std::string args_str = args.str(); 305605495c5dSJonas Devlieghere ret_val = LLDBSwigPythonCallCommandObject(impl_obj_sp->GetValue(), 305705495c5dSJonas Devlieghere debugger_sp, args_str.c_str(), 305805495c5dSJonas Devlieghere cmd_retobj, exe_ctx_ref_sp); 30592c1f46dcSZachary Turner } 30602c1f46dcSZachary Turner 30612c1f46dcSZachary Turner if (!ret_val) 30622c1f46dcSZachary Turner error.SetErrorString("unable to execute script function"); 30632c1f46dcSZachary Turner else 30642c1f46dcSZachary Turner error.Clear(); 30652c1f46dcSZachary Turner 30662c1f46dcSZachary Turner return ret_val; 30672c1f46dcSZachary Turner } 30682c1f46dcSZachary Turner 306993571c3cSJonas Devlieghere /// In Python, a special attribute __doc__ contains the docstring for an object 307093571c3cSJonas Devlieghere /// (function, method, class, ...) if any is defined Otherwise, the attribute's 307193571c3cSJonas Devlieghere /// value is None. 307263dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item, 3073b9c1b51eSKate Stone std::string &dest) { 30742c1f46dcSZachary Turner dest.clear(); 307593571c3cSJonas Devlieghere 30762c1f46dcSZachary Turner if (!item || !*item) 30772c1f46dcSZachary Turner return false; 307893571c3cSJonas Devlieghere 30792c1f46dcSZachary Turner std::string command(item); 30802c1f46dcSZachary Turner command += ".__doc__"; 30812c1f46dcSZachary Turner 308293571c3cSJonas Devlieghere // Python is going to point this to valid data if ExecuteOneLineWithReturn 308393571c3cSJonas Devlieghere // returns successfully. 308493571c3cSJonas Devlieghere char *result_ptr = nullptr; 30852c1f46dcSZachary Turner 3086b9c1b51eSKate Stone if (ExecuteOneLineWithReturn( 308793571c3cSJonas Devlieghere command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone, 30882c1f46dcSZachary Turner &result_ptr, 3089b9c1b51eSKate Stone ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false))) { 30902c1f46dcSZachary Turner if (result_ptr) 30912c1f46dcSZachary Turner dest.assign(result_ptr); 30922c1f46dcSZachary Turner return true; 30932c1f46dcSZachary Turner } 309493571c3cSJonas Devlieghere 309593571c3cSJonas Devlieghere StreamString str_stream; 309693571c3cSJonas Devlieghere str_stream << "Function " << item 309793571c3cSJonas Devlieghere << " was not found. Containing module might be missing."; 309893571c3cSJonas Devlieghere dest = std::string(str_stream.GetString()); 309993571c3cSJonas Devlieghere 310093571c3cSJonas Devlieghere return false; 31012c1f46dcSZachary Turner } 31022c1f46dcSZachary Turner 310363dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject( 3104b9c1b51eSKate Stone StructuredData::GenericSP cmd_obj_sp, std::string &dest) { 31052c1f46dcSZachary Turner dest.clear(); 31062c1f46dcSZachary Turner 3107b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 31082c1f46dcSZachary Turner 31092c1f46dcSZachary Turner static char callee_name[] = "get_short_help"; 31102c1f46dcSZachary Turner 31112c1f46dcSZachary Turner if (!cmd_obj_sp) 31122c1f46dcSZachary Turner return false; 31132c1f46dcSZachary Turner 3114b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 3115b9c1b51eSKate Stone (PyObject *)cmd_obj_sp->GetValue()); 31162c1f46dcSZachary Turner 3117f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 31182c1f46dcSZachary Turner return false; 31192c1f46dcSZachary Turner 3120b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 3121b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 31222c1f46dcSZachary Turner 31232c1f46dcSZachary Turner if (PyErr_Occurred()) 31242c1f46dcSZachary Turner PyErr_Clear(); 31252c1f46dcSZachary Turner 3126f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 31272c1f46dcSZachary Turner return false; 31282c1f46dcSZachary Turner 3129b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 31302c1f46dcSZachary Turner if (PyErr_Occurred()) 31312c1f46dcSZachary Turner PyErr_Clear(); 31322c1f46dcSZachary Turner return false; 31332c1f46dcSZachary Turner } 31342c1f46dcSZachary Turner 31352c1f46dcSZachary Turner if (PyErr_Occurred()) 31362c1f46dcSZachary Turner PyErr_Clear(); 31372c1f46dcSZachary Turner 313893571c3cSJonas Devlieghere // Right now we know this function exists and is callable. 3139b9c1b51eSKate Stone PythonObject py_return( 3140b9c1b51eSKate Stone PyRefType::Owned, 3141b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 31422c1f46dcSZachary Turner 314393571c3cSJonas Devlieghere // If it fails, print the error but otherwise go on. 3144b9c1b51eSKate Stone if (PyErr_Occurred()) { 31452c1f46dcSZachary Turner PyErr_Print(); 31462c1f46dcSZachary Turner PyErr_Clear(); 31472c1f46dcSZachary Turner } 31482c1f46dcSZachary Turner 3149b9c1b51eSKate Stone if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { 3150f8b22f8fSZachary Turner PythonString py_string(PyRefType::Borrowed, py_return.get()); 315122c8efcdSZachary Turner llvm::StringRef return_data(py_string.GetString()); 315222c8efcdSZachary Turner dest.assign(return_data.data(), return_data.size()); 315393571c3cSJonas Devlieghere return true; 31542c1f46dcSZachary Turner } 315593571c3cSJonas Devlieghere 315693571c3cSJonas Devlieghere return false; 31572c1f46dcSZachary Turner } 31582c1f46dcSZachary Turner 315963dd5d25SJonas Devlieghere uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject( 3160b9c1b51eSKate Stone StructuredData::GenericSP cmd_obj_sp) { 31612c1f46dcSZachary Turner uint32_t result = 0; 31622c1f46dcSZachary Turner 3163b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 31642c1f46dcSZachary Turner 31652c1f46dcSZachary Turner static char callee_name[] = "get_flags"; 31662c1f46dcSZachary Turner 31672c1f46dcSZachary Turner if (!cmd_obj_sp) 31682c1f46dcSZachary Turner return result; 31692c1f46dcSZachary Turner 3170b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 3171b9c1b51eSKate Stone (PyObject *)cmd_obj_sp->GetValue()); 31722c1f46dcSZachary Turner 3173f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 31742c1f46dcSZachary Turner return result; 31752c1f46dcSZachary Turner 3176b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 3177b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 31782c1f46dcSZachary Turner 31792c1f46dcSZachary Turner if (PyErr_Occurred()) 31802c1f46dcSZachary Turner PyErr_Clear(); 31812c1f46dcSZachary Turner 3182f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 31832c1f46dcSZachary Turner return result; 31842c1f46dcSZachary Turner 3185b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 31862c1f46dcSZachary Turner if (PyErr_Occurred()) 31872c1f46dcSZachary Turner PyErr_Clear(); 31882c1f46dcSZachary Turner return result; 31892c1f46dcSZachary Turner } 31902c1f46dcSZachary Turner 31912c1f46dcSZachary Turner if (PyErr_Occurred()) 31922c1f46dcSZachary Turner PyErr_Clear(); 31932c1f46dcSZachary Turner 319452712d3fSLawrence D'Anna long long py_return = unwrapOrSetPythonException( 319552712d3fSLawrence D'Anna As<long long>(implementor.CallMethod(callee_name))); 31962c1f46dcSZachary Turner 31972c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 3198b9c1b51eSKate Stone if (PyErr_Occurred()) { 31992c1f46dcSZachary Turner PyErr_Print(); 32002c1f46dcSZachary Turner PyErr_Clear(); 320152712d3fSLawrence D'Anna } else { 320252712d3fSLawrence D'Anna result = py_return; 32032c1f46dcSZachary Turner } 32042c1f46dcSZachary Turner 32052c1f46dcSZachary Turner return result; 32062c1f46dcSZachary Turner } 32072c1f46dcSZachary Turner 320863dd5d25SJonas Devlieghere bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject( 3209b9c1b51eSKate Stone StructuredData::GenericSP cmd_obj_sp, std::string &dest) { 32102c1f46dcSZachary Turner bool got_string = false; 32112c1f46dcSZachary Turner dest.clear(); 32122c1f46dcSZachary Turner 3213b9c1b51eSKate Stone Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 32142c1f46dcSZachary Turner 32152c1f46dcSZachary Turner static char callee_name[] = "get_long_help"; 32162c1f46dcSZachary Turner 32172c1f46dcSZachary Turner if (!cmd_obj_sp) 32182c1f46dcSZachary Turner return false; 32192c1f46dcSZachary Turner 3220b9c1b51eSKate Stone PythonObject implementor(PyRefType::Borrowed, 3221b9c1b51eSKate Stone (PyObject *)cmd_obj_sp->GetValue()); 32222c1f46dcSZachary Turner 3223f8b22f8fSZachary Turner if (!implementor.IsAllocated()) 32242c1f46dcSZachary Turner return false; 32252c1f46dcSZachary Turner 3226b9c1b51eSKate Stone PythonObject pmeth(PyRefType::Owned, 3227b9c1b51eSKate Stone PyObject_GetAttrString(implementor.get(), callee_name)); 32282c1f46dcSZachary Turner 32292c1f46dcSZachary Turner if (PyErr_Occurred()) 32302c1f46dcSZachary Turner PyErr_Clear(); 32312c1f46dcSZachary Turner 3232f8b22f8fSZachary Turner if (!pmeth.IsAllocated()) 32332c1f46dcSZachary Turner return false; 32342c1f46dcSZachary Turner 3235b9c1b51eSKate Stone if (PyCallable_Check(pmeth.get()) == 0) { 32362c1f46dcSZachary Turner if (PyErr_Occurred()) 32372c1f46dcSZachary Turner PyErr_Clear(); 32382c1f46dcSZachary Turner 32392c1f46dcSZachary Turner return false; 32402c1f46dcSZachary Turner } 32412c1f46dcSZachary Turner 32422c1f46dcSZachary Turner if (PyErr_Occurred()) 32432c1f46dcSZachary Turner PyErr_Clear(); 32442c1f46dcSZachary Turner 32452c1f46dcSZachary Turner // right now we know this function exists and is callable.. 3246b9c1b51eSKate Stone PythonObject py_return( 3247b9c1b51eSKate Stone PyRefType::Owned, 3248b9c1b51eSKate Stone PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 32492c1f46dcSZachary Turner 32502c1f46dcSZachary Turner // if it fails, print the error but otherwise go on 3251b9c1b51eSKate Stone if (PyErr_Occurred()) { 32522c1f46dcSZachary Turner PyErr_Print(); 32532c1f46dcSZachary Turner PyErr_Clear(); 32542c1f46dcSZachary Turner } 32552c1f46dcSZachary Turner 3256b9c1b51eSKate Stone if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { 3257f8b22f8fSZachary Turner PythonString str(PyRefType::Borrowed, py_return.get()); 325822c8efcdSZachary Turner llvm::StringRef str_data(str.GetString()); 325922c8efcdSZachary Turner dest.assign(str_data.data(), str_data.size()); 32602c1f46dcSZachary Turner got_string = true; 32612c1f46dcSZachary Turner } 32622c1f46dcSZachary Turner 32632c1f46dcSZachary Turner return got_string; 32642c1f46dcSZachary Turner } 32652c1f46dcSZachary Turner 32662c1f46dcSZachary Turner std::unique_ptr<ScriptInterpreterLocker> 326763dd5d25SJonas Devlieghere ScriptInterpreterPythonImpl::AcquireInterpreterLock() { 3268b9c1b51eSKate Stone std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker( 3269b9c1b51eSKate Stone this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN, 32702c1f46dcSZachary Turner Locker::FreeLock | Locker::TearDownSession)); 32712c1f46dcSZachary Turner return py_lock; 32722c1f46dcSZachary Turner } 32732c1f46dcSZachary Turner 327463dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::InitializePrivate() { 327515d1b4e2SEnrico Granata if (g_initialized) 327615d1b4e2SEnrico Granata return; 327715d1b4e2SEnrico Granata 32782c1f46dcSZachary Turner g_initialized = true; 32792c1f46dcSZachary Turner 32805c1c8443SJonas Devlieghere LLDB_SCOPED_TIMER(); 32812c1f46dcSZachary Turner 3282b9c1b51eSKate Stone // RAII-based initialization which correctly handles multiple-initialization, 328305097246SAdrian Prantl // version- specific differences among Python 2 and Python 3, and saving and 328405097246SAdrian Prantl // restoring various other pieces of state that can get mucked with during 328505097246SAdrian Prantl // initialization. 3286079fe48aSZachary Turner InitializePythonRAII initialize_guard; 32872c1f46dcSZachary Turner 328805495c5dSJonas Devlieghere LLDBSwigPyInit(); 32892c1f46dcSZachary Turner 3290b9c1b51eSKate Stone // Update the path python uses to search for modules to include the current 3291b9c1b51eSKate Stone // directory. 32922c1f46dcSZachary Turner 32932c1f46dcSZachary Turner PyRun_SimpleString("import sys"); 32942c1f46dcSZachary Turner AddToSysPath(AddLocation::End, "."); 32952c1f46dcSZachary Turner 3296b9c1b51eSKate Stone // Don't denormalize paths when calling file_spec.GetPath(). On platforms 329705097246SAdrian Prantl // that use a backslash as the path separator, this will result in executing 329805097246SAdrian Prantl // python code containing paths with unescaped backslashes. But Python also 329905097246SAdrian Prantl // accepts forward slashes, so to make life easier we just use that. 33002df331b0SPavel Labath if (FileSpec file_spec = GetPythonDir()) 33012c1f46dcSZachary Turner AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false)); 330260f028ffSPavel Labath if (FileSpec file_spec = HostInfo::GetShlibDir()) 33032c1f46dcSZachary Turner AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false)); 33042c1f46dcSZachary Turner 3305b9c1b51eSKate Stone PyRun_SimpleString("sys.dont_write_bytecode = 1; import " 3306b9c1b51eSKate Stone "lldb.embedded_interpreter; from " 3307b9c1b51eSKate Stone "lldb.embedded_interpreter import run_python_interpreter; " 3308b9c1b51eSKate Stone "from lldb.embedded_interpreter import run_one_line"); 33092c1f46dcSZachary Turner } 33102c1f46dcSZachary Turner 331163dd5d25SJonas Devlieghere void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location, 3312b9c1b51eSKate Stone std::string path) { 33132c1f46dcSZachary Turner std::string path_copy; 33142c1f46dcSZachary Turner 33152c1f46dcSZachary Turner std::string statement; 3316b9c1b51eSKate Stone if (location == AddLocation::Beginning) { 33172c1f46dcSZachary Turner statement.assign("sys.path.insert(0,\""); 33182c1f46dcSZachary Turner statement.append(path); 33192c1f46dcSZachary Turner statement.append("\")"); 3320b9c1b51eSKate Stone } else { 33212c1f46dcSZachary Turner statement.assign("sys.path.append(\""); 33222c1f46dcSZachary Turner statement.append(path); 33232c1f46dcSZachary Turner statement.append("\")"); 33242c1f46dcSZachary Turner } 33252c1f46dcSZachary Turner PyRun_SimpleString(statement.c_str()); 33262c1f46dcSZachary Turner } 33272c1f46dcSZachary Turner 3328bcadb5a3SPavel Labath // We are intentionally NOT calling Py_Finalize here (this would be the logical 3329bcadb5a3SPavel Labath // place to call it). Calling Py_Finalize here causes test suite runs to seg 3330bcadb5a3SPavel Labath // fault: The test suite runs in Python. It registers SBDebugger::Terminate to 3331bcadb5a3SPavel Labath // be called 'at_exit'. When the test suite Python harness finishes up, it 3332bcadb5a3SPavel Labath // calls Py_Finalize, which calls all the 'at_exit' registered functions. 3333bcadb5a3SPavel Labath // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate, 3334bcadb5a3SPavel Labath // which calls ScriptInterpreter::Terminate, which calls 333563dd5d25SJonas Devlieghere // ScriptInterpreterPythonImpl::Terminate. So if we call Py_Finalize here, we 333663dd5d25SJonas Devlieghere // end up with Py_Finalize being called from within Py_Finalize, which results 333763dd5d25SJonas Devlieghere // in a seg fault. Since this function only gets called when lldb is shutting 333863dd5d25SJonas Devlieghere // down and going away anyway, the fact that we don't actually call Py_Finalize 3339bcadb5a3SPavel Labath // should not cause any problems (everything should shut down/go away anyway 3340bcadb5a3SPavel Labath // when the process exits). 3341bcadb5a3SPavel Labath // 334263dd5d25SJonas Devlieghere // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); } 3343d68983e3SPavel Labath 33444e26cf2cSJonas Devlieghere #endif 3345