1*dda28197Spatrick //===-- ScriptInterpreterPython.cpp ---------------------------------------===// 2061da546Spatrick // 3061da546Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4061da546Spatrick // See https://llvm.org/LICENSE.txt for license information. 5061da546Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6061da546Spatrick // 7061da546Spatrick //===----------------------------------------------------------------------===// 8061da546Spatrick 9061da546Spatrick #include "lldb/Host/Config.h" 10061da546Spatrick 11061da546Spatrick #if LLDB_ENABLE_PYTHON 12061da546Spatrick 13061da546Spatrick // LLDB Python header must be included first 14061da546Spatrick #include "lldb-python.h" 15061da546Spatrick 16061da546Spatrick #include "PythonDataObjects.h" 17061da546Spatrick #include "PythonReadline.h" 18061da546Spatrick #include "ScriptInterpreterPythonImpl.h" 19061da546Spatrick #include "lldb/API/SBFrame.h" 20061da546Spatrick #include "lldb/API/SBValue.h" 21061da546Spatrick #include "lldb/Breakpoint/StoppointCallbackContext.h" 22061da546Spatrick #include "lldb/Breakpoint/WatchpointOptions.h" 23061da546Spatrick #include "lldb/Core/Communication.h" 24061da546Spatrick #include "lldb/Core/Debugger.h" 25061da546Spatrick #include "lldb/Core/PluginManager.h" 26061da546Spatrick #include "lldb/Core/ValueObject.h" 27061da546Spatrick #include "lldb/DataFormatters/TypeSummary.h" 28061da546Spatrick #include "lldb/Host/FileSystem.h" 29061da546Spatrick #include "lldb/Host/HostInfo.h" 30061da546Spatrick #include "lldb/Host/Pipe.h" 31061da546Spatrick #include "lldb/Interpreter/CommandInterpreter.h" 32061da546Spatrick #include "lldb/Interpreter/CommandReturnObject.h" 33061da546Spatrick #include "lldb/Target/Thread.h" 34061da546Spatrick #include "lldb/Target/ThreadPlan.h" 35061da546Spatrick #include "lldb/Utility/Timer.h" 36061da546Spatrick #include "llvm/ADT/STLExtras.h" 37061da546Spatrick #include "llvm/ADT/StringRef.h" 38*dda28197Spatrick #include "llvm/Support/Error.h" 39061da546Spatrick #include "llvm/Support/FileSystem.h" 40061da546Spatrick #include "llvm/Support/FormatAdapters.h" 41061da546Spatrick 42061da546Spatrick #include <memory> 43061da546Spatrick #include <mutex> 44061da546Spatrick #include <stdio.h> 45061da546Spatrick #include <stdlib.h> 46061da546Spatrick #include <string> 47061da546Spatrick 48061da546Spatrick using namespace lldb; 49061da546Spatrick using namespace lldb_private; 50061da546Spatrick using namespace lldb_private::python; 51061da546Spatrick using llvm::Expected; 52061da546Spatrick 53*dda28197Spatrick LLDB_PLUGIN_DEFINE(ScriptInterpreterPython) 54*dda28197Spatrick 55061da546Spatrick // Defined in the SWIG source file 56061da546Spatrick #if PY_MAJOR_VERSION >= 3 57061da546Spatrick extern "C" PyObject *PyInit__lldb(void); 58061da546Spatrick 59061da546Spatrick #define LLDBSwigPyInit PyInit__lldb 60061da546Spatrick 61061da546Spatrick #else 62061da546Spatrick extern "C" void init_lldb(void); 63061da546Spatrick 64061da546Spatrick #define LLDBSwigPyInit init_lldb 65061da546Spatrick #endif 66061da546Spatrick 67061da546Spatrick // These prototypes are the Pythonic implementations of the required callbacks. 68061da546Spatrick // Although these are scripting-language specific, their definition depends on 69061da546Spatrick // the public API. 70061da546Spatrick 71061da546Spatrick #pragma clang diagnostic push 72061da546Spatrick #pragma clang diagnostic ignored "-Wreturn-type-c-linkage" 73061da546Spatrick 74061da546Spatrick // Disable warning C4190: 'LLDBSwigPythonBreakpointCallbackFunction' has 75061da546Spatrick // C-linkage specified, but returns UDT 'llvm::Expected<bool>' which is 76061da546Spatrick // incompatible with C 77061da546Spatrick #if _MSC_VER 78061da546Spatrick #pragma warning (push) 79061da546Spatrick #pragma warning (disable : 4190) 80061da546Spatrick #endif 81061da546Spatrick 82061da546Spatrick extern "C" llvm::Expected<bool> LLDBSwigPythonBreakpointCallbackFunction( 83061da546Spatrick const char *python_function_name, const char *session_dictionary_name, 84061da546Spatrick const lldb::StackFrameSP &sb_frame, 85061da546Spatrick const lldb::BreakpointLocationSP &sb_bp_loc, StructuredDataImpl *args_impl); 86061da546Spatrick 87061da546Spatrick #if _MSC_VER 88061da546Spatrick #pragma warning (pop) 89061da546Spatrick #endif 90061da546Spatrick 91061da546Spatrick #pragma clang diagnostic pop 92061da546Spatrick 93061da546Spatrick extern "C" bool LLDBSwigPythonWatchpointCallbackFunction( 94061da546Spatrick const char *python_function_name, const char *session_dictionary_name, 95061da546Spatrick const lldb::StackFrameSP &sb_frame, const lldb::WatchpointSP &sb_wp); 96061da546Spatrick 97061da546Spatrick extern "C" bool LLDBSwigPythonCallTypeScript( 98061da546Spatrick const char *python_function_name, void *session_dictionary, 99061da546Spatrick const lldb::ValueObjectSP &valobj_sp, void **pyfunct_wrapper, 100061da546Spatrick const lldb::TypeSummaryOptionsSP &options_sp, std::string &retval); 101061da546Spatrick 102061da546Spatrick extern "C" void * 103061da546Spatrick LLDBSwigPythonCreateSyntheticProvider(const char *python_class_name, 104061da546Spatrick const char *session_dictionary_name, 105061da546Spatrick const lldb::ValueObjectSP &valobj_sp); 106061da546Spatrick 107061da546Spatrick extern "C" void * 108061da546Spatrick LLDBSwigPythonCreateCommandObject(const char *python_class_name, 109061da546Spatrick const char *session_dictionary_name, 110061da546Spatrick const lldb::DebuggerSP debugger_sp); 111061da546Spatrick 112061da546Spatrick extern "C" void *LLDBSwigPythonCreateScriptedThreadPlan( 113061da546Spatrick const char *python_class_name, const char *session_dictionary_name, 114061da546Spatrick StructuredDataImpl *args_data, 115061da546Spatrick std::string &error_string, 116061da546Spatrick const lldb::ThreadPlanSP &thread_plan_sp); 117061da546Spatrick 118061da546Spatrick extern "C" bool LLDBSWIGPythonCallThreadPlan(void *implementor, 119061da546Spatrick const char *method_name, 120061da546Spatrick Event *event_sp, bool &got_error); 121061da546Spatrick 122061da546Spatrick extern "C" void *LLDBSwigPythonCreateScriptedBreakpointResolver( 123061da546Spatrick const char *python_class_name, const char *session_dictionary_name, 124061da546Spatrick lldb_private::StructuredDataImpl *args, lldb::BreakpointSP &bkpt_sp); 125061da546Spatrick 126061da546Spatrick extern "C" unsigned int 127061da546Spatrick LLDBSwigPythonCallBreakpointResolver(void *implementor, const char *method_name, 128061da546Spatrick lldb_private::SymbolContext *sym_ctx); 129061da546Spatrick 130061da546Spatrick extern "C" size_t LLDBSwigPython_CalculateNumChildren(void *implementor, 131061da546Spatrick uint32_t max); 132061da546Spatrick 133061da546Spatrick extern "C" void *LLDBSwigPython_GetChildAtIndex(void *implementor, 134061da546Spatrick uint32_t idx); 135061da546Spatrick 136061da546Spatrick extern "C" int LLDBSwigPython_GetIndexOfChildWithName(void *implementor, 137061da546Spatrick const char *child_name); 138061da546Spatrick 139061da546Spatrick extern "C" void *LLDBSWIGPython_CastPyObjectToSBValue(void *data); 140061da546Spatrick 141061da546Spatrick extern lldb::ValueObjectSP 142061da546Spatrick LLDBSWIGPython_GetValueObjectSPFromSBValue(void *data); 143061da546Spatrick 144061da546Spatrick extern "C" bool LLDBSwigPython_UpdateSynthProviderInstance(void *implementor); 145061da546Spatrick 146061da546Spatrick extern "C" bool 147061da546Spatrick LLDBSwigPython_MightHaveChildrenSynthProviderInstance(void *implementor); 148061da546Spatrick 149061da546Spatrick extern "C" void * 150061da546Spatrick LLDBSwigPython_GetValueSynthProviderInstance(void *implementor); 151061da546Spatrick 152061da546Spatrick extern "C" bool 153061da546Spatrick LLDBSwigPythonCallCommand(const char *python_function_name, 154061da546Spatrick const char *session_dictionary_name, 155061da546Spatrick lldb::DebuggerSP &debugger, const char *args, 156061da546Spatrick lldb_private::CommandReturnObject &cmd_retobj, 157061da546Spatrick lldb::ExecutionContextRefSP exe_ctx_ref_sp); 158061da546Spatrick 159061da546Spatrick extern "C" bool 160061da546Spatrick LLDBSwigPythonCallCommandObject(void *implementor, lldb::DebuggerSP &debugger, 161061da546Spatrick const char *args, 162061da546Spatrick lldb_private::CommandReturnObject &cmd_retobj, 163061da546Spatrick lldb::ExecutionContextRefSP exe_ctx_ref_sp); 164061da546Spatrick 165061da546Spatrick extern "C" bool 166061da546Spatrick LLDBSwigPythonCallModuleInit(const char *python_module_name, 167061da546Spatrick const char *session_dictionary_name, 168061da546Spatrick lldb::DebuggerSP &debugger); 169061da546Spatrick 170061da546Spatrick extern "C" void * 171061da546Spatrick LLDBSWIGPythonCreateOSPlugin(const char *python_class_name, 172061da546Spatrick const char *session_dictionary_name, 173061da546Spatrick const lldb::ProcessSP &process_sp); 174061da546Spatrick 175061da546Spatrick extern "C" void * 176061da546Spatrick LLDBSWIGPython_CreateFrameRecognizer(const char *python_class_name, 177061da546Spatrick const char *session_dictionary_name); 178061da546Spatrick 179061da546Spatrick extern "C" void * 180061da546Spatrick LLDBSwigPython_GetRecognizedArguments(void *implementor, 181061da546Spatrick const lldb::StackFrameSP &frame_sp); 182061da546Spatrick 183061da546Spatrick extern "C" bool LLDBSWIGPythonRunScriptKeywordProcess( 184061da546Spatrick const char *python_function_name, const char *session_dictionary_name, 185061da546Spatrick lldb::ProcessSP &process, std::string &output); 186061da546Spatrick 187061da546Spatrick extern "C" bool LLDBSWIGPythonRunScriptKeywordThread( 188061da546Spatrick const char *python_function_name, const char *session_dictionary_name, 189061da546Spatrick lldb::ThreadSP &thread, std::string &output); 190061da546Spatrick 191061da546Spatrick extern "C" bool LLDBSWIGPythonRunScriptKeywordTarget( 192061da546Spatrick const char *python_function_name, const char *session_dictionary_name, 193061da546Spatrick lldb::TargetSP &target, std::string &output); 194061da546Spatrick 195061da546Spatrick extern "C" bool LLDBSWIGPythonRunScriptKeywordFrame( 196061da546Spatrick const char *python_function_name, const char *session_dictionary_name, 197061da546Spatrick lldb::StackFrameSP &frame, std::string &output); 198061da546Spatrick 199061da546Spatrick extern "C" bool LLDBSWIGPythonRunScriptKeywordValue( 200061da546Spatrick const char *python_function_name, const char *session_dictionary_name, 201061da546Spatrick lldb::ValueObjectSP &value, std::string &output); 202061da546Spatrick 203061da546Spatrick extern "C" void * 204061da546Spatrick LLDBSWIGPython_GetDynamicSetting(void *module, const char *setting, 205061da546Spatrick const lldb::TargetSP &target_sp); 206061da546Spatrick 207061da546Spatrick static bool g_initialized = false; 208061da546Spatrick 209061da546Spatrick namespace { 210061da546Spatrick 211061da546Spatrick // Initializing Python is not a straightforward process. We cannot control 212061da546Spatrick // what external code may have done before getting to this point in LLDB, 213061da546Spatrick // including potentially having already initialized Python, so we need to do a 214061da546Spatrick // lot of work to ensure that the existing state of the system is maintained 215061da546Spatrick // across our initialization. We do this by using an RAII pattern where we 216061da546Spatrick // save off initial state at the beginning, and restore it at the end 217061da546Spatrick struct InitializePythonRAII { 218061da546Spatrick public: 219061da546Spatrick InitializePythonRAII() 220061da546Spatrick : m_gil_state(PyGILState_UNLOCKED), m_was_already_initialized(false) { 221061da546Spatrick InitializePythonHome(); 222061da546Spatrick 223061da546Spatrick #ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE 224061da546Spatrick // Python's readline is incompatible with libedit being linked into lldb. 225061da546Spatrick // Provide a patched version local to the embedded interpreter. 226061da546Spatrick bool ReadlinePatched = false; 227061da546Spatrick for (auto *p = PyImport_Inittab; p->name != NULL; p++) { 228061da546Spatrick if (strcmp(p->name, "readline") == 0) { 229061da546Spatrick p->initfunc = initlldb_readline; 230061da546Spatrick break; 231061da546Spatrick } 232061da546Spatrick } 233061da546Spatrick if (!ReadlinePatched) { 234061da546Spatrick PyImport_AppendInittab("readline", initlldb_readline); 235061da546Spatrick ReadlinePatched = true; 236061da546Spatrick } 237061da546Spatrick #endif 238061da546Spatrick 239061da546Spatrick // Register _lldb as a built-in module. 240061da546Spatrick PyImport_AppendInittab("_lldb", LLDBSwigPyInit); 241061da546Spatrick 242061da546Spatrick // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for 243061da546Spatrick // calling `Py_Initialize` and `PyEval_InitThreads`. < 3.2 requires that you 244061da546Spatrick // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last. 245061da546Spatrick #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3) 246061da546Spatrick Py_InitializeEx(0); 247061da546Spatrick InitializeThreadsPrivate(); 248061da546Spatrick #else 249061da546Spatrick InitializeThreadsPrivate(); 250061da546Spatrick Py_InitializeEx(0); 251061da546Spatrick #endif 252061da546Spatrick } 253061da546Spatrick 254061da546Spatrick ~InitializePythonRAII() { 255061da546Spatrick if (m_was_already_initialized) { 256061da546Spatrick Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 257061da546Spatrick LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked", 258061da546Spatrick m_gil_state == PyGILState_UNLOCKED ? "un" : ""); 259061da546Spatrick PyGILState_Release(m_gil_state); 260061da546Spatrick } else { 261061da546Spatrick // We initialized the threads in this function, just unlock the GIL. 262061da546Spatrick PyEval_SaveThread(); 263061da546Spatrick } 264061da546Spatrick } 265061da546Spatrick 266061da546Spatrick private: 267061da546Spatrick void InitializePythonHome() { 268*dda28197Spatrick #if LLDB_EMBED_PYTHON_HOME 269*dda28197Spatrick #if PY_MAJOR_VERSION >= 3 270*dda28197Spatrick typedef wchar_t* str_type; 271*dda28197Spatrick #else 272*dda28197Spatrick typedef char* str_type; 273*dda28197Spatrick #endif 274*dda28197Spatrick static str_type g_python_home = []() -> str_type { 275*dda28197Spatrick const char *lldb_python_home = LLDB_PYTHON_HOME; 276*dda28197Spatrick const char *absolute_python_home = nullptr; 277*dda28197Spatrick llvm::SmallString<64> path; 278*dda28197Spatrick if (llvm::sys::path::is_absolute(lldb_python_home)) { 279*dda28197Spatrick absolute_python_home = lldb_python_home; 280*dda28197Spatrick } else { 281*dda28197Spatrick FileSpec spec = HostInfo::GetShlibDir(); 282*dda28197Spatrick if (!spec) 283*dda28197Spatrick return nullptr; 284*dda28197Spatrick spec.GetPath(path); 285*dda28197Spatrick llvm::sys::path::append(path, lldb_python_home); 286*dda28197Spatrick absolute_python_home = path.c_str(); 287*dda28197Spatrick } 288061da546Spatrick #if PY_MAJOR_VERSION >= 3 289061da546Spatrick size_t size = 0; 290*dda28197Spatrick return Py_DecodeLocale(absolute_python_home, &size); 291061da546Spatrick #else 292*dda28197Spatrick return strdup(absolute_python_home); 293061da546Spatrick #endif 294*dda28197Spatrick }(); 295*dda28197Spatrick if (g_python_home != nullptr) { 296061da546Spatrick Py_SetPythonHome(g_python_home); 297*dda28197Spatrick } 298061da546Spatrick #else 299061da546Spatrick #if defined(__APPLE__) && PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION == 7 300061da546Spatrick // For Darwin, the only Python version supported is the one shipped in the 301061da546Spatrick // OS OS and linked with lldb. Other installation of Python may have higher 302061da546Spatrick // priorities in the path, overriding PYTHONHOME and causing 303061da546Spatrick // problems/incompatibilities. In order to avoid confusion, always hardcode 304061da546Spatrick // the PythonHome to be right, as it's not going to change. 305061da546Spatrick static char path[] = 306061da546Spatrick "/System/Library/Frameworks/Python.framework/Versions/2.7"; 307061da546Spatrick Py_SetPythonHome(path); 308061da546Spatrick #endif 309061da546Spatrick #endif 310061da546Spatrick } 311061da546Spatrick 312061da546Spatrick void InitializeThreadsPrivate() { 313061da546Spatrick // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself, 314061da546Spatrick // so there is no way to determine whether the embedded interpreter 315061da546Spatrick // was already initialized by some external code. `PyEval_ThreadsInitialized` 316061da546Spatrick // would always return `true` and `PyGILState_Ensure/Release` flow would be 317061da546Spatrick // executed instead of unlocking GIL with `PyEval_SaveThread`. When 318061da546Spatrick // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock. 319061da546Spatrick #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3) 320061da546Spatrick // The only case we should go further and acquire the GIL: it is unlocked. 321061da546Spatrick if (PyGILState_Check()) 322061da546Spatrick return; 323061da546Spatrick #endif 324061da546Spatrick 325061da546Spatrick if (PyEval_ThreadsInitialized()) { 326061da546Spatrick Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 327061da546Spatrick 328061da546Spatrick m_was_already_initialized = true; 329061da546Spatrick m_gil_state = PyGILState_Ensure(); 330061da546Spatrick LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n", 331061da546Spatrick m_gil_state == PyGILState_UNLOCKED ? "un" : ""); 332061da546Spatrick return; 333061da546Spatrick } 334061da546Spatrick 335061da546Spatrick // InitThreads acquires the GIL if it hasn't been called before. 336061da546Spatrick PyEval_InitThreads(); 337061da546Spatrick } 338061da546Spatrick 339061da546Spatrick TerminalState m_stdin_tty_state; 340061da546Spatrick PyGILState_STATE m_gil_state; 341061da546Spatrick bool m_was_already_initialized; 342061da546Spatrick }; 343061da546Spatrick } // namespace 344061da546Spatrick 345061da546Spatrick void ScriptInterpreterPython::ComputePythonDirForApple( 346061da546Spatrick llvm::SmallVectorImpl<char> &path) { 347061da546Spatrick auto style = llvm::sys::path::Style::posix; 348061da546Spatrick 349061da546Spatrick llvm::StringRef path_ref(path.begin(), path.size()); 350061da546Spatrick auto rbegin = llvm::sys::path::rbegin(path_ref, style); 351061da546Spatrick auto rend = llvm::sys::path::rend(path_ref); 352061da546Spatrick auto framework = std::find(rbegin, rend, "LLDB.framework"); 353061da546Spatrick if (framework == rend) { 354061da546Spatrick ComputePythonDir(path); 355061da546Spatrick return; 356061da546Spatrick } 357061da546Spatrick path.resize(framework - rend); 358061da546Spatrick llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python"); 359061da546Spatrick } 360061da546Spatrick 361061da546Spatrick void ScriptInterpreterPython::ComputePythonDir( 362061da546Spatrick llvm::SmallVectorImpl<char> &path) { 363061da546Spatrick // Build the path by backing out of the lib dir, then building with whatever 364061da546Spatrick // the real python interpreter uses. (e.g. lib for most, lib64 on RHEL 365061da546Spatrick // x86_64, or bin on Windows). 366061da546Spatrick llvm::sys::path::remove_filename(path); 367061da546Spatrick llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR); 368061da546Spatrick 369061da546Spatrick #if defined(_WIN32) 370061da546Spatrick // This will be injected directly through FileSpec.GetDirectory().SetString(), 371061da546Spatrick // so we need to normalize manually. 372061da546Spatrick std::replace(path.begin(), path.end(), '\\', '/'); 373061da546Spatrick #endif 374061da546Spatrick } 375061da546Spatrick 376061da546Spatrick FileSpec ScriptInterpreterPython::GetPythonDir() { 377061da546Spatrick static FileSpec g_spec = []() { 378061da546Spatrick FileSpec spec = HostInfo::GetShlibDir(); 379061da546Spatrick if (!spec) 380061da546Spatrick return FileSpec(); 381061da546Spatrick llvm::SmallString<64> path; 382061da546Spatrick spec.GetPath(path); 383061da546Spatrick 384061da546Spatrick #if defined(__APPLE__) 385061da546Spatrick ComputePythonDirForApple(path); 386061da546Spatrick #else 387061da546Spatrick ComputePythonDir(path); 388061da546Spatrick #endif 389061da546Spatrick spec.GetDirectory().SetString(path); 390061da546Spatrick return spec; 391061da546Spatrick }(); 392061da546Spatrick return g_spec; 393061da546Spatrick } 394061da546Spatrick 395061da546Spatrick lldb_private::ConstString ScriptInterpreterPython::GetPluginNameStatic() { 396061da546Spatrick static ConstString g_name("script-python"); 397061da546Spatrick return g_name; 398061da546Spatrick } 399061da546Spatrick 400061da546Spatrick const char *ScriptInterpreterPython::GetPluginDescriptionStatic() { 401061da546Spatrick return "Embedded Python interpreter"; 402061da546Spatrick } 403061da546Spatrick 404061da546Spatrick void ScriptInterpreterPython::Initialize() { 405061da546Spatrick static llvm::once_flag g_once_flag; 406061da546Spatrick 407061da546Spatrick llvm::call_once(g_once_flag, []() { 408061da546Spatrick PluginManager::RegisterPlugin(GetPluginNameStatic(), 409061da546Spatrick GetPluginDescriptionStatic(), 410061da546Spatrick lldb::eScriptLanguagePython, 411061da546Spatrick ScriptInterpreterPythonImpl::CreateInstance); 412061da546Spatrick }); 413061da546Spatrick } 414061da546Spatrick 415061da546Spatrick void ScriptInterpreterPython::Terminate() {} 416061da546Spatrick 417061da546Spatrick ScriptInterpreterPythonImpl::Locker::Locker( 418061da546Spatrick ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry, 419061da546Spatrick uint16_t on_leave, FileSP in, FileSP out, FileSP err) 420061da546Spatrick : ScriptInterpreterLocker(), 421061da546Spatrick m_teardown_session((on_leave & TearDownSession) == TearDownSession), 422061da546Spatrick m_python_interpreter(py_interpreter) { 423061da546Spatrick DoAcquireLock(); 424061da546Spatrick if ((on_entry & InitSession) == InitSession) { 425061da546Spatrick if (!DoInitSession(on_entry, in, out, err)) { 426061da546Spatrick // Don't teardown the session if we didn't init it. 427061da546Spatrick m_teardown_session = false; 428061da546Spatrick } 429061da546Spatrick } 430061da546Spatrick } 431061da546Spatrick 432061da546Spatrick bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() { 433061da546Spatrick Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 434061da546Spatrick m_GILState = PyGILState_Ensure(); 435061da546Spatrick LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked", 436061da546Spatrick m_GILState == PyGILState_UNLOCKED ? "un" : ""); 437061da546Spatrick 438061da546Spatrick // we need to save the thread state when we first start the command because 439061da546Spatrick // we might decide to interrupt it while some action is taking place outside 440061da546Spatrick // of Python (e.g. printing to screen, waiting for the network, ...) in that 441061da546Spatrick // case, _PyThreadState_Current will be NULL - and we would be unable to set 442061da546Spatrick // the asynchronous exception - not a desirable situation 443061da546Spatrick m_python_interpreter->SetThreadState(PyThreadState_Get()); 444061da546Spatrick m_python_interpreter->IncrementLockCount(); 445061da546Spatrick return true; 446061da546Spatrick } 447061da546Spatrick 448061da546Spatrick bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags, 449061da546Spatrick FileSP in, FileSP out, 450061da546Spatrick FileSP err) { 451061da546Spatrick if (!m_python_interpreter) 452061da546Spatrick return false; 453061da546Spatrick return m_python_interpreter->EnterSession(on_entry_flags, in, out, err); 454061da546Spatrick } 455061da546Spatrick 456061da546Spatrick bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() { 457061da546Spatrick Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 458061da546Spatrick LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked", 459061da546Spatrick m_GILState == PyGILState_UNLOCKED ? "un" : ""); 460061da546Spatrick PyGILState_Release(m_GILState); 461061da546Spatrick m_python_interpreter->DecrementLockCount(); 462061da546Spatrick return true; 463061da546Spatrick } 464061da546Spatrick 465061da546Spatrick bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() { 466061da546Spatrick if (!m_python_interpreter) 467061da546Spatrick return false; 468061da546Spatrick m_python_interpreter->LeaveSession(); 469061da546Spatrick return true; 470061da546Spatrick } 471061da546Spatrick 472061da546Spatrick ScriptInterpreterPythonImpl::Locker::~Locker() { 473061da546Spatrick if (m_teardown_session) 474061da546Spatrick DoTearDownSession(); 475061da546Spatrick DoFreeLock(); 476061da546Spatrick } 477061da546Spatrick 478061da546Spatrick ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger) 479061da546Spatrick : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(), 480061da546Spatrick m_saved_stderr(), m_main_module(), 481061da546Spatrick m_session_dict(PyInitialValue::Invalid), 482061da546Spatrick m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(), 483061da546Spatrick m_run_one_line_str_global(), 484061da546Spatrick m_dictionary_name(m_debugger.GetInstanceName().AsCString()), 485061da546Spatrick m_active_io_handler(eIOHandlerNone), m_session_is_active(false), 486*dda28197Spatrick m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0), 487061da546Spatrick m_command_thread_state(nullptr) { 488061da546Spatrick InitializePrivate(); 489061da546Spatrick 490061da546Spatrick m_dictionary_name.append("_dict"); 491061da546Spatrick StreamString run_string; 492061da546Spatrick run_string.Printf("%s = dict()", m_dictionary_name.c_str()); 493061da546Spatrick 494061da546Spatrick Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock); 495061da546Spatrick PyRun_SimpleString(run_string.GetData()); 496061da546Spatrick 497061da546Spatrick run_string.Clear(); 498061da546Spatrick run_string.Printf( 499061da546Spatrick "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')", 500061da546Spatrick m_dictionary_name.c_str()); 501061da546Spatrick PyRun_SimpleString(run_string.GetData()); 502061da546Spatrick 503061da546Spatrick // Reloading modules requires a different syntax in Python 2 and Python 3. 504061da546Spatrick // This provides a consistent syntax no matter what version of Python. 505061da546Spatrick run_string.Clear(); 506061da546Spatrick run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')", 507061da546Spatrick m_dictionary_name.c_str()); 508061da546Spatrick PyRun_SimpleString(run_string.GetData()); 509061da546Spatrick 510061da546Spatrick // WARNING: temporary code that loads Cocoa formatters - this should be done 511061da546Spatrick // on a per-platform basis rather than loading the whole set and letting the 512061da546Spatrick // individual formatter classes exploit APIs to check whether they can/cannot 513061da546Spatrick // do their task 514061da546Spatrick run_string.Clear(); 515061da546Spatrick run_string.Printf( 516061da546Spatrick "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')", 517061da546Spatrick m_dictionary_name.c_str()); 518061da546Spatrick PyRun_SimpleString(run_string.GetData()); 519061da546Spatrick run_string.Clear(); 520061da546Spatrick 521061da546Spatrick run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from " 522061da546Spatrick "lldb.embedded_interpreter import run_python_interpreter; " 523061da546Spatrick "from lldb.embedded_interpreter import run_one_line')", 524061da546Spatrick m_dictionary_name.c_str()); 525061da546Spatrick PyRun_SimpleString(run_string.GetData()); 526061da546Spatrick run_string.Clear(); 527061da546Spatrick 528061da546Spatrick run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64 529061da546Spatrick "; pydoc.pager = pydoc.plainpager')", 530061da546Spatrick m_dictionary_name.c_str(), m_debugger.GetID()); 531061da546Spatrick PyRun_SimpleString(run_string.GetData()); 532061da546Spatrick } 533061da546Spatrick 534061da546Spatrick ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() { 535061da546Spatrick // the session dictionary may hold objects with complex state which means 536061da546Spatrick // that they may need to be torn down with some level of smarts and that, in 537061da546Spatrick // turn, requires a valid thread state force Python to procure itself such a 538061da546Spatrick // thread state, nuke the session dictionary and then release it for others 539061da546Spatrick // to use and proceed with the rest of the shutdown 540061da546Spatrick auto gil_state = PyGILState_Ensure(); 541061da546Spatrick m_session_dict.Reset(); 542061da546Spatrick PyGILState_Release(gil_state); 543061da546Spatrick } 544061da546Spatrick 545061da546Spatrick lldb_private::ConstString ScriptInterpreterPythonImpl::GetPluginName() { 546061da546Spatrick return GetPluginNameStatic(); 547061da546Spatrick } 548061da546Spatrick 549061da546Spatrick uint32_t ScriptInterpreterPythonImpl::GetPluginVersion() { return 1; } 550061da546Spatrick 551061da546Spatrick void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler, 552061da546Spatrick bool interactive) { 553061da546Spatrick const char *instructions = nullptr; 554061da546Spatrick 555061da546Spatrick switch (m_active_io_handler) { 556061da546Spatrick case eIOHandlerNone: 557061da546Spatrick break; 558061da546Spatrick case eIOHandlerBreakpoint: 559061da546Spatrick instructions = R"(Enter your Python command(s). Type 'DONE' to end. 560061da546Spatrick def function (frame, bp_loc, internal_dict): 561061da546Spatrick """frame: the lldb.SBFrame for the location at which you stopped 562061da546Spatrick bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information 563061da546Spatrick internal_dict: an LLDB support object not to be used""" 564061da546Spatrick )"; 565061da546Spatrick break; 566061da546Spatrick case eIOHandlerWatchpoint: 567061da546Spatrick instructions = "Enter your Python command(s). Type 'DONE' to end.\n"; 568061da546Spatrick break; 569061da546Spatrick } 570061da546Spatrick 571061da546Spatrick if (instructions) { 572061da546Spatrick StreamFileSP output_sp(io_handler.GetOutputStreamFileSP()); 573061da546Spatrick if (output_sp && interactive) { 574061da546Spatrick output_sp->PutCString(instructions); 575061da546Spatrick output_sp->Flush(); 576061da546Spatrick } 577061da546Spatrick } 578061da546Spatrick } 579061da546Spatrick 580061da546Spatrick void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler, 581061da546Spatrick std::string &data) { 582061da546Spatrick io_handler.SetIsDone(true); 583061da546Spatrick bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode(); 584061da546Spatrick 585061da546Spatrick switch (m_active_io_handler) { 586061da546Spatrick case eIOHandlerNone: 587061da546Spatrick break; 588061da546Spatrick case eIOHandlerBreakpoint: { 589061da546Spatrick std::vector<BreakpointOptions *> *bp_options_vec = 590061da546Spatrick (std::vector<BreakpointOptions *> *)io_handler.GetUserData(); 591061da546Spatrick for (auto bp_options : *bp_options_vec) { 592061da546Spatrick if (!bp_options) 593061da546Spatrick continue; 594061da546Spatrick 595061da546Spatrick auto data_up = std::make_unique<CommandDataPython>(); 596061da546Spatrick if (!data_up) 597061da546Spatrick break; 598061da546Spatrick data_up->user_source.SplitIntoLines(data); 599061da546Spatrick 600061da546Spatrick StructuredData::ObjectSP empty_args_sp; 601061da546Spatrick if (GenerateBreakpointCommandCallbackData(data_up->user_source, 602061da546Spatrick data_up->script_source, 603061da546Spatrick false) 604061da546Spatrick .Success()) { 605061da546Spatrick auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>( 606061da546Spatrick std::move(data_up)); 607061da546Spatrick bp_options->SetCallback( 608061da546Spatrick ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); 609061da546Spatrick } else if (!batch_mode) { 610061da546Spatrick StreamFileSP error_sp = io_handler.GetErrorStreamFileSP(); 611061da546Spatrick if (error_sp) { 612061da546Spatrick error_sp->Printf("Warning: No command attached to breakpoint.\n"); 613061da546Spatrick error_sp->Flush(); 614061da546Spatrick } 615061da546Spatrick } 616061da546Spatrick } 617061da546Spatrick m_active_io_handler = eIOHandlerNone; 618061da546Spatrick } break; 619061da546Spatrick case eIOHandlerWatchpoint: { 620061da546Spatrick WatchpointOptions *wp_options = 621061da546Spatrick (WatchpointOptions *)io_handler.GetUserData(); 622061da546Spatrick auto data_up = std::make_unique<WatchpointOptions::CommandData>(); 623061da546Spatrick data_up->user_source.SplitIntoLines(data); 624061da546Spatrick 625061da546Spatrick if (GenerateWatchpointCommandCallbackData(data_up->user_source, 626061da546Spatrick data_up->script_source)) { 627061da546Spatrick auto baton_sp = 628061da546Spatrick std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up)); 629061da546Spatrick wp_options->SetCallback( 630061da546Spatrick ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp); 631061da546Spatrick } else if (!batch_mode) { 632061da546Spatrick StreamFileSP error_sp = io_handler.GetErrorStreamFileSP(); 633061da546Spatrick if (error_sp) { 634061da546Spatrick error_sp->Printf("Warning: No command attached to breakpoint.\n"); 635061da546Spatrick error_sp->Flush(); 636061da546Spatrick } 637061da546Spatrick } 638061da546Spatrick m_active_io_handler = eIOHandlerNone; 639061da546Spatrick } break; 640061da546Spatrick } 641061da546Spatrick } 642061da546Spatrick 643061da546Spatrick lldb::ScriptInterpreterSP 644061da546Spatrick ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) { 645061da546Spatrick return std::make_shared<ScriptInterpreterPythonImpl>(debugger); 646061da546Spatrick } 647061da546Spatrick 648061da546Spatrick void ScriptInterpreterPythonImpl::LeaveSession() { 649061da546Spatrick Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 650061da546Spatrick if (log) 651061da546Spatrick log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()"); 652061da546Spatrick 653061da546Spatrick // Unset the LLDB global variables. 654061da546Spatrick PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process " 655061da546Spatrick "= None; lldb.thread = None; lldb.frame = None"); 656061da546Spatrick 657061da546Spatrick // checking that we have a valid thread state - since we use our own 658061da546Spatrick // threading and locking in some (rare) cases during cleanup Python may end 659061da546Spatrick // up believing we have no thread state and PyImport_AddModule will crash if 660061da546Spatrick // that is the case - since that seems to only happen when destroying the 661061da546Spatrick // SBDebugger, we can make do without clearing up stdout and stderr 662061da546Spatrick 663061da546Spatrick // rdar://problem/11292882 664061da546Spatrick // When the current thread state is NULL, PyThreadState_Get() issues a fatal 665061da546Spatrick // error. 666061da546Spatrick if (PyThreadState_GetDict()) { 667061da546Spatrick PythonDictionary &sys_module_dict = GetSysModuleDictionary(); 668061da546Spatrick if (sys_module_dict.IsValid()) { 669061da546Spatrick if (m_saved_stdin.IsValid()) { 670061da546Spatrick sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin); 671061da546Spatrick m_saved_stdin.Reset(); 672061da546Spatrick } 673061da546Spatrick if (m_saved_stdout.IsValid()) { 674061da546Spatrick sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout); 675061da546Spatrick m_saved_stdout.Reset(); 676061da546Spatrick } 677061da546Spatrick if (m_saved_stderr.IsValid()) { 678061da546Spatrick sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr); 679061da546Spatrick m_saved_stderr.Reset(); 680061da546Spatrick } 681061da546Spatrick } 682061da546Spatrick } 683061da546Spatrick 684061da546Spatrick m_session_is_active = false; 685061da546Spatrick } 686061da546Spatrick 687061da546Spatrick bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp, 688061da546Spatrick const char *py_name, 689061da546Spatrick PythonObject &save_file, 690061da546Spatrick const char *mode) { 691061da546Spatrick if (!file_sp || !*file_sp) { 692061da546Spatrick save_file.Reset(); 693061da546Spatrick return false; 694061da546Spatrick } 695061da546Spatrick File &file = *file_sp; 696061da546Spatrick 697061da546Spatrick // Flush the file before giving it to python to avoid interleaved output. 698061da546Spatrick file.Flush(); 699061da546Spatrick 700061da546Spatrick PythonDictionary &sys_module_dict = GetSysModuleDictionary(); 701061da546Spatrick 702061da546Spatrick auto new_file = PythonFile::FromFile(file, mode); 703061da546Spatrick if (!new_file) { 704061da546Spatrick llvm::consumeError(new_file.takeError()); 705061da546Spatrick return false; 706061da546Spatrick } 707061da546Spatrick 708061da546Spatrick save_file = sys_module_dict.GetItemForKey(PythonString(py_name)); 709061da546Spatrick 710061da546Spatrick sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get()); 711061da546Spatrick return true; 712061da546Spatrick } 713061da546Spatrick 714061da546Spatrick bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags, 715061da546Spatrick FileSP in_sp, FileSP out_sp, 716061da546Spatrick FileSP err_sp) { 717061da546Spatrick // If we have already entered the session, without having officially 'left' 718061da546Spatrick // it, then there is no need to 'enter' it again. 719061da546Spatrick Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 720061da546Spatrick if (m_session_is_active) { 721061da546Spatrick LLDB_LOGF( 722061da546Spatrick log, 723061da546Spatrick "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 724061da546Spatrick ") session is already active, returning without doing anything", 725061da546Spatrick on_entry_flags); 726061da546Spatrick return false; 727061da546Spatrick } 728061da546Spatrick 729061da546Spatrick LLDB_LOGF( 730061da546Spatrick log, 731061da546Spatrick "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")", 732061da546Spatrick on_entry_flags); 733061da546Spatrick 734061da546Spatrick m_session_is_active = true; 735061da546Spatrick 736061da546Spatrick StreamString run_string; 737061da546Spatrick 738061da546Spatrick if (on_entry_flags & Locker::InitGlobals) { 739061da546Spatrick run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, 740061da546Spatrick m_dictionary_name.c_str(), m_debugger.GetID()); 741061da546Spatrick run_string.Printf( 742061da546Spatrick "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", 743061da546Spatrick m_debugger.GetID()); 744061da546Spatrick run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()"); 745061da546Spatrick run_string.PutCString("; lldb.process = lldb.target.GetProcess()"); 746061da546Spatrick run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()"); 747061da546Spatrick run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()"); 748061da546Spatrick run_string.PutCString("')"); 749061da546Spatrick } else { 750061da546Spatrick // If we aren't initing the globals, we should still always set the 751061da546Spatrick // debugger (since that is always unique.) 752061da546Spatrick run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, 753061da546Spatrick m_dictionary_name.c_str(), m_debugger.GetID()); 754061da546Spatrick run_string.Printf( 755061da546Spatrick "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", 756061da546Spatrick m_debugger.GetID()); 757061da546Spatrick run_string.PutCString("')"); 758061da546Spatrick } 759061da546Spatrick 760061da546Spatrick PyRun_SimpleString(run_string.GetData()); 761061da546Spatrick run_string.Clear(); 762061da546Spatrick 763061da546Spatrick PythonDictionary &sys_module_dict = GetSysModuleDictionary(); 764061da546Spatrick if (sys_module_dict.IsValid()) { 765061da546Spatrick lldb::FileSP top_in_sp; 766061da546Spatrick lldb::StreamFileSP top_out_sp, top_err_sp; 767061da546Spatrick if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp) 768061da546Spatrick m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp, 769061da546Spatrick top_err_sp); 770061da546Spatrick 771061da546Spatrick if (on_entry_flags & Locker::NoSTDIN) { 772061da546Spatrick m_saved_stdin.Reset(); 773061da546Spatrick } else { 774061da546Spatrick if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) { 775061da546Spatrick if (top_in_sp) 776061da546Spatrick SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r"); 777061da546Spatrick } 778061da546Spatrick } 779061da546Spatrick 780061da546Spatrick if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) { 781061da546Spatrick if (top_out_sp) 782061da546Spatrick SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w"); 783061da546Spatrick } 784061da546Spatrick 785061da546Spatrick if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) { 786061da546Spatrick if (top_err_sp) 787061da546Spatrick SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w"); 788061da546Spatrick } 789061da546Spatrick } 790061da546Spatrick 791061da546Spatrick if (PyErr_Occurred()) 792061da546Spatrick PyErr_Clear(); 793061da546Spatrick 794061da546Spatrick return true; 795061da546Spatrick } 796061da546Spatrick 797061da546Spatrick PythonModule &ScriptInterpreterPythonImpl::GetMainModule() { 798061da546Spatrick if (!m_main_module.IsValid()) 799061da546Spatrick m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__")); 800061da546Spatrick return m_main_module; 801061da546Spatrick } 802061da546Spatrick 803061da546Spatrick PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() { 804061da546Spatrick if (m_session_dict.IsValid()) 805061da546Spatrick return m_session_dict; 806061da546Spatrick 807061da546Spatrick PythonObject &main_module = GetMainModule(); 808061da546Spatrick if (!main_module.IsValid()) 809061da546Spatrick return m_session_dict; 810061da546Spatrick 811061da546Spatrick PythonDictionary main_dict(PyRefType::Borrowed, 812061da546Spatrick PyModule_GetDict(main_module.get())); 813061da546Spatrick if (!main_dict.IsValid()) 814061da546Spatrick return m_session_dict; 815061da546Spatrick 816061da546Spatrick m_session_dict = unwrapIgnoringErrors( 817061da546Spatrick As<PythonDictionary>(main_dict.GetItem(m_dictionary_name))); 818061da546Spatrick return m_session_dict; 819061da546Spatrick } 820061da546Spatrick 821061da546Spatrick PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() { 822061da546Spatrick if (m_sys_module_dict.IsValid()) 823061da546Spatrick return m_sys_module_dict; 824061da546Spatrick PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys")); 825061da546Spatrick m_sys_module_dict = sys_module.GetDictionary(); 826061da546Spatrick return m_sys_module_dict; 827061da546Spatrick } 828061da546Spatrick 829061da546Spatrick llvm::Expected<unsigned> 830061da546Spatrick ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable( 831061da546Spatrick const llvm::StringRef &callable_name) { 832061da546Spatrick if (callable_name.empty()) { 833061da546Spatrick return llvm::createStringError( 834061da546Spatrick llvm::inconvertibleErrorCode(), 835061da546Spatrick "called with empty callable name."); 836061da546Spatrick } 837061da546Spatrick Locker py_lock(this, Locker::AcquireLock | 838061da546Spatrick Locker::InitSession | 839061da546Spatrick Locker::NoSTDIN); 840061da546Spatrick auto dict = PythonModule::MainModule() 841061da546Spatrick .ResolveName<PythonDictionary>(m_dictionary_name); 842061da546Spatrick auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>( 843061da546Spatrick callable_name, dict); 844061da546Spatrick if (!pfunc.IsAllocated()) { 845061da546Spatrick return llvm::createStringError( 846061da546Spatrick llvm::inconvertibleErrorCode(), 847061da546Spatrick "can't find callable: %s", callable_name.str().c_str()); 848061da546Spatrick } 849061da546Spatrick llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo(); 850061da546Spatrick if (!arg_info) 851061da546Spatrick return arg_info.takeError(); 852061da546Spatrick return arg_info.get().max_positional_args; 853061da546Spatrick } 854061da546Spatrick 855061da546Spatrick static std::string GenerateUniqueName(const char *base_name_wanted, 856061da546Spatrick uint32_t &functions_counter, 857061da546Spatrick const void *name_token = nullptr) { 858061da546Spatrick StreamString sstr; 859061da546Spatrick 860061da546Spatrick if (!base_name_wanted) 861061da546Spatrick return std::string(); 862061da546Spatrick 863061da546Spatrick if (!name_token) 864061da546Spatrick sstr.Printf("%s_%d", base_name_wanted, functions_counter++); 865061da546Spatrick else 866061da546Spatrick sstr.Printf("%s_%p", base_name_wanted, name_token); 867061da546Spatrick 868*dda28197Spatrick return std::string(sstr.GetString()); 869061da546Spatrick } 870061da546Spatrick 871061da546Spatrick bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() { 872061da546Spatrick if (m_run_one_line_function.IsValid()) 873061da546Spatrick return true; 874061da546Spatrick 875061da546Spatrick PythonObject module(PyRefType::Borrowed, 876061da546Spatrick PyImport_AddModule("lldb.embedded_interpreter")); 877061da546Spatrick if (!module.IsValid()) 878061da546Spatrick return false; 879061da546Spatrick 880061da546Spatrick PythonDictionary module_dict(PyRefType::Borrowed, 881061da546Spatrick PyModule_GetDict(module.get())); 882061da546Spatrick if (!module_dict.IsValid()) 883061da546Spatrick return false; 884061da546Spatrick 885061da546Spatrick m_run_one_line_function = 886061da546Spatrick module_dict.GetItemForKey(PythonString("run_one_line")); 887061da546Spatrick m_run_one_line_str_global = 888061da546Spatrick module_dict.GetItemForKey(PythonString("g_run_one_line_str")); 889061da546Spatrick return m_run_one_line_function.IsValid(); 890061da546Spatrick } 891061da546Spatrick 892061da546Spatrick bool ScriptInterpreterPythonImpl::ExecuteOneLine( 893061da546Spatrick llvm::StringRef command, CommandReturnObject *result, 894061da546Spatrick const ExecuteScriptOptions &options) { 895061da546Spatrick std::string command_str = command.str(); 896061da546Spatrick 897061da546Spatrick if (!m_valid_session) 898061da546Spatrick return false; 899061da546Spatrick 900061da546Spatrick if (!command.empty()) { 901061da546Spatrick // We want to call run_one_line, passing in the dictionary and the command 902061da546Spatrick // string. We cannot do this through PyRun_SimpleString here because the 903061da546Spatrick // command string may contain escaped characters, and putting it inside 904061da546Spatrick // another string to pass to PyRun_SimpleString messes up the escaping. So 905061da546Spatrick // we use the following more complicated method to pass the command string 906061da546Spatrick // directly down to Python. 907*dda28197Spatrick llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>> 908*dda28197Spatrick io_redirect_or_error = ScriptInterpreterIORedirect::Create( 909*dda28197Spatrick options.GetEnableIO(), m_debugger, result); 910*dda28197Spatrick if (!io_redirect_or_error) { 911*dda28197Spatrick if (result) 912*dda28197Spatrick result->AppendErrorWithFormatv( 913*dda28197Spatrick "failed to redirect I/O: {0}\n", 914*dda28197Spatrick llvm::fmt_consume(io_redirect_or_error.takeError())); 915*dda28197Spatrick else 916*dda28197Spatrick llvm::consumeError(io_redirect_or_error.takeError()); 917061da546Spatrick return false; 918061da546Spatrick } 919*dda28197Spatrick 920*dda28197Spatrick ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error; 921061da546Spatrick 922061da546Spatrick bool success = false; 923061da546Spatrick { 924061da546Spatrick // WARNING! It's imperative that this RAII scope be as tight as 925061da546Spatrick // possible. In particular, the scope must end *before* we try to join 926061da546Spatrick // the read thread. The reason for this is that a pre-requisite for 927061da546Spatrick // joining the read thread is that we close the write handle (to break 928061da546Spatrick // the pipe and cause it to wake up and exit). But acquiring the GIL as 929061da546Spatrick // below will redirect Python's stdio to use this same handle. If we 930061da546Spatrick // close the handle while Python is still using it, bad things will 931061da546Spatrick // happen. 932061da546Spatrick Locker locker( 933061da546Spatrick this, 934061da546Spatrick Locker::AcquireLock | Locker::InitSession | 935061da546Spatrick (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) | 936061da546Spatrick ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN), 937*dda28197Spatrick Locker::FreeAcquiredLock | Locker::TearDownSession, 938*dda28197Spatrick io_redirect.GetInputFile(), io_redirect.GetOutputFile(), 939*dda28197Spatrick io_redirect.GetErrorFile()); 940061da546Spatrick 941061da546Spatrick // Find the correct script interpreter dictionary in the main module. 942061da546Spatrick PythonDictionary &session_dict = GetSessionDictionary(); 943061da546Spatrick if (session_dict.IsValid()) { 944061da546Spatrick if (GetEmbeddedInterpreterModuleObjects()) { 945061da546Spatrick if (PyCallable_Check(m_run_one_line_function.get())) { 946061da546Spatrick PythonObject pargs( 947061da546Spatrick PyRefType::Owned, 948061da546Spatrick Py_BuildValue("(Os)", session_dict.get(), command_str.c_str())); 949061da546Spatrick if (pargs.IsValid()) { 950061da546Spatrick PythonObject return_value( 951061da546Spatrick PyRefType::Owned, 952061da546Spatrick PyObject_CallObject(m_run_one_line_function.get(), 953061da546Spatrick pargs.get())); 954061da546Spatrick if (return_value.IsValid()) 955061da546Spatrick success = true; 956061da546Spatrick else if (options.GetMaskoutErrors() && PyErr_Occurred()) { 957061da546Spatrick PyErr_Print(); 958061da546Spatrick PyErr_Clear(); 959061da546Spatrick } 960061da546Spatrick } 961061da546Spatrick } 962061da546Spatrick } 963061da546Spatrick } 964061da546Spatrick 965*dda28197Spatrick io_redirect.Flush(); 966061da546Spatrick } 967061da546Spatrick 968061da546Spatrick if (success) 969061da546Spatrick return true; 970061da546Spatrick 971061da546Spatrick // The one-liner failed. Append the error message. 972061da546Spatrick if (result) { 973061da546Spatrick result->AppendErrorWithFormat( 974061da546Spatrick "python failed attempting to evaluate '%s'\n", command_str.c_str()); 975061da546Spatrick } 976061da546Spatrick return false; 977061da546Spatrick } 978061da546Spatrick 979061da546Spatrick if (result) 980061da546Spatrick result->AppendError("empty command passed to python\n"); 981061da546Spatrick return false; 982061da546Spatrick } 983061da546Spatrick 984061da546Spatrick void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() { 985061da546Spatrick static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 986061da546Spatrick Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); 987061da546Spatrick 988061da546Spatrick Debugger &debugger = m_debugger; 989061da546Spatrick 990061da546Spatrick // At the moment, the only time the debugger does not have an input file 991061da546Spatrick // handle is when this is called directly from Python, in which case it is 992061da546Spatrick // both dangerous and unnecessary (not to mention confusing) to try to embed 993061da546Spatrick // a running interpreter loop inside the already running Python interpreter 994061da546Spatrick // loop, so we won't do it. 995061da546Spatrick 996061da546Spatrick if (!debugger.GetInputFile().IsValid()) 997061da546Spatrick return; 998061da546Spatrick 999061da546Spatrick IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this)); 1000061da546Spatrick if (io_handler_sp) { 1001*dda28197Spatrick debugger.RunIOHandlerAsync(io_handler_sp); 1002061da546Spatrick } 1003061da546Spatrick } 1004061da546Spatrick 1005061da546Spatrick bool ScriptInterpreterPythonImpl::Interrupt() { 1006061da546Spatrick Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT)); 1007061da546Spatrick 1008061da546Spatrick if (IsExecutingPython()) { 1009061da546Spatrick PyThreadState *state = PyThreadState_GET(); 1010061da546Spatrick if (!state) 1011061da546Spatrick state = GetThreadState(); 1012061da546Spatrick if (state) { 1013061da546Spatrick long tid = state->thread_id; 1014061da546Spatrick PyThreadState_Swap(state); 1015061da546Spatrick int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt); 1016061da546Spatrick LLDB_LOGF(log, 1017061da546Spatrick "ScriptInterpreterPythonImpl::Interrupt() sending " 1018061da546Spatrick "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...", 1019061da546Spatrick tid, num_threads); 1020061da546Spatrick return true; 1021061da546Spatrick } 1022061da546Spatrick } 1023061da546Spatrick LLDB_LOGF(log, 1024061da546Spatrick "ScriptInterpreterPythonImpl::Interrupt() python code not running, " 1025061da546Spatrick "can't interrupt"); 1026061da546Spatrick return false; 1027061da546Spatrick } 1028061da546Spatrick 1029061da546Spatrick bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn( 1030061da546Spatrick llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type, 1031061da546Spatrick void *ret_value, const ExecuteScriptOptions &options) { 1032061da546Spatrick 1033061da546Spatrick Locker locker(this, 1034061da546Spatrick Locker::AcquireLock | Locker::InitSession | 1035061da546Spatrick (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) | 1036061da546Spatrick Locker::NoSTDIN, 1037061da546Spatrick Locker::FreeAcquiredLock | Locker::TearDownSession); 1038061da546Spatrick 1039061da546Spatrick PythonModule &main_module = GetMainModule(); 1040061da546Spatrick PythonDictionary globals = main_module.GetDictionary(); 1041061da546Spatrick 1042061da546Spatrick PythonDictionary locals = GetSessionDictionary(); 1043061da546Spatrick if (!locals.IsValid()) 1044061da546Spatrick locals = unwrapIgnoringErrors( 1045061da546Spatrick As<PythonDictionary>(globals.GetAttribute(m_dictionary_name))); 1046061da546Spatrick if (!locals.IsValid()) 1047061da546Spatrick locals = globals; 1048061da546Spatrick 1049061da546Spatrick Expected<PythonObject> maybe_py_return = 1050061da546Spatrick runStringOneLine(in_string, globals, locals); 1051061da546Spatrick 1052061da546Spatrick if (!maybe_py_return) { 1053061da546Spatrick llvm::handleAllErrors( 1054061da546Spatrick maybe_py_return.takeError(), 1055061da546Spatrick [&](PythonException &E) { 1056061da546Spatrick E.Restore(); 1057061da546Spatrick if (options.GetMaskoutErrors()) { 1058061da546Spatrick if (E.Matches(PyExc_SyntaxError)) { 1059061da546Spatrick PyErr_Print(); 1060061da546Spatrick } 1061061da546Spatrick PyErr_Clear(); 1062061da546Spatrick } 1063061da546Spatrick }, 1064061da546Spatrick [](const llvm::ErrorInfoBase &E) {}); 1065061da546Spatrick return false; 1066061da546Spatrick } 1067061da546Spatrick 1068061da546Spatrick PythonObject py_return = std::move(maybe_py_return.get()); 1069061da546Spatrick assert(py_return.IsValid()); 1070061da546Spatrick 1071061da546Spatrick switch (return_type) { 1072061da546Spatrick case eScriptReturnTypeCharPtr: // "char *" 1073061da546Spatrick { 1074061da546Spatrick const char format[3] = "s#"; 1075061da546Spatrick return PyArg_Parse(py_return.get(), format, (char **)ret_value); 1076061da546Spatrick } 1077061da546Spatrick case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == 1078061da546Spatrick // Py_None 1079061da546Spatrick { 1080061da546Spatrick const char format[3] = "z"; 1081061da546Spatrick return PyArg_Parse(py_return.get(), format, (char **)ret_value); 1082061da546Spatrick } 1083061da546Spatrick case eScriptReturnTypeBool: { 1084061da546Spatrick const char format[2] = "b"; 1085061da546Spatrick return PyArg_Parse(py_return.get(), format, (bool *)ret_value); 1086061da546Spatrick } 1087061da546Spatrick case eScriptReturnTypeShortInt: { 1088061da546Spatrick const char format[2] = "h"; 1089061da546Spatrick return PyArg_Parse(py_return.get(), format, (short *)ret_value); 1090061da546Spatrick } 1091061da546Spatrick case eScriptReturnTypeShortIntUnsigned: { 1092061da546Spatrick const char format[2] = "H"; 1093061da546Spatrick return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value); 1094061da546Spatrick } 1095061da546Spatrick case eScriptReturnTypeInt: { 1096061da546Spatrick const char format[2] = "i"; 1097061da546Spatrick return PyArg_Parse(py_return.get(), format, (int *)ret_value); 1098061da546Spatrick } 1099061da546Spatrick case eScriptReturnTypeIntUnsigned: { 1100061da546Spatrick const char format[2] = "I"; 1101061da546Spatrick return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value); 1102061da546Spatrick } 1103061da546Spatrick case eScriptReturnTypeLongInt: { 1104061da546Spatrick const char format[2] = "l"; 1105061da546Spatrick return PyArg_Parse(py_return.get(), format, (long *)ret_value); 1106061da546Spatrick } 1107061da546Spatrick case eScriptReturnTypeLongIntUnsigned: { 1108061da546Spatrick const char format[2] = "k"; 1109061da546Spatrick return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value); 1110061da546Spatrick } 1111061da546Spatrick case eScriptReturnTypeLongLong: { 1112061da546Spatrick const char format[2] = "L"; 1113061da546Spatrick return PyArg_Parse(py_return.get(), format, (long long *)ret_value); 1114061da546Spatrick } 1115061da546Spatrick case eScriptReturnTypeLongLongUnsigned: { 1116061da546Spatrick const char format[2] = "K"; 1117061da546Spatrick return PyArg_Parse(py_return.get(), format, 1118061da546Spatrick (unsigned long long *)ret_value); 1119061da546Spatrick } 1120061da546Spatrick case eScriptReturnTypeFloat: { 1121061da546Spatrick const char format[2] = "f"; 1122061da546Spatrick return PyArg_Parse(py_return.get(), format, (float *)ret_value); 1123061da546Spatrick } 1124061da546Spatrick case eScriptReturnTypeDouble: { 1125061da546Spatrick const char format[2] = "d"; 1126061da546Spatrick return PyArg_Parse(py_return.get(), format, (double *)ret_value); 1127061da546Spatrick } 1128061da546Spatrick case eScriptReturnTypeChar: { 1129061da546Spatrick const char format[2] = "c"; 1130061da546Spatrick return PyArg_Parse(py_return.get(), format, (char *)ret_value); 1131061da546Spatrick } 1132061da546Spatrick case eScriptReturnTypeOpaqueObject: { 1133061da546Spatrick *((PyObject **)ret_value) = py_return.release(); 1134061da546Spatrick return true; 1135061da546Spatrick } 1136061da546Spatrick } 1137061da546Spatrick llvm_unreachable("Fully covered switch!"); 1138061da546Spatrick } 1139061da546Spatrick 1140061da546Spatrick Status ScriptInterpreterPythonImpl::ExecuteMultipleLines( 1141061da546Spatrick const char *in_string, const ExecuteScriptOptions &options) { 1142061da546Spatrick 1143061da546Spatrick if (in_string == nullptr) 1144061da546Spatrick return Status(); 1145061da546Spatrick 1146061da546Spatrick Locker locker(this, 1147061da546Spatrick Locker::AcquireLock | Locker::InitSession | 1148061da546Spatrick (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) | 1149061da546Spatrick Locker::NoSTDIN, 1150061da546Spatrick Locker::FreeAcquiredLock | Locker::TearDownSession); 1151061da546Spatrick 1152061da546Spatrick PythonModule &main_module = GetMainModule(); 1153061da546Spatrick PythonDictionary globals = main_module.GetDictionary(); 1154061da546Spatrick 1155061da546Spatrick PythonDictionary locals = GetSessionDictionary(); 1156061da546Spatrick if (!locals.IsValid()) 1157061da546Spatrick locals = unwrapIgnoringErrors( 1158061da546Spatrick As<PythonDictionary>(globals.GetAttribute(m_dictionary_name))); 1159061da546Spatrick if (!locals.IsValid()) 1160061da546Spatrick locals = globals; 1161061da546Spatrick 1162061da546Spatrick Expected<PythonObject> return_value = 1163061da546Spatrick runStringMultiLine(in_string, globals, locals); 1164061da546Spatrick 1165061da546Spatrick if (!return_value) { 1166061da546Spatrick llvm::Error error = 1167061da546Spatrick llvm::handleErrors(return_value.takeError(), [&](PythonException &E) { 1168061da546Spatrick llvm::Error error = llvm::createStringError( 1169061da546Spatrick llvm::inconvertibleErrorCode(), E.ReadBacktrace()); 1170061da546Spatrick if (!options.GetMaskoutErrors()) 1171061da546Spatrick E.Restore(); 1172061da546Spatrick return error; 1173061da546Spatrick }); 1174061da546Spatrick return Status(std::move(error)); 1175061da546Spatrick } 1176061da546Spatrick 1177061da546Spatrick return Status(); 1178061da546Spatrick } 1179061da546Spatrick 1180061da546Spatrick void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback( 1181061da546Spatrick std::vector<BreakpointOptions *> &bp_options_vec, 1182061da546Spatrick CommandReturnObject &result) { 1183061da546Spatrick m_active_io_handler = eIOHandlerBreakpoint; 1184061da546Spatrick m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler( 1185061da546Spatrick " ", *this, &bp_options_vec); 1186061da546Spatrick } 1187061da546Spatrick 1188061da546Spatrick void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback( 1189061da546Spatrick WatchpointOptions *wp_options, CommandReturnObject &result) { 1190061da546Spatrick m_active_io_handler = eIOHandlerWatchpoint; 1191061da546Spatrick m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler( 1192061da546Spatrick " ", *this, wp_options); 1193061da546Spatrick } 1194061da546Spatrick 1195061da546Spatrick Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction( 1196061da546Spatrick BreakpointOptions *bp_options, const char *function_name, 1197061da546Spatrick StructuredData::ObjectSP extra_args_sp) { 1198061da546Spatrick Status error; 1199061da546Spatrick // For now just cons up a oneliner that calls the provided function. 1200061da546Spatrick std::string oneliner("return "); 1201061da546Spatrick oneliner += function_name; 1202061da546Spatrick 1203061da546Spatrick llvm::Expected<unsigned> maybe_args = 1204061da546Spatrick GetMaxPositionalArgumentsForCallable(function_name); 1205061da546Spatrick if (!maybe_args) { 1206061da546Spatrick error.SetErrorStringWithFormat( 1207061da546Spatrick "could not get num args: %s", 1208061da546Spatrick llvm::toString(maybe_args.takeError()).c_str()); 1209061da546Spatrick return error; 1210061da546Spatrick } 1211061da546Spatrick size_t max_args = *maybe_args; 1212061da546Spatrick 1213061da546Spatrick bool uses_extra_args = false; 1214061da546Spatrick if (max_args >= 4) { 1215061da546Spatrick uses_extra_args = true; 1216061da546Spatrick oneliner += "(frame, bp_loc, extra_args, internal_dict)"; 1217061da546Spatrick } else if (max_args >= 3) { 1218061da546Spatrick if (extra_args_sp) { 1219061da546Spatrick error.SetErrorString("cannot pass extra_args to a three argument callback" 1220061da546Spatrick ); 1221061da546Spatrick return error; 1222061da546Spatrick } 1223061da546Spatrick uses_extra_args = false; 1224061da546Spatrick oneliner += "(frame, bp_loc, internal_dict)"; 1225061da546Spatrick } else { 1226061da546Spatrick error.SetErrorStringWithFormat("expected 3 or 4 argument " 1227061da546Spatrick "function, %s can only take %zu", 1228061da546Spatrick function_name, max_args); 1229061da546Spatrick return error; 1230061da546Spatrick } 1231061da546Spatrick 1232061da546Spatrick SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp, 1233061da546Spatrick uses_extra_args); 1234061da546Spatrick return error; 1235061da546Spatrick } 1236061da546Spatrick 1237061da546Spatrick Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( 1238061da546Spatrick BreakpointOptions *bp_options, 1239061da546Spatrick std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) { 1240061da546Spatrick Status error; 1241061da546Spatrick error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source, 1242061da546Spatrick cmd_data_up->script_source, 1243061da546Spatrick false); 1244061da546Spatrick if (error.Fail()) { 1245061da546Spatrick return error; 1246061da546Spatrick } 1247061da546Spatrick auto baton_sp = 1248061da546Spatrick std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up)); 1249061da546Spatrick bp_options->SetCallback( 1250061da546Spatrick ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); 1251061da546Spatrick return error; 1252061da546Spatrick } 1253061da546Spatrick 1254061da546Spatrick Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( 1255061da546Spatrick BreakpointOptions *bp_options, const char *command_body_text) { 1256061da546Spatrick return SetBreakpointCommandCallback(bp_options, command_body_text, {},false); 1257061da546Spatrick } 1258061da546Spatrick 1259061da546Spatrick // Set a Python one-liner as the callback for the breakpoint. 1260061da546Spatrick Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( 1261061da546Spatrick BreakpointOptions *bp_options, const char *command_body_text, 1262061da546Spatrick StructuredData::ObjectSP extra_args_sp, 1263061da546Spatrick bool uses_extra_args) { 1264061da546Spatrick auto data_up = std::make_unique<CommandDataPython>(extra_args_sp); 1265061da546Spatrick // Split the command_body_text into lines, and pass that to 1266061da546Spatrick // GenerateBreakpointCommandCallbackData. That will wrap the body in an 1267061da546Spatrick // auto-generated function, and return the function name in script_source. 1268061da546Spatrick // That is what the callback will actually invoke. 1269061da546Spatrick 1270061da546Spatrick data_up->user_source.SplitIntoLines(command_body_text); 1271061da546Spatrick Status error = GenerateBreakpointCommandCallbackData(data_up->user_source, 1272061da546Spatrick data_up->script_source, 1273061da546Spatrick uses_extra_args); 1274061da546Spatrick if (error.Success()) { 1275061da546Spatrick auto baton_sp = 1276061da546Spatrick std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up)); 1277061da546Spatrick bp_options->SetCallback( 1278061da546Spatrick ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); 1279061da546Spatrick return error; 1280*dda28197Spatrick } 1281061da546Spatrick return error; 1282061da546Spatrick } 1283061da546Spatrick 1284061da546Spatrick // Set a Python one-liner as the callback for the watchpoint. 1285061da546Spatrick void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback( 1286061da546Spatrick WatchpointOptions *wp_options, const char *oneliner) { 1287061da546Spatrick auto data_up = std::make_unique<WatchpointOptions::CommandData>(); 1288061da546Spatrick 1289061da546Spatrick // It's necessary to set both user_source and script_source to the oneliner. 1290061da546Spatrick // The former is used to generate callback description (as in watchpoint 1291061da546Spatrick // command list) while the latter is used for Python to interpret during the 1292061da546Spatrick // actual callback. 1293061da546Spatrick 1294061da546Spatrick data_up->user_source.AppendString(oneliner); 1295061da546Spatrick data_up->script_source.assign(oneliner); 1296061da546Spatrick 1297061da546Spatrick if (GenerateWatchpointCommandCallbackData(data_up->user_source, 1298061da546Spatrick data_up->script_source)) { 1299061da546Spatrick auto baton_sp = 1300061da546Spatrick std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up)); 1301061da546Spatrick wp_options->SetCallback( 1302061da546Spatrick ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp); 1303061da546Spatrick } 1304061da546Spatrick 1305061da546Spatrick return; 1306061da546Spatrick } 1307061da546Spatrick 1308061da546Spatrick Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter( 1309061da546Spatrick StringList &function_def) { 1310061da546Spatrick // Convert StringList to one long, newline delimited, const char *. 1311061da546Spatrick std::string function_def_string(function_def.CopyList()); 1312061da546Spatrick 1313061da546Spatrick Status error = ExecuteMultipleLines( 1314061da546Spatrick function_def_string.c_str(), 1315061da546Spatrick ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false)); 1316061da546Spatrick return error; 1317061da546Spatrick } 1318061da546Spatrick 1319061da546Spatrick Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature, 1320061da546Spatrick const StringList &input) { 1321061da546Spatrick Status error; 1322061da546Spatrick int num_lines = input.GetSize(); 1323061da546Spatrick if (num_lines == 0) { 1324061da546Spatrick error.SetErrorString("No input data."); 1325061da546Spatrick return error; 1326061da546Spatrick } 1327061da546Spatrick 1328061da546Spatrick if (!signature || *signature == 0) { 1329061da546Spatrick error.SetErrorString("No output function name."); 1330061da546Spatrick return error; 1331061da546Spatrick } 1332061da546Spatrick 1333061da546Spatrick StreamString sstr; 1334061da546Spatrick StringList auto_generated_function; 1335061da546Spatrick auto_generated_function.AppendString(signature); 1336061da546Spatrick auto_generated_function.AppendString( 1337061da546Spatrick " global_dict = globals()"); // Grab the global dictionary 1338061da546Spatrick auto_generated_function.AppendString( 1339061da546Spatrick " new_keys = internal_dict.keys()"); // Make a list of keys in the 1340061da546Spatrick // session dict 1341061da546Spatrick auto_generated_function.AppendString( 1342061da546Spatrick " old_keys = global_dict.keys()"); // Save list of keys in global dict 1343061da546Spatrick auto_generated_function.AppendString( 1344061da546Spatrick " global_dict.update (internal_dict)"); // Add the session dictionary 1345061da546Spatrick // to the 1346061da546Spatrick // global dictionary. 1347061da546Spatrick 1348061da546Spatrick // Wrap everything up inside the function, increasing the indentation. 1349061da546Spatrick 1350061da546Spatrick auto_generated_function.AppendString(" if True:"); 1351061da546Spatrick for (int i = 0; i < num_lines; ++i) { 1352061da546Spatrick sstr.Clear(); 1353061da546Spatrick sstr.Printf(" %s", input.GetStringAtIndex(i)); 1354061da546Spatrick auto_generated_function.AppendString(sstr.GetData()); 1355061da546Spatrick } 1356061da546Spatrick auto_generated_function.AppendString( 1357061da546Spatrick " for key in new_keys:"); // Iterate over all the keys from session 1358061da546Spatrick // dict 1359061da546Spatrick auto_generated_function.AppendString( 1360061da546Spatrick " internal_dict[key] = global_dict[key]"); // Update session dict 1361061da546Spatrick // values 1362061da546Spatrick auto_generated_function.AppendString( 1363061da546Spatrick " if key not in old_keys:"); // If key was not originally in 1364061da546Spatrick // global dict 1365061da546Spatrick auto_generated_function.AppendString( 1366061da546Spatrick " del global_dict[key]"); // ...then remove key/value from 1367061da546Spatrick // global dict 1368061da546Spatrick 1369061da546Spatrick // Verify that the results are valid Python. 1370061da546Spatrick 1371061da546Spatrick error = ExportFunctionDefinitionToInterpreter(auto_generated_function); 1372061da546Spatrick 1373061da546Spatrick return error; 1374061da546Spatrick } 1375061da546Spatrick 1376061da546Spatrick bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction( 1377061da546Spatrick StringList &user_input, std::string &output, const void *name_token) { 1378061da546Spatrick static uint32_t num_created_functions = 0; 1379061da546Spatrick user_input.RemoveBlankLines(); 1380061da546Spatrick StreamString sstr; 1381061da546Spatrick 1382061da546Spatrick // Check to see if we have any data; if not, just return. 1383061da546Spatrick if (user_input.GetSize() == 0) 1384061da546Spatrick return false; 1385061da546Spatrick 1386061da546Spatrick // Take what the user wrote, wrap it all up inside one big auto-generated 1387061da546Spatrick // Python function, passing in the ValueObject as parameter to the function. 1388061da546Spatrick 1389061da546Spatrick std::string auto_generated_function_name( 1390061da546Spatrick GenerateUniqueName("lldb_autogen_python_type_print_func", 1391061da546Spatrick num_created_functions, name_token)); 1392061da546Spatrick sstr.Printf("def %s (valobj, internal_dict):", 1393061da546Spatrick auto_generated_function_name.c_str()); 1394061da546Spatrick 1395061da546Spatrick if (!GenerateFunction(sstr.GetData(), user_input).Success()) 1396061da546Spatrick return false; 1397061da546Spatrick 1398061da546Spatrick // Store the name of the auto-generated function to be called. 1399061da546Spatrick output.assign(auto_generated_function_name); 1400061da546Spatrick return true; 1401061da546Spatrick } 1402061da546Spatrick 1403061da546Spatrick bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction( 1404061da546Spatrick StringList &user_input, std::string &output) { 1405061da546Spatrick static uint32_t num_created_functions = 0; 1406061da546Spatrick user_input.RemoveBlankLines(); 1407061da546Spatrick StreamString sstr; 1408061da546Spatrick 1409061da546Spatrick // Check to see if we have any data; if not, just return. 1410061da546Spatrick if (user_input.GetSize() == 0) 1411061da546Spatrick return false; 1412061da546Spatrick 1413061da546Spatrick std::string auto_generated_function_name(GenerateUniqueName( 1414061da546Spatrick "lldb_autogen_python_cmd_alias_func", num_created_functions)); 1415061da546Spatrick 1416061da546Spatrick sstr.Printf("def %s (debugger, args, result, internal_dict):", 1417061da546Spatrick auto_generated_function_name.c_str()); 1418061da546Spatrick 1419061da546Spatrick if (!GenerateFunction(sstr.GetData(), user_input).Success()) 1420061da546Spatrick return false; 1421061da546Spatrick 1422061da546Spatrick // Store the name of the auto-generated function to be called. 1423061da546Spatrick output.assign(auto_generated_function_name); 1424061da546Spatrick return true; 1425061da546Spatrick } 1426061da546Spatrick 1427061da546Spatrick bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass( 1428061da546Spatrick StringList &user_input, std::string &output, const void *name_token) { 1429061da546Spatrick static uint32_t num_created_classes = 0; 1430061da546Spatrick user_input.RemoveBlankLines(); 1431061da546Spatrick int num_lines = user_input.GetSize(); 1432061da546Spatrick StreamString sstr; 1433061da546Spatrick 1434061da546Spatrick // Check to see if we have any data; if not, just return. 1435061da546Spatrick if (user_input.GetSize() == 0) 1436061da546Spatrick return false; 1437061da546Spatrick 1438061da546Spatrick // Wrap all user input into a Python class 1439061da546Spatrick 1440061da546Spatrick std::string auto_generated_class_name(GenerateUniqueName( 1441061da546Spatrick "lldb_autogen_python_type_synth_class", num_created_classes, name_token)); 1442061da546Spatrick 1443061da546Spatrick StringList auto_generated_class; 1444061da546Spatrick 1445061da546Spatrick // Create the function name & definition string. 1446061da546Spatrick 1447061da546Spatrick sstr.Printf("class %s:", auto_generated_class_name.c_str()); 1448061da546Spatrick auto_generated_class.AppendString(sstr.GetString()); 1449061da546Spatrick 1450061da546Spatrick // Wrap everything up inside the class, increasing the indentation. we don't 1451061da546Spatrick // need to play any fancy indentation tricks here because there is no 1452061da546Spatrick // surrounding code whose indentation we need to honor 1453061da546Spatrick for (int i = 0; i < num_lines; ++i) { 1454061da546Spatrick sstr.Clear(); 1455061da546Spatrick sstr.Printf(" %s", user_input.GetStringAtIndex(i)); 1456061da546Spatrick auto_generated_class.AppendString(sstr.GetString()); 1457061da546Spatrick } 1458061da546Spatrick 1459061da546Spatrick // Verify that the results are valid Python. (even though the method is 1460061da546Spatrick // ExportFunctionDefinitionToInterpreter, a class will actually be exported) 1461061da546Spatrick // (TODO: rename that method to ExportDefinitionToInterpreter) 1462061da546Spatrick if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success()) 1463061da546Spatrick return false; 1464061da546Spatrick 1465061da546Spatrick // Store the name of the auto-generated class 1466061da546Spatrick 1467061da546Spatrick output.assign(auto_generated_class_name); 1468061da546Spatrick return true; 1469061da546Spatrick } 1470061da546Spatrick 1471061da546Spatrick StructuredData::GenericSP 1472061da546Spatrick ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) { 1473061da546Spatrick if (class_name == nullptr || class_name[0] == '\0') 1474061da546Spatrick return StructuredData::GenericSP(); 1475061da546Spatrick 1476061da546Spatrick void *ret_val; 1477061da546Spatrick 1478061da546Spatrick { 1479061da546Spatrick Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, 1480061da546Spatrick Locker::FreeLock); 1481061da546Spatrick ret_val = LLDBSWIGPython_CreateFrameRecognizer(class_name, 1482061da546Spatrick m_dictionary_name.c_str()); 1483061da546Spatrick } 1484061da546Spatrick 1485061da546Spatrick return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 1486061da546Spatrick } 1487061da546Spatrick 1488061da546Spatrick lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments( 1489061da546Spatrick const StructuredData::ObjectSP &os_plugin_object_sp, 1490061da546Spatrick lldb::StackFrameSP frame_sp) { 1491061da546Spatrick Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 1492061da546Spatrick 1493061da546Spatrick if (!os_plugin_object_sp) 1494061da546Spatrick return ValueObjectListSP(); 1495061da546Spatrick 1496061da546Spatrick StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 1497061da546Spatrick if (!generic) 1498061da546Spatrick return nullptr; 1499061da546Spatrick 1500061da546Spatrick PythonObject implementor(PyRefType::Borrowed, 1501061da546Spatrick (PyObject *)generic->GetValue()); 1502061da546Spatrick 1503061da546Spatrick if (!implementor.IsAllocated()) 1504061da546Spatrick return ValueObjectListSP(); 1505061da546Spatrick 1506061da546Spatrick PythonObject py_return(PyRefType::Owned, 1507061da546Spatrick (PyObject *)LLDBSwigPython_GetRecognizedArguments( 1508061da546Spatrick implementor.get(), frame_sp)); 1509061da546Spatrick 1510061da546Spatrick // if it fails, print the error but otherwise go on 1511061da546Spatrick if (PyErr_Occurred()) { 1512061da546Spatrick PyErr_Print(); 1513061da546Spatrick PyErr_Clear(); 1514061da546Spatrick } 1515061da546Spatrick if (py_return.get()) { 1516061da546Spatrick PythonList result_list(PyRefType::Borrowed, py_return.get()); 1517061da546Spatrick ValueObjectListSP result = ValueObjectListSP(new ValueObjectList()); 1518061da546Spatrick for (size_t i = 0; i < result_list.GetSize(); i++) { 1519061da546Spatrick PyObject *item = result_list.GetItemAtIndex(i).get(); 1520061da546Spatrick lldb::SBValue *sb_value_ptr = 1521061da546Spatrick (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item); 1522061da546Spatrick auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); 1523061da546Spatrick if (valobj_sp) 1524061da546Spatrick result->Append(valobj_sp); 1525061da546Spatrick } 1526061da546Spatrick return result; 1527061da546Spatrick } 1528061da546Spatrick return ValueObjectListSP(); 1529061da546Spatrick } 1530061da546Spatrick 1531061da546Spatrick StructuredData::GenericSP 1532061da546Spatrick ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject( 1533061da546Spatrick const char *class_name, lldb::ProcessSP process_sp) { 1534061da546Spatrick if (class_name == nullptr || class_name[0] == '\0') 1535061da546Spatrick return StructuredData::GenericSP(); 1536061da546Spatrick 1537061da546Spatrick if (!process_sp) 1538061da546Spatrick return StructuredData::GenericSP(); 1539061da546Spatrick 1540061da546Spatrick void *ret_val; 1541061da546Spatrick 1542061da546Spatrick { 1543061da546Spatrick Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, 1544061da546Spatrick Locker::FreeLock); 1545061da546Spatrick ret_val = LLDBSWIGPythonCreateOSPlugin( 1546061da546Spatrick class_name, m_dictionary_name.c_str(), process_sp); 1547061da546Spatrick } 1548061da546Spatrick 1549061da546Spatrick return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 1550061da546Spatrick } 1551061da546Spatrick 1552061da546Spatrick StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo( 1553061da546Spatrick StructuredData::ObjectSP os_plugin_object_sp) { 1554061da546Spatrick Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 1555061da546Spatrick 1556061da546Spatrick static char callee_name[] = "get_register_info"; 1557061da546Spatrick 1558061da546Spatrick if (!os_plugin_object_sp) 1559061da546Spatrick return StructuredData::DictionarySP(); 1560061da546Spatrick 1561061da546Spatrick StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 1562061da546Spatrick if (!generic) 1563061da546Spatrick return nullptr; 1564061da546Spatrick 1565061da546Spatrick PythonObject implementor(PyRefType::Borrowed, 1566061da546Spatrick (PyObject *)generic->GetValue()); 1567061da546Spatrick 1568061da546Spatrick if (!implementor.IsAllocated()) 1569061da546Spatrick return StructuredData::DictionarySP(); 1570061da546Spatrick 1571061da546Spatrick PythonObject pmeth(PyRefType::Owned, 1572061da546Spatrick PyObject_GetAttrString(implementor.get(), callee_name)); 1573061da546Spatrick 1574061da546Spatrick if (PyErr_Occurred()) 1575061da546Spatrick PyErr_Clear(); 1576061da546Spatrick 1577061da546Spatrick if (!pmeth.IsAllocated()) 1578061da546Spatrick return StructuredData::DictionarySP(); 1579061da546Spatrick 1580061da546Spatrick if (PyCallable_Check(pmeth.get()) == 0) { 1581061da546Spatrick if (PyErr_Occurred()) 1582061da546Spatrick PyErr_Clear(); 1583061da546Spatrick 1584061da546Spatrick return StructuredData::DictionarySP(); 1585061da546Spatrick } 1586061da546Spatrick 1587061da546Spatrick if (PyErr_Occurred()) 1588061da546Spatrick PyErr_Clear(); 1589061da546Spatrick 1590061da546Spatrick // right now we know this function exists and is callable.. 1591061da546Spatrick PythonObject py_return( 1592061da546Spatrick PyRefType::Owned, 1593061da546Spatrick PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 1594061da546Spatrick 1595061da546Spatrick // if it fails, print the error but otherwise go on 1596061da546Spatrick if (PyErr_Occurred()) { 1597061da546Spatrick PyErr_Print(); 1598061da546Spatrick PyErr_Clear(); 1599061da546Spatrick } 1600061da546Spatrick if (py_return.get()) { 1601061da546Spatrick PythonDictionary result_dict(PyRefType::Borrowed, py_return.get()); 1602061da546Spatrick return result_dict.CreateStructuredDictionary(); 1603061da546Spatrick } 1604061da546Spatrick return StructuredData::DictionarySP(); 1605061da546Spatrick } 1606061da546Spatrick 1607061da546Spatrick StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo( 1608061da546Spatrick StructuredData::ObjectSP os_plugin_object_sp) { 1609061da546Spatrick Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 1610061da546Spatrick 1611061da546Spatrick static char callee_name[] = "get_thread_info"; 1612061da546Spatrick 1613061da546Spatrick if (!os_plugin_object_sp) 1614061da546Spatrick return StructuredData::ArraySP(); 1615061da546Spatrick 1616061da546Spatrick StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 1617061da546Spatrick if (!generic) 1618061da546Spatrick return nullptr; 1619061da546Spatrick 1620061da546Spatrick PythonObject implementor(PyRefType::Borrowed, 1621061da546Spatrick (PyObject *)generic->GetValue()); 1622061da546Spatrick 1623061da546Spatrick if (!implementor.IsAllocated()) 1624061da546Spatrick return StructuredData::ArraySP(); 1625061da546Spatrick 1626061da546Spatrick PythonObject pmeth(PyRefType::Owned, 1627061da546Spatrick PyObject_GetAttrString(implementor.get(), callee_name)); 1628061da546Spatrick 1629061da546Spatrick if (PyErr_Occurred()) 1630061da546Spatrick PyErr_Clear(); 1631061da546Spatrick 1632061da546Spatrick if (!pmeth.IsAllocated()) 1633061da546Spatrick return StructuredData::ArraySP(); 1634061da546Spatrick 1635061da546Spatrick if (PyCallable_Check(pmeth.get()) == 0) { 1636061da546Spatrick if (PyErr_Occurred()) 1637061da546Spatrick PyErr_Clear(); 1638061da546Spatrick 1639061da546Spatrick return StructuredData::ArraySP(); 1640061da546Spatrick } 1641061da546Spatrick 1642061da546Spatrick if (PyErr_Occurred()) 1643061da546Spatrick PyErr_Clear(); 1644061da546Spatrick 1645061da546Spatrick // right now we know this function exists and is callable.. 1646061da546Spatrick PythonObject py_return( 1647061da546Spatrick PyRefType::Owned, 1648061da546Spatrick PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 1649061da546Spatrick 1650061da546Spatrick // if it fails, print the error but otherwise go on 1651061da546Spatrick if (PyErr_Occurred()) { 1652061da546Spatrick PyErr_Print(); 1653061da546Spatrick PyErr_Clear(); 1654061da546Spatrick } 1655061da546Spatrick 1656061da546Spatrick if (py_return.get()) { 1657061da546Spatrick PythonList result_list(PyRefType::Borrowed, py_return.get()); 1658061da546Spatrick return result_list.CreateStructuredArray(); 1659061da546Spatrick } 1660061da546Spatrick return StructuredData::ArraySP(); 1661061da546Spatrick } 1662061da546Spatrick 1663061da546Spatrick // GetPythonValueFormatString provides a system independent type safe way to 1664061da546Spatrick // convert a variable's type into a python value format. Python value formats 1665061da546Spatrick // are defined in terms of builtin C types and could change from system to as 1666061da546Spatrick // the underlying typedef for uint* types, size_t, off_t and other values 1667061da546Spatrick // change. 1668061da546Spatrick 1669061da546Spatrick template <typename T> const char *GetPythonValueFormatString(T t); 1670061da546Spatrick template <> const char *GetPythonValueFormatString(char *) { return "s"; } 1671061da546Spatrick template <> const char *GetPythonValueFormatString(char) { return "b"; } 1672061da546Spatrick template <> const char *GetPythonValueFormatString(unsigned char) { 1673061da546Spatrick return "B"; 1674061da546Spatrick } 1675061da546Spatrick template <> const char *GetPythonValueFormatString(short) { return "h"; } 1676061da546Spatrick template <> const char *GetPythonValueFormatString(unsigned short) { 1677061da546Spatrick return "H"; 1678061da546Spatrick } 1679061da546Spatrick template <> const char *GetPythonValueFormatString(int) { return "i"; } 1680061da546Spatrick template <> const char *GetPythonValueFormatString(unsigned int) { return "I"; } 1681061da546Spatrick template <> const char *GetPythonValueFormatString(long) { return "l"; } 1682061da546Spatrick template <> const char *GetPythonValueFormatString(unsigned long) { 1683061da546Spatrick return "k"; 1684061da546Spatrick } 1685061da546Spatrick template <> const char *GetPythonValueFormatString(long long) { return "L"; } 1686061da546Spatrick template <> const char *GetPythonValueFormatString(unsigned long long) { 1687061da546Spatrick return "K"; 1688061da546Spatrick } 1689061da546Spatrick template <> const char *GetPythonValueFormatString(float t) { return "f"; } 1690061da546Spatrick template <> const char *GetPythonValueFormatString(double t) { return "d"; } 1691061da546Spatrick 1692061da546Spatrick StructuredData::StringSP 1693061da546Spatrick ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData( 1694061da546Spatrick StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) { 1695061da546Spatrick Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 1696061da546Spatrick 1697061da546Spatrick static char callee_name[] = "get_register_data"; 1698061da546Spatrick static char *param_format = 1699061da546Spatrick const_cast<char *>(GetPythonValueFormatString(tid)); 1700061da546Spatrick 1701061da546Spatrick if (!os_plugin_object_sp) 1702061da546Spatrick return StructuredData::StringSP(); 1703061da546Spatrick 1704061da546Spatrick StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 1705061da546Spatrick if (!generic) 1706061da546Spatrick return nullptr; 1707061da546Spatrick PythonObject implementor(PyRefType::Borrowed, 1708061da546Spatrick (PyObject *)generic->GetValue()); 1709061da546Spatrick 1710061da546Spatrick if (!implementor.IsAllocated()) 1711061da546Spatrick return StructuredData::StringSP(); 1712061da546Spatrick 1713061da546Spatrick PythonObject pmeth(PyRefType::Owned, 1714061da546Spatrick PyObject_GetAttrString(implementor.get(), callee_name)); 1715061da546Spatrick 1716061da546Spatrick if (PyErr_Occurred()) 1717061da546Spatrick PyErr_Clear(); 1718061da546Spatrick 1719061da546Spatrick if (!pmeth.IsAllocated()) 1720061da546Spatrick return StructuredData::StringSP(); 1721061da546Spatrick 1722061da546Spatrick if (PyCallable_Check(pmeth.get()) == 0) { 1723061da546Spatrick if (PyErr_Occurred()) 1724061da546Spatrick PyErr_Clear(); 1725061da546Spatrick return StructuredData::StringSP(); 1726061da546Spatrick } 1727061da546Spatrick 1728061da546Spatrick if (PyErr_Occurred()) 1729061da546Spatrick PyErr_Clear(); 1730061da546Spatrick 1731061da546Spatrick // right now we know this function exists and is callable.. 1732061da546Spatrick PythonObject py_return( 1733061da546Spatrick PyRefType::Owned, 1734061da546Spatrick PyObject_CallMethod(implementor.get(), callee_name, param_format, tid)); 1735061da546Spatrick 1736061da546Spatrick // if it fails, print the error but otherwise go on 1737061da546Spatrick if (PyErr_Occurred()) { 1738061da546Spatrick PyErr_Print(); 1739061da546Spatrick PyErr_Clear(); 1740061da546Spatrick } 1741061da546Spatrick 1742061da546Spatrick if (py_return.get()) { 1743061da546Spatrick PythonBytes result(PyRefType::Borrowed, py_return.get()); 1744061da546Spatrick return result.CreateStructuredString(); 1745061da546Spatrick } 1746061da546Spatrick return StructuredData::StringSP(); 1747061da546Spatrick } 1748061da546Spatrick 1749061da546Spatrick StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread( 1750061da546Spatrick StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid, 1751061da546Spatrick lldb::addr_t context) { 1752061da546Spatrick Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 1753061da546Spatrick 1754061da546Spatrick static char callee_name[] = "create_thread"; 1755061da546Spatrick std::string param_format; 1756061da546Spatrick param_format += GetPythonValueFormatString(tid); 1757061da546Spatrick param_format += GetPythonValueFormatString(context); 1758061da546Spatrick 1759061da546Spatrick if (!os_plugin_object_sp) 1760061da546Spatrick return StructuredData::DictionarySP(); 1761061da546Spatrick 1762061da546Spatrick StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 1763061da546Spatrick if (!generic) 1764061da546Spatrick return nullptr; 1765061da546Spatrick 1766061da546Spatrick PythonObject implementor(PyRefType::Borrowed, 1767061da546Spatrick (PyObject *)generic->GetValue()); 1768061da546Spatrick 1769061da546Spatrick if (!implementor.IsAllocated()) 1770061da546Spatrick return StructuredData::DictionarySP(); 1771061da546Spatrick 1772061da546Spatrick PythonObject pmeth(PyRefType::Owned, 1773061da546Spatrick PyObject_GetAttrString(implementor.get(), callee_name)); 1774061da546Spatrick 1775061da546Spatrick if (PyErr_Occurred()) 1776061da546Spatrick PyErr_Clear(); 1777061da546Spatrick 1778061da546Spatrick if (!pmeth.IsAllocated()) 1779061da546Spatrick return StructuredData::DictionarySP(); 1780061da546Spatrick 1781061da546Spatrick if (PyCallable_Check(pmeth.get()) == 0) { 1782061da546Spatrick if (PyErr_Occurred()) 1783061da546Spatrick PyErr_Clear(); 1784061da546Spatrick return StructuredData::DictionarySP(); 1785061da546Spatrick } 1786061da546Spatrick 1787061da546Spatrick if (PyErr_Occurred()) 1788061da546Spatrick PyErr_Clear(); 1789061da546Spatrick 1790061da546Spatrick // right now we know this function exists and is callable.. 1791061da546Spatrick PythonObject py_return(PyRefType::Owned, 1792061da546Spatrick PyObject_CallMethod(implementor.get(), callee_name, 1793061da546Spatrick ¶m_format[0], tid, context)); 1794061da546Spatrick 1795061da546Spatrick // if it fails, print the error but otherwise go on 1796061da546Spatrick if (PyErr_Occurred()) { 1797061da546Spatrick PyErr_Print(); 1798061da546Spatrick PyErr_Clear(); 1799061da546Spatrick } 1800061da546Spatrick 1801061da546Spatrick if (py_return.get()) { 1802061da546Spatrick PythonDictionary result_dict(PyRefType::Borrowed, py_return.get()); 1803061da546Spatrick return result_dict.CreateStructuredDictionary(); 1804061da546Spatrick } 1805061da546Spatrick return StructuredData::DictionarySP(); 1806061da546Spatrick } 1807061da546Spatrick 1808061da546Spatrick StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan( 1809061da546Spatrick const char *class_name, StructuredDataImpl *args_data, 1810061da546Spatrick std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) { 1811061da546Spatrick if (class_name == nullptr || class_name[0] == '\0') 1812061da546Spatrick return StructuredData::ObjectSP(); 1813061da546Spatrick 1814061da546Spatrick if (!thread_plan_sp.get()) 1815061da546Spatrick return {}; 1816061da546Spatrick 1817061da546Spatrick Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger(); 1818061da546Spatrick ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter(); 1819061da546Spatrick ScriptInterpreterPythonImpl *python_interpreter = 1820061da546Spatrick static_cast<ScriptInterpreterPythonImpl *>(script_interpreter); 1821061da546Spatrick 1822061da546Spatrick if (!script_interpreter) 1823061da546Spatrick return {}; 1824061da546Spatrick 1825061da546Spatrick void *ret_val; 1826061da546Spatrick 1827061da546Spatrick { 1828061da546Spatrick Locker py_lock(this, 1829061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1830061da546Spatrick ret_val = LLDBSwigPythonCreateScriptedThreadPlan( 1831061da546Spatrick class_name, python_interpreter->m_dictionary_name.c_str(), 1832061da546Spatrick args_data, error_str, thread_plan_sp); 1833061da546Spatrick if (!ret_val) 1834061da546Spatrick return {}; 1835061da546Spatrick } 1836061da546Spatrick 1837061da546Spatrick return StructuredData::ObjectSP(new StructuredPythonObject(ret_val)); 1838061da546Spatrick } 1839061da546Spatrick 1840061da546Spatrick bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop( 1841061da546Spatrick StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) { 1842061da546Spatrick bool explains_stop = true; 1843061da546Spatrick StructuredData::Generic *generic = nullptr; 1844061da546Spatrick if (implementor_sp) 1845061da546Spatrick generic = implementor_sp->GetAsGeneric(); 1846061da546Spatrick if (generic) { 1847061da546Spatrick Locker py_lock(this, 1848061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1849061da546Spatrick explains_stop = LLDBSWIGPythonCallThreadPlan( 1850061da546Spatrick generic->GetValue(), "explains_stop", event, script_error); 1851061da546Spatrick if (script_error) 1852061da546Spatrick return true; 1853061da546Spatrick } 1854061da546Spatrick return explains_stop; 1855061da546Spatrick } 1856061da546Spatrick 1857061da546Spatrick bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop( 1858061da546Spatrick StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) { 1859061da546Spatrick bool should_stop = true; 1860061da546Spatrick StructuredData::Generic *generic = nullptr; 1861061da546Spatrick if (implementor_sp) 1862061da546Spatrick generic = implementor_sp->GetAsGeneric(); 1863061da546Spatrick if (generic) { 1864061da546Spatrick Locker py_lock(this, 1865061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1866061da546Spatrick should_stop = LLDBSWIGPythonCallThreadPlan( 1867061da546Spatrick generic->GetValue(), "should_stop", event, script_error); 1868061da546Spatrick if (script_error) 1869061da546Spatrick return true; 1870061da546Spatrick } 1871061da546Spatrick return should_stop; 1872061da546Spatrick } 1873061da546Spatrick 1874061da546Spatrick bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale( 1875061da546Spatrick StructuredData::ObjectSP implementor_sp, bool &script_error) { 1876061da546Spatrick bool is_stale = true; 1877061da546Spatrick StructuredData::Generic *generic = nullptr; 1878061da546Spatrick if (implementor_sp) 1879061da546Spatrick generic = implementor_sp->GetAsGeneric(); 1880061da546Spatrick if (generic) { 1881061da546Spatrick Locker py_lock(this, 1882061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1883061da546Spatrick is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale", 1884061da546Spatrick nullptr, script_error); 1885061da546Spatrick if (script_error) 1886061da546Spatrick return true; 1887061da546Spatrick } 1888061da546Spatrick return is_stale; 1889061da546Spatrick } 1890061da546Spatrick 1891061da546Spatrick lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState( 1892061da546Spatrick StructuredData::ObjectSP implementor_sp, bool &script_error) { 1893061da546Spatrick bool should_step = false; 1894061da546Spatrick StructuredData::Generic *generic = nullptr; 1895061da546Spatrick if (implementor_sp) 1896061da546Spatrick generic = implementor_sp->GetAsGeneric(); 1897061da546Spatrick if (generic) { 1898061da546Spatrick Locker py_lock(this, 1899061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1900061da546Spatrick should_step = LLDBSWIGPythonCallThreadPlan( 1901061da546Spatrick generic->GetValue(), "should_step", nullptr, script_error); 1902061da546Spatrick if (script_error) 1903061da546Spatrick should_step = true; 1904061da546Spatrick } 1905061da546Spatrick if (should_step) 1906061da546Spatrick return lldb::eStateStepping; 1907061da546Spatrick return lldb::eStateRunning; 1908061da546Spatrick } 1909061da546Spatrick 1910061da546Spatrick StructuredData::GenericSP 1911061da546Spatrick ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver( 1912061da546Spatrick const char *class_name, StructuredDataImpl *args_data, 1913061da546Spatrick lldb::BreakpointSP &bkpt_sp) { 1914061da546Spatrick 1915061da546Spatrick if (class_name == nullptr || class_name[0] == '\0') 1916061da546Spatrick return StructuredData::GenericSP(); 1917061da546Spatrick 1918061da546Spatrick if (!bkpt_sp.get()) 1919061da546Spatrick return StructuredData::GenericSP(); 1920061da546Spatrick 1921061da546Spatrick Debugger &debugger = bkpt_sp->GetTarget().GetDebugger(); 1922061da546Spatrick ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter(); 1923061da546Spatrick ScriptInterpreterPythonImpl *python_interpreter = 1924061da546Spatrick static_cast<ScriptInterpreterPythonImpl *>(script_interpreter); 1925061da546Spatrick 1926061da546Spatrick if (!script_interpreter) 1927061da546Spatrick return StructuredData::GenericSP(); 1928061da546Spatrick 1929061da546Spatrick void *ret_val; 1930061da546Spatrick 1931061da546Spatrick { 1932061da546Spatrick Locker py_lock(this, 1933061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1934061da546Spatrick 1935061da546Spatrick ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver( 1936061da546Spatrick class_name, python_interpreter->m_dictionary_name.c_str(), args_data, 1937061da546Spatrick bkpt_sp); 1938061da546Spatrick } 1939061da546Spatrick 1940061da546Spatrick return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 1941061da546Spatrick } 1942061da546Spatrick 1943061da546Spatrick bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback( 1944061da546Spatrick StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) { 1945061da546Spatrick bool should_continue = false; 1946061da546Spatrick 1947061da546Spatrick if (implementor_sp) { 1948061da546Spatrick Locker py_lock(this, 1949061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1950061da546Spatrick should_continue = LLDBSwigPythonCallBreakpointResolver( 1951061da546Spatrick implementor_sp->GetValue(), "__callback__", sym_ctx); 1952061da546Spatrick if (PyErr_Occurred()) { 1953061da546Spatrick PyErr_Print(); 1954061da546Spatrick PyErr_Clear(); 1955061da546Spatrick } 1956061da546Spatrick } 1957061da546Spatrick return should_continue; 1958061da546Spatrick } 1959061da546Spatrick 1960061da546Spatrick lldb::SearchDepth 1961061da546Spatrick ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth( 1962061da546Spatrick StructuredData::GenericSP implementor_sp) { 1963061da546Spatrick int depth_as_int = lldb::eSearchDepthModule; 1964061da546Spatrick if (implementor_sp) { 1965061da546Spatrick Locker py_lock(this, 1966061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1967061da546Spatrick depth_as_int = LLDBSwigPythonCallBreakpointResolver( 1968061da546Spatrick implementor_sp->GetValue(), "__get_depth__", nullptr); 1969061da546Spatrick if (PyErr_Occurred()) { 1970061da546Spatrick PyErr_Print(); 1971061da546Spatrick PyErr_Clear(); 1972061da546Spatrick } 1973061da546Spatrick } 1974061da546Spatrick if (depth_as_int == lldb::eSearchDepthInvalid) 1975061da546Spatrick return lldb::eSearchDepthModule; 1976061da546Spatrick 1977061da546Spatrick if (depth_as_int <= lldb::kLastSearchDepthKind) 1978061da546Spatrick return (lldb::SearchDepth)depth_as_int; 1979061da546Spatrick return lldb::eSearchDepthModule; 1980061da546Spatrick } 1981061da546Spatrick 1982061da546Spatrick StructuredData::ObjectSP 1983061da546Spatrick ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec, 1984061da546Spatrick lldb_private::Status &error) { 1985061da546Spatrick if (!FileSystem::Instance().Exists(file_spec)) { 1986061da546Spatrick error.SetErrorString("no such file"); 1987061da546Spatrick return StructuredData::ObjectSP(); 1988061da546Spatrick } 1989061da546Spatrick 1990061da546Spatrick StructuredData::ObjectSP module_sp; 1991061da546Spatrick 1992061da546Spatrick if (LoadScriptingModule(file_spec.GetPath().c_str(), true, error, &module_sp)) 1993061da546Spatrick return module_sp; 1994061da546Spatrick 1995061da546Spatrick return StructuredData::ObjectSP(); 1996061da546Spatrick } 1997061da546Spatrick 1998061da546Spatrick StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings( 1999061da546Spatrick StructuredData::ObjectSP plugin_module_sp, Target *target, 2000061da546Spatrick const char *setting_name, lldb_private::Status &error) { 2001061da546Spatrick if (!plugin_module_sp || !target || !setting_name || !setting_name[0]) 2002061da546Spatrick return StructuredData::DictionarySP(); 2003061da546Spatrick StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric(); 2004061da546Spatrick if (!generic) 2005061da546Spatrick return StructuredData::DictionarySP(); 2006061da546Spatrick 2007061da546Spatrick Locker py_lock(this, 2008061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2009061da546Spatrick TargetSP target_sp(target->shared_from_this()); 2010061da546Spatrick 2011061da546Spatrick auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting( 2012061da546Spatrick generic->GetValue(), setting_name, target_sp); 2013061da546Spatrick 2014061da546Spatrick if (!setting) 2015061da546Spatrick return StructuredData::DictionarySP(); 2016061da546Spatrick 2017061da546Spatrick PythonDictionary py_dict = 2018061da546Spatrick unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting))); 2019061da546Spatrick 2020061da546Spatrick if (!py_dict) 2021061da546Spatrick return StructuredData::DictionarySP(); 2022061da546Spatrick 2023061da546Spatrick return py_dict.CreateStructuredDictionary(); 2024061da546Spatrick } 2025061da546Spatrick 2026061da546Spatrick StructuredData::ObjectSP 2027061da546Spatrick ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider( 2028061da546Spatrick const char *class_name, lldb::ValueObjectSP valobj) { 2029061da546Spatrick if (class_name == nullptr || class_name[0] == '\0') 2030061da546Spatrick return StructuredData::ObjectSP(); 2031061da546Spatrick 2032061da546Spatrick if (!valobj.get()) 2033061da546Spatrick return StructuredData::ObjectSP(); 2034061da546Spatrick 2035061da546Spatrick ExecutionContext exe_ctx(valobj->GetExecutionContextRef()); 2036061da546Spatrick Target *target = exe_ctx.GetTargetPtr(); 2037061da546Spatrick 2038061da546Spatrick if (!target) 2039061da546Spatrick return StructuredData::ObjectSP(); 2040061da546Spatrick 2041061da546Spatrick Debugger &debugger = target->GetDebugger(); 2042061da546Spatrick ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter(); 2043061da546Spatrick ScriptInterpreterPythonImpl *python_interpreter = 2044061da546Spatrick (ScriptInterpreterPythonImpl *)script_interpreter; 2045061da546Spatrick 2046061da546Spatrick if (!script_interpreter) 2047061da546Spatrick return StructuredData::ObjectSP(); 2048061da546Spatrick 2049061da546Spatrick void *ret_val = nullptr; 2050061da546Spatrick 2051061da546Spatrick { 2052061da546Spatrick Locker py_lock(this, 2053061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2054061da546Spatrick ret_val = LLDBSwigPythonCreateSyntheticProvider( 2055061da546Spatrick class_name, python_interpreter->m_dictionary_name.c_str(), valobj); 2056061da546Spatrick } 2057061da546Spatrick 2058061da546Spatrick return StructuredData::ObjectSP(new StructuredPythonObject(ret_val)); 2059061da546Spatrick } 2060061da546Spatrick 2061061da546Spatrick StructuredData::GenericSP 2062061da546Spatrick ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) { 2063061da546Spatrick DebuggerSP debugger_sp(m_debugger.shared_from_this()); 2064061da546Spatrick 2065061da546Spatrick if (class_name == nullptr || class_name[0] == '\0') 2066061da546Spatrick return StructuredData::GenericSP(); 2067061da546Spatrick 2068061da546Spatrick if (!debugger_sp.get()) 2069061da546Spatrick return StructuredData::GenericSP(); 2070061da546Spatrick 2071061da546Spatrick void *ret_val; 2072061da546Spatrick 2073061da546Spatrick { 2074061da546Spatrick Locker py_lock(this, 2075061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2076061da546Spatrick ret_val = LLDBSwigPythonCreateCommandObject( 2077061da546Spatrick class_name, m_dictionary_name.c_str(), debugger_sp); 2078061da546Spatrick } 2079061da546Spatrick 2080061da546Spatrick return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 2081061da546Spatrick } 2082061da546Spatrick 2083061da546Spatrick bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction( 2084061da546Spatrick const char *oneliner, std::string &output, const void *name_token) { 2085061da546Spatrick StringList input; 2086061da546Spatrick input.SplitIntoLines(oneliner, strlen(oneliner)); 2087061da546Spatrick return GenerateTypeScriptFunction(input, output, name_token); 2088061da546Spatrick } 2089061da546Spatrick 2090061da546Spatrick bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass( 2091061da546Spatrick const char *oneliner, std::string &output, const void *name_token) { 2092061da546Spatrick StringList input; 2093061da546Spatrick input.SplitIntoLines(oneliner, strlen(oneliner)); 2094061da546Spatrick return GenerateTypeSynthClass(input, output, name_token); 2095061da546Spatrick } 2096061da546Spatrick 2097061da546Spatrick Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData( 2098061da546Spatrick StringList &user_input, std::string &output, 2099061da546Spatrick bool has_extra_args) { 2100061da546Spatrick static uint32_t num_created_functions = 0; 2101061da546Spatrick user_input.RemoveBlankLines(); 2102061da546Spatrick StreamString sstr; 2103061da546Spatrick Status error; 2104061da546Spatrick if (user_input.GetSize() == 0) { 2105061da546Spatrick error.SetErrorString("No input data."); 2106061da546Spatrick return error; 2107061da546Spatrick } 2108061da546Spatrick 2109061da546Spatrick std::string auto_generated_function_name(GenerateUniqueName( 2110061da546Spatrick "lldb_autogen_python_bp_callback_func_", num_created_functions)); 2111061da546Spatrick if (has_extra_args) 2112061da546Spatrick sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):", 2113061da546Spatrick auto_generated_function_name.c_str()); 2114061da546Spatrick else 2115061da546Spatrick sstr.Printf("def %s (frame, bp_loc, internal_dict):", 2116061da546Spatrick auto_generated_function_name.c_str()); 2117061da546Spatrick 2118061da546Spatrick error = GenerateFunction(sstr.GetData(), user_input); 2119061da546Spatrick if (!error.Success()) 2120061da546Spatrick return error; 2121061da546Spatrick 2122061da546Spatrick // Store the name of the auto-generated function to be called. 2123061da546Spatrick output.assign(auto_generated_function_name); 2124061da546Spatrick return error; 2125061da546Spatrick } 2126061da546Spatrick 2127061da546Spatrick bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData( 2128061da546Spatrick StringList &user_input, std::string &output) { 2129061da546Spatrick static uint32_t num_created_functions = 0; 2130061da546Spatrick user_input.RemoveBlankLines(); 2131061da546Spatrick StreamString sstr; 2132061da546Spatrick 2133061da546Spatrick if (user_input.GetSize() == 0) 2134061da546Spatrick return false; 2135061da546Spatrick 2136061da546Spatrick std::string auto_generated_function_name(GenerateUniqueName( 2137061da546Spatrick "lldb_autogen_python_wp_callback_func_", num_created_functions)); 2138061da546Spatrick sstr.Printf("def %s (frame, wp, internal_dict):", 2139061da546Spatrick auto_generated_function_name.c_str()); 2140061da546Spatrick 2141061da546Spatrick if (!GenerateFunction(sstr.GetData(), user_input).Success()) 2142061da546Spatrick return false; 2143061da546Spatrick 2144061da546Spatrick // Store the name of the auto-generated function to be called. 2145061da546Spatrick output.assign(auto_generated_function_name); 2146061da546Spatrick return true; 2147061da546Spatrick } 2148061da546Spatrick 2149061da546Spatrick bool ScriptInterpreterPythonImpl::GetScriptedSummary( 2150061da546Spatrick const char *python_function_name, lldb::ValueObjectSP valobj, 2151061da546Spatrick StructuredData::ObjectSP &callee_wrapper_sp, 2152061da546Spatrick const TypeSummaryOptions &options, std::string &retval) { 2153061da546Spatrick 2154061da546Spatrick static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 2155061da546Spatrick Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); 2156061da546Spatrick 2157061da546Spatrick if (!valobj.get()) { 2158061da546Spatrick retval.assign("<no object>"); 2159061da546Spatrick return false; 2160061da546Spatrick } 2161061da546Spatrick 2162061da546Spatrick void *old_callee = nullptr; 2163061da546Spatrick StructuredData::Generic *generic = nullptr; 2164061da546Spatrick if (callee_wrapper_sp) { 2165061da546Spatrick generic = callee_wrapper_sp->GetAsGeneric(); 2166061da546Spatrick if (generic) 2167061da546Spatrick old_callee = generic->GetValue(); 2168061da546Spatrick } 2169061da546Spatrick void *new_callee = old_callee; 2170061da546Spatrick 2171061da546Spatrick bool ret_val; 2172061da546Spatrick if (python_function_name && *python_function_name) { 2173061da546Spatrick { 2174061da546Spatrick Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | 2175061da546Spatrick Locker::NoSTDIN); 2176061da546Spatrick { 2177061da546Spatrick TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options)); 2178061da546Spatrick 2179061da546Spatrick static Timer::Category func_cat("LLDBSwigPythonCallTypeScript"); 2180061da546Spatrick Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript"); 2181061da546Spatrick ret_val = LLDBSwigPythonCallTypeScript( 2182061da546Spatrick python_function_name, GetSessionDictionary().get(), valobj, 2183061da546Spatrick &new_callee, options_sp, retval); 2184061da546Spatrick } 2185061da546Spatrick } 2186061da546Spatrick } else { 2187061da546Spatrick retval.assign("<no function name>"); 2188061da546Spatrick return false; 2189061da546Spatrick } 2190061da546Spatrick 2191061da546Spatrick if (new_callee && old_callee != new_callee) 2192061da546Spatrick callee_wrapper_sp = std::make_shared<StructuredPythonObject>(new_callee); 2193061da546Spatrick 2194061da546Spatrick return ret_val; 2195061da546Spatrick } 2196061da546Spatrick 2197061da546Spatrick bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction( 2198061da546Spatrick void *baton, StoppointCallbackContext *context, user_id_t break_id, 2199061da546Spatrick user_id_t break_loc_id) { 2200061da546Spatrick CommandDataPython *bp_option_data = (CommandDataPython *)baton; 2201061da546Spatrick const char *python_function_name = bp_option_data->script_source.c_str(); 2202061da546Spatrick 2203061da546Spatrick if (!context) 2204061da546Spatrick return true; 2205061da546Spatrick 2206061da546Spatrick ExecutionContext exe_ctx(context->exe_ctx_ref); 2207061da546Spatrick Target *target = exe_ctx.GetTargetPtr(); 2208061da546Spatrick 2209061da546Spatrick if (!target) 2210061da546Spatrick return true; 2211061da546Spatrick 2212061da546Spatrick Debugger &debugger = target->GetDebugger(); 2213061da546Spatrick ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter(); 2214061da546Spatrick ScriptInterpreterPythonImpl *python_interpreter = 2215061da546Spatrick (ScriptInterpreterPythonImpl *)script_interpreter; 2216061da546Spatrick 2217061da546Spatrick if (!script_interpreter) 2218061da546Spatrick return true; 2219061da546Spatrick 2220061da546Spatrick if (python_function_name && python_function_name[0]) { 2221061da546Spatrick const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP()); 2222061da546Spatrick BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id); 2223061da546Spatrick if (breakpoint_sp) { 2224061da546Spatrick const BreakpointLocationSP bp_loc_sp( 2225061da546Spatrick breakpoint_sp->FindLocationByID(break_loc_id)); 2226061da546Spatrick 2227061da546Spatrick if (stop_frame_sp && bp_loc_sp) { 2228061da546Spatrick bool ret_val = true; 2229061da546Spatrick { 2230061da546Spatrick Locker py_lock(python_interpreter, Locker::AcquireLock | 2231061da546Spatrick Locker::InitSession | 2232061da546Spatrick Locker::NoSTDIN); 2233061da546Spatrick Expected<bool> maybe_ret_val = 2234061da546Spatrick LLDBSwigPythonBreakpointCallbackFunction( 2235061da546Spatrick python_function_name, 2236061da546Spatrick python_interpreter->m_dictionary_name.c_str(), stop_frame_sp, 2237061da546Spatrick bp_loc_sp, bp_option_data->m_extra_args_up.get()); 2238061da546Spatrick 2239061da546Spatrick if (!maybe_ret_val) { 2240061da546Spatrick 2241061da546Spatrick llvm::handleAllErrors( 2242061da546Spatrick maybe_ret_val.takeError(), 2243061da546Spatrick [&](PythonException &E) { 2244061da546Spatrick debugger.GetErrorStream() << E.ReadBacktrace(); 2245061da546Spatrick }, 2246061da546Spatrick [&](const llvm::ErrorInfoBase &E) { 2247061da546Spatrick debugger.GetErrorStream() << E.message(); 2248061da546Spatrick }); 2249061da546Spatrick 2250061da546Spatrick } else { 2251061da546Spatrick ret_val = maybe_ret_val.get(); 2252061da546Spatrick } 2253061da546Spatrick } 2254061da546Spatrick return ret_val; 2255061da546Spatrick } 2256061da546Spatrick } 2257061da546Spatrick } 2258061da546Spatrick // We currently always true so we stop in case anything goes wrong when 2259061da546Spatrick // trying to call the script function 2260061da546Spatrick return true; 2261061da546Spatrick } 2262061da546Spatrick 2263061da546Spatrick bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction( 2264061da546Spatrick void *baton, StoppointCallbackContext *context, user_id_t watch_id) { 2265061da546Spatrick WatchpointOptions::CommandData *wp_option_data = 2266061da546Spatrick (WatchpointOptions::CommandData *)baton; 2267061da546Spatrick const char *python_function_name = wp_option_data->script_source.c_str(); 2268061da546Spatrick 2269061da546Spatrick if (!context) 2270061da546Spatrick return true; 2271061da546Spatrick 2272061da546Spatrick ExecutionContext exe_ctx(context->exe_ctx_ref); 2273061da546Spatrick Target *target = exe_ctx.GetTargetPtr(); 2274061da546Spatrick 2275061da546Spatrick if (!target) 2276061da546Spatrick return true; 2277061da546Spatrick 2278061da546Spatrick Debugger &debugger = target->GetDebugger(); 2279061da546Spatrick ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter(); 2280061da546Spatrick ScriptInterpreterPythonImpl *python_interpreter = 2281061da546Spatrick (ScriptInterpreterPythonImpl *)script_interpreter; 2282061da546Spatrick 2283061da546Spatrick if (!script_interpreter) 2284061da546Spatrick return true; 2285061da546Spatrick 2286061da546Spatrick if (python_function_name && python_function_name[0]) { 2287061da546Spatrick const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP()); 2288061da546Spatrick WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id); 2289061da546Spatrick if (wp_sp) { 2290061da546Spatrick if (stop_frame_sp && wp_sp) { 2291061da546Spatrick bool ret_val = true; 2292061da546Spatrick { 2293061da546Spatrick Locker py_lock(python_interpreter, Locker::AcquireLock | 2294061da546Spatrick Locker::InitSession | 2295061da546Spatrick Locker::NoSTDIN); 2296061da546Spatrick ret_val = LLDBSwigPythonWatchpointCallbackFunction( 2297061da546Spatrick python_function_name, 2298061da546Spatrick python_interpreter->m_dictionary_name.c_str(), stop_frame_sp, 2299061da546Spatrick wp_sp); 2300061da546Spatrick } 2301061da546Spatrick return ret_val; 2302061da546Spatrick } 2303061da546Spatrick } 2304061da546Spatrick } 2305061da546Spatrick // We currently always true so we stop in case anything goes wrong when 2306061da546Spatrick // trying to call the script function 2307061da546Spatrick return true; 2308061da546Spatrick } 2309061da546Spatrick 2310061da546Spatrick size_t ScriptInterpreterPythonImpl::CalculateNumChildren( 2311061da546Spatrick const StructuredData::ObjectSP &implementor_sp, uint32_t max) { 2312061da546Spatrick if (!implementor_sp) 2313061da546Spatrick return 0; 2314061da546Spatrick StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 2315061da546Spatrick if (!generic) 2316061da546Spatrick return 0; 2317061da546Spatrick void *implementor = generic->GetValue(); 2318061da546Spatrick if (!implementor) 2319061da546Spatrick return 0; 2320061da546Spatrick 2321061da546Spatrick size_t ret_val = 0; 2322061da546Spatrick 2323061da546Spatrick { 2324061da546Spatrick Locker py_lock(this, 2325061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2326061da546Spatrick ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max); 2327061da546Spatrick } 2328061da546Spatrick 2329061da546Spatrick return ret_val; 2330061da546Spatrick } 2331061da546Spatrick 2332061da546Spatrick lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex( 2333061da546Spatrick const StructuredData::ObjectSP &implementor_sp, uint32_t idx) { 2334061da546Spatrick if (!implementor_sp) 2335061da546Spatrick return lldb::ValueObjectSP(); 2336061da546Spatrick 2337061da546Spatrick StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 2338061da546Spatrick if (!generic) 2339061da546Spatrick return lldb::ValueObjectSP(); 2340061da546Spatrick void *implementor = generic->GetValue(); 2341061da546Spatrick if (!implementor) 2342061da546Spatrick return lldb::ValueObjectSP(); 2343061da546Spatrick 2344061da546Spatrick lldb::ValueObjectSP ret_val; 2345061da546Spatrick { 2346061da546Spatrick Locker py_lock(this, 2347061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2348061da546Spatrick void *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx); 2349061da546Spatrick if (child_ptr != nullptr && child_ptr != Py_None) { 2350061da546Spatrick lldb::SBValue *sb_value_ptr = 2351061da546Spatrick (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr); 2352061da546Spatrick if (sb_value_ptr == nullptr) 2353061da546Spatrick Py_XDECREF(child_ptr); 2354061da546Spatrick else 2355061da546Spatrick ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); 2356061da546Spatrick } else { 2357061da546Spatrick Py_XDECREF(child_ptr); 2358061da546Spatrick } 2359061da546Spatrick } 2360061da546Spatrick 2361061da546Spatrick return ret_val; 2362061da546Spatrick } 2363061da546Spatrick 2364061da546Spatrick int ScriptInterpreterPythonImpl::GetIndexOfChildWithName( 2365061da546Spatrick const StructuredData::ObjectSP &implementor_sp, const char *child_name) { 2366061da546Spatrick if (!implementor_sp) 2367061da546Spatrick return UINT32_MAX; 2368061da546Spatrick 2369061da546Spatrick StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 2370061da546Spatrick if (!generic) 2371061da546Spatrick return UINT32_MAX; 2372061da546Spatrick void *implementor = generic->GetValue(); 2373061da546Spatrick if (!implementor) 2374061da546Spatrick return UINT32_MAX; 2375061da546Spatrick 2376061da546Spatrick int ret_val = UINT32_MAX; 2377061da546Spatrick 2378061da546Spatrick { 2379061da546Spatrick Locker py_lock(this, 2380061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2381061da546Spatrick ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name); 2382061da546Spatrick } 2383061da546Spatrick 2384061da546Spatrick return ret_val; 2385061da546Spatrick } 2386061da546Spatrick 2387061da546Spatrick bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance( 2388061da546Spatrick const StructuredData::ObjectSP &implementor_sp) { 2389061da546Spatrick bool ret_val = false; 2390061da546Spatrick 2391061da546Spatrick if (!implementor_sp) 2392061da546Spatrick return ret_val; 2393061da546Spatrick 2394061da546Spatrick StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 2395061da546Spatrick if (!generic) 2396061da546Spatrick return ret_val; 2397061da546Spatrick void *implementor = generic->GetValue(); 2398061da546Spatrick if (!implementor) 2399061da546Spatrick return ret_val; 2400061da546Spatrick 2401061da546Spatrick { 2402061da546Spatrick Locker py_lock(this, 2403061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2404061da546Spatrick ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor); 2405061da546Spatrick } 2406061da546Spatrick 2407061da546Spatrick return ret_val; 2408061da546Spatrick } 2409061da546Spatrick 2410061da546Spatrick bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance( 2411061da546Spatrick const StructuredData::ObjectSP &implementor_sp) { 2412061da546Spatrick bool ret_val = false; 2413061da546Spatrick 2414061da546Spatrick if (!implementor_sp) 2415061da546Spatrick return ret_val; 2416061da546Spatrick 2417061da546Spatrick StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 2418061da546Spatrick if (!generic) 2419061da546Spatrick return ret_val; 2420061da546Spatrick void *implementor = generic->GetValue(); 2421061da546Spatrick if (!implementor) 2422061da546Spatrick return ret_val; 2423061da546Spatrick 2424061da546Spatrick { 2425061da546Spatrick Locker py_lock(this, 2426061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2427061da546Spatrick ret_val = 2428061da546Spatrick LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor); 2429061da546Spatrick } 2430061da546Spatrick 2431061da546Spatrick return ret_val; 2432061da546Spatrick } 2433061da546Spatrick 2434061da546Spatrick lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue( 2435061da546Spatrick const StructuredData::ObjectSP &implementor_sp) { 2436061da546Spatrick lldb::ValueObjectSP ret_val(nullptr); 2437061da546Spatrick 2438061da546Spatrick if (!implementor_sp) 2439061da546Spatrick return ret_val; 2440061da546Spatrick 2441061da546Spatrick StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 2442061da546Spatrick if (!generic) 2443061da546Spatrick return ret_val; 2444061da546Spatrick void *implementor = generic->GetValue(); 2445061da546Spatrick if (!implementor) 2446061da546Spatrick return ret_val; 2447061da546Spatrick 2448061da546Spatrick { 2449061da546Spatrick Locker py_lock(this, 2450061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2451061da546Spatrick void *child_ptr = LLDBSwigPython_GetValueSynthProviderInstance(implementor); 2452061da546Spatrick if (child_ptr != nullptr && child_ptr != Py_None) { 2453061da546Spatrick lldb::SBValue *sb_value_ptr = 2454061da546Spatrick (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr); 2455061da546Spatrick if (sb_value_ptr == nullptr) 2456061da546Spatrick Py_XDECREF(child_ptr); 2457061da546Spatrick else 2458061da546Spatrick ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); 2459061da546Spatrick } else { 2460061da546Spatrick Py_XDECREF(child_ptr); 2461061da546Spatrick } 2462061da546Spatrick } 2463061da546Spatrick 2464061da546Spatrick return ret_val; 2465061da546Spatrick } 2466061da546Spatrick 2467061da546Spatrick ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName( 2468061da546Spatrick const StructuredData::ObjectSP &implementor_sp) { 2469061da546Spatrick Locker py_lock(this, 2470061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2471061da546Spatrick 2472061da546Spatrick static char callee_name[] = "get_type_name"; 2473061da546Spatrick 2474061da546Spatrick ConstString ret_val; 2475061da546Spatrick bool got_string = false; 2476061da546Spatrick std::string buffer; 2477061da546Spatrick 2478061da546Spatrick if (!implementor_sp) 2479061da546Spatrick return ret_val; 2480061da546Spatrick 2481061da546Spatrick StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 2482061da546Spatrick if (!generic) 2483061da546Spatrick return ret_val; 2484061da546Spatrick PythonObject implementor(PyRefType::Borrowed, 2485061da546Spatrick (PyObject *)generic->GetValue()); 2486061da546Spatrick if (!implementor.IsAllocated()) 2487061da546Spatrick return ret_val; 2488061da546Spatrick 2489061da546Spatrick PythonObject pmeth(PyRefType::Owned, 2490061da546Spatrick PyObject_GetAttrString(implementor.get(), callee_name)); 2491061da546Spatrick 2492061da546Spatrick if (PyErr_Occurred()) 2493061da546Spatrick PyErr_Clear(); 2494061da546Spatrick 2495061da546Spatrick if (!pmeth.IsAllocated()) 2496061da546Spatrick return ret_val; 2497061da546Spatrick 2498061da546Spatrick if (PyCallable_Check(pmeth.get()) == 0) { 2499061da546Spatrick if (PyErr_Occurred()) 2500061da546Spatrick PyErr_Clear(); 2501061da546Spatrick return ret_val; 2502061da546Spatrick } 2503061da546Spatrick 2504061da546Spatrick if (PyErr_Occurred()) 2505061da546Spatrick PyErr_Clear(); 2506061da546Spatrick 2507061da546Spatrick // right now we know this function exists and is callable.. 2508061da546Spatrick PythonObject py_return( 2509061da546Spatrick PyRefType::Owned, 2510061da546Spatrick PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 2511061da546Spatrick 2512061da546Spatrick // if it fails, print the error but otherwise go on 2513061da546Spatrick if (PyErr_Occurred()) { 2514061da546Spatrick PyErr_Print(); 2515061da546Spatrick PyErr_Clear(); 2516061da546Spatrick } 2517061da546Spatrick 2518061da546Spatrick if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { 2519061da546Spatrick PythonString py_string(PyRefType::Borrowed, py_return.get()); 2520061da546Spatrick llvm::StringRef return_data(py_string.GetString()); 2521061da546Spatrick if (!return_data.empty()) { 2522061da546Spatrick buffer.assign(return_data.data(), return_data.size()); 2523061da546Spatrick got_string = true; 2524061da546Spatrick } 2525061da546Spatrick } 2526061da546Spatrick 2527061da546Spatrick if (got_string) 2528061da546Spatrick ret_val.SetCStringWithLength(buffer.c_str(), buffer.size()); 2529061da546Spatrick 2530061da546Spatrick return ret_val; 2531061da546Spatrick } 2532061da546Spatrick 2533061da546Spatrick bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 2534061da546Spatrick const char *impl_function, Process *process, std::string &output, 2535061da546Spatrick Status &error) { 2536061da546Spatrick bool ret_val; 2537061da546Spatrick if (!process) { 2538061da546Spatrick error.SetErrorString("no process"); 2539061da546Spatrick return false; 2540061da546Spatrick } 2541061da546Spatrick if (!impl_function || !impl_function[0]) { 2542061da546Spatrick error.SetErrorString("no function to execute"); 2543061da546Spatrick return false; 2544061da546Spatrick } 2545061da546Spatrick 2546061da546Spatrick { 2547061da546Spatrick ProcessSP process_sp(process->shared_from_this()); 2548061da546Spatrick Locker py_lock(this, 2549061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2550061da546Spatrick ret_val = LLDBSWIGPythonRunScriptKeywordProcess( 2551061da546Spatrick impl_function, m_dictionary_name.c_str(), process_sp, output); 2552061da546Spatrick if (!ret_val) 2553061da546Spatrick error.SetErrorString("python script evaluation failed"); 2554061da546Spatrick } 2555061da546Spatrick return ret_val; 2556061da546Spatrick } 2557061da546Spatrick 2558061da546Spatrick bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 2559061da546Spatrick const char *impl_function, Thread *thread, std::string &output, 2560061da546Spatrick Status &error) { 2561061da546Spatrick bool ret_val; 2562061da546Spatrick if (!thread) { 2563061da546Spatrick error.SetErrorString("no thread"); 2564061da546Spatrick return false; 2565061da546Spatrick } 2566061da546Spatrick if (!impl_function || !impl_function[0]) { 2567061da546Spatrick error.SetErrorString("no function to execute"); 2568061da546Spatrick return false; 2569061da546Spatrick } 2570061da546Spatrick 2571061da546Spatrick { 2572061da546Spatrick ThreadSP thread_sp(thread->shared_from_this()); 2573061da546Spatrick Locker py_lock(this, 2574061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2575061da546Spatrick ret_val = LLDBSWIGPythonRunScriptKeywordThread( 2576061da546Spatrick impl_function, m_dictionary_name.c_str(), thread_sp, output); 2577061da546Spatrick if (!ret_val) 2578061da546Spatrick error.SetErrorString("python script evaluation failed"); 2579061da546Spatrick } 2580061da546Spatrick return ret_val; 2581061da546Spatrick } 2582061da546Spatrick 2583061da546Spatrick bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 2584061da546Spatrick const char *impl_function, Target *target, std::string &output, 2585061da546Spatrick Status &error) { 2586061da546Spatrick bool ret_val; 2587061da546Spatrick if (!target) { 2588061da546Spatrick error.SetErrorString("no thread"); 2589061da546Spatrick return false; 2590061da546Spatrick } 2591061da546Spatrick if (!impl_function || !impl_function[0]) { 2592061da546Spatrick error.SetErrorString("no function to execute"); 2593061da546Spatrick return false; 2594061da546Spatrick } 2595061da546Spatrick 2596061da546Spatrick { 2597061da546Spatrick TargetSP target_sp(target->shared_from_this()); 2598061da546Spatrick Locker py_lock(this, 2599061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2600061da546Spatrick ret_val = LLDBSWIGPythonRunScriptKeywordTarget( 2601061da546Spatrick impl_function, m_dictionary_name.c_str(), target_sp, output); 2602061da546Spatrick if (!ret_val) 2603061da546Spatrick error.SetErrorString("python script evaluation failed"); 2604061da546Spatrick } 2605061da546Spatrick return ret_val; 2606061da546Spatrick } 2607061da546Spatrick 2608061da546Spatrick bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 2609061da546Spatrick const char *impl_function, StackFrame *frame, std::string &output, 2610061da546Spatrick Status &error) { 2611061da546Spatrick bool ret_val; 2612061da546Spatrick if (!frame) { 2613061da546Spatrick error.SetErrorString("no frame"); 2614061da546Spatrick return false; 2615061da546Spatrick } 2616061da546Spatrick if (!impl_function || !impl_function[0]) { 2617061da546Spatrick error.SetErrorString("no function to execute"); 2618061da546Spatrick return false; 2619061da546Spatrick } 2620061da546Spatrick 2621061da546Spatrick { 2622061da546Spatrick StackFrameSP frame_sp(frame->shared_from_this()); 2623061da546Spatrick Locker py_lock(this, 2624061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2625061da546Spatrick ret_val = LLDBSWIGPythonRunScriptKeywordFrame( 2626061da546Spatrick impl_function, m_dictionary_name.c_str(), frame_sp, output); 2627061da546Spatrick if (!ret_val) 2628061da546Spatrick error.SetErrorString("python script evaluation failed"); 2629061da546Spatrick } 2630061da546Spatrick return ret_val; 2631061da546Spatrick } 2632061da546Spatrick 2633061da546Spatrick bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( 2634061da546Spatrick const char *impl_function, ValueObject *value, std::string &output, 2635061da546Spatrick Status &error) { 2636061da546Spatrick bool ret_val; 2637061da546Spatrick if (!value) { 2638061da546Spatrick error.SetErrorString("no value"); 2639061da546Spatrick return false; 2640061da546Spatrick } 2641061da546Spatrick if (!impl_function || !impl_function[0]) { 2642061da546Spatrick error.SetErrorString("no function to execute"); 2643061da546Spatrick return false; 2644061da546Spatrick } 2645061da546Spatrick 2646061da546Spatrick { 2647061da546Spatrick ValueObjectSP value_sp(value->GetSP()); 2648061da546Spatrick Locker py_lock(this, 2649061da546Spatrick Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2650061da546Spatrick ret_val = LLDBSWIGPythonRunScriptKeywordValue( 2651061da546Spatrick impl_function, m_dictionary_name.c_str(), value_sp, output); 2652061da546Spatrick if (!ret_val) 2653061da546Spatrick error.SetErrorString("python script evaluation failed"); 2654061da546Spatrick } 2655061da546Spatrick return ret_val; 2656061da546Spatrick } 2657061da546Spatrick 2658061da546Spatrick uint64_t replace_all(std::string &str, const std::string &oldStr, 2659061da546Spatrick const std::string &newStr) { 2660061da546Spatrick size_t pos = 0; 2661061da546Spatrick uint64_t matches = 0; 2662061da546Spatrick while ((pos = str.find(oldStr, pos)) != std::string::npos) { 2663061da546Spatrick matches++; 2664061da546Spatrick str.replace(pos, oldStr.length(), newStr); 2665061da546Spatrick pos += newStr.length(); 2666061da546Spatrick } 2667061da546Spatrick return matches; 2668061da546Spatrick } 2669061da546Spatrick 2670061da546Spatrick bool ScriptInterpreterPythonImpl::LoadScriptingModule( 2671061da546Spatrick const char *pathname, bool init_session, lldb_private::Status &error, 2672061da546Spatrick StructuredData::ObjectSP *module_sp) { 2673061da546Spatrick if (!pathname || !pathname[0]) { 2674061da546Spatrick error.SetErrorString("invalid pathname"); 2675061da546Spatrick return false; 2676061da546Spatrick } 2677061da546Spatrick 2678061da546Spatrick lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); 2679061da546Spatrick 2680061da546Spatrick { 2681061da546Spatrick FileSpec target_file(pathname); 2682061da546Spatrick FileSystem::Instance().Resolve(target_file); 2683*dda28197Spatrick FileSystem::Instance().Collect(target_file); 2684061da546Spatrick std::string basename(target_file.GetFilename().GetCString()); 2685061da546Spatrick 2686061da546Spatrick StreamString command_stream; 2687061da546Spatrick 2688061da546Spatrick // Before executing Python code, lock the GIL. 2689061da546Spatrick Locker py_lock(this, 2690061da546Spatrick Locker::AcquireLock | 2691061da546Spatrick (init_session ? Locker::InitSession : 0) | 2692061da546Spatrick Locker::NoSTDIN, 2693061da546Spatrick Locker::FreeAcquiredLock | 2694061da546Spatrick (init_session ? Locker::TearDownSession : 0)); 2695061da546Spatrick namespace fs = llvm::sys::fs; 2696061da546Spatrick fs::file_status st; 2697061da546Spatrick std::error_code ec = status(target_file.GetPath(), st); 2698061da546Spatrick 2699061da546Spatrick if (ec || st.type() == fs::file_type::status_error || 2700061da546Spatrick st.type() == fs::file_type::type_unknown || 2701061da546Spatrick st.type() == fs::file_type::file_not_found) { 2702061da546Spatrick // if not a valid file of any sort, check if it might be a filename still 2703061da546Spatrick // dot can't be used but / and \ can, and if either is found, reject 2704061da546Spatrick if (strchr(pathname, '\\') || strchr(pathname, '/')) { 2705061da546Spatrick error.SetErrorString("invalid pathname"); 2706061da546Spatrick return false; 2707061da546Spatrick } 2708061da546Spatrick basename = pathname; // not a filename, probably a package of some sort, 2709061da546Spatrick // let it go through 2710061da546Spatrick } else if (is_directory(st) || is_regular_file(st)) { 2711061da546Spatrick if (target_file.GetDirectory().IsEmpty()) { 2712061da546Spatrick error.SetErrorString("invalid directory name"); 2713061da546Spatrick return false; 2714061da546Spatrick } 2715061da546Spatrick 2716061da546Spatrick std::string directory = target_file.GetDirectory().GetCString(); 2717061da546Spatrick replace_all(directory, "\\", "\\\\"); 2718061da546Spatrick replace_all(directory, "'", "\\'"); 2719061da546Spatrick 2720061da546Spatrick // now make sure that Python has "directory" in the search path 2721061da546Spatrick StreamString command_stream; 2722061da546Spatrick command_stream.Printf("if not (sys.path.__contains__('%s')):\n " 2723061da546Spatrick "sys.path.insert(1,'%s');\n\n", 2724061da546Spatrick directory.c_str(), directory.c_str()); 2725061da546Spatrick bool syspath_retval = 2726061da546Spatrick ExecuteMultipleLines(command_stream.GetData(), 2727061da546Spatrick ScriptInterpreter::ExecuteScriptOptions() 2728061da546Spatrick .SetEnableIO(false) 2729061da546Spatrick .SetSetLLDBGlobals(false)) 2730061da546Spatrick .Success(); 2731061da546Spatrick if (!syspath_retval) { 2732061da546Spatrick error.SetErrorString("Python sys.path handling failed"); 2733061da546Spatrick return false; 2734061da546Spatrick } 2735061da546Spatrick 2736061da546Spatrick // strip .py or .pyc extension 2737061da546Spatrick ConstString extension = target_file.GetFileNameExtension(); 2738061da546Spatrick if (extension) { 2739061da546Spatrick if (llvm::StringRef(extension.GetCString()) == ".py") 2740061da546Spatrick basename.resize(basename.length() - 3); 2741061da546Spatrick else if (llvm::StringRef(extension.GetCString()) == ".pyc") 2742061da546Spatrick basename.resize(basename.length() - 4); 2743061da546Spatrick } 2744061da546Spatrick } else { 2745061da546Spatrick error.SetErrorString("no known way to import this module specification"); 2746061da546Spatrick return false; 2747061da546Spatrick } 2748061da546Spatrick 2749061da546Spatrick // check if the module is already import-ed 2750061da546Spatrick command_stream.Clear(); 2751061da546Spatrick command_stream.Printf("sys.modules.__contains__('%s')", basename.c_str()); 2752061da546Spatrick bool does_contain = false; 2753061da546Spatrick // this call will succeed if the module was ever imported in any Debugger 2754061da546Spatrick // in the lifetime of the process in which this LLDB framework is living 2755061da546Spatrick bool was_imported_globally = 2756061da546Spatrick (ExecuteOneLineWithReturn( 2757061da546Spatrick command_stream.GetData(), 2758061da546Spatrick ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, 2759061da546Spatrick ScriptInterpreter::ExecuteScriptOptions() 2760061da546Spatrick .SetEnableIO(false) 2761061da546Spatrick .SetSetLLDBGlobals(false)) && 2762061da546Spatrick does_contain); 2763061da546Spatrick // this call will fail if the module was not imported in this Debugger 2764061da546Spatrick // before 2765061da546Spatrick command_stream.Clear(); 2766061da546Spatrick command_stream.Printf("sys.getrefcount(%s)", basename.c_str()); 2767061da546Spatrick bool was_imported_locally = GetSessionDictionary() 2768061da546Spatrick .GetItemForKey(PythonString(basename)) 2769061da546Spatrick .IsAllocated(); 2770061da546Spatrick 2771061da546Spatrick bool was_imported = (was_imported_globally || was_imported_locally); 2772061da546Spatrick 2773061da546Spatrick // now actually do the import 2774061da546Spatrick command_stream.Clear(); 2775061da546Spatrick 2776061da546Spatrick if (was_imported) { 2777061da546Spatrick if (!was_imported_locally) 2778061da546Spatrick command_stream.Printf("import %s ; reload_module(%s)", basename.c_str(), 2779061da546Spatrick basename.c_str()); 2780061da546Spatrick else 2781061da546Spatrick command_stream.Printf("reload_module(%s)", basename.c_str()); 2782061da546Spatrick } else 2783061da546Spatrick command_stream.Printf("import %s", basename.c_str()); 2784061da546Spatrick 2785061da546Spatrick error = ExecuteMultipleLines(command_stream.GetData(), 2786061da546Spatrick ScriptInterpreter::ExecuteScriptOptions() 2787061da546Spatrick .SetEnableIO(false) 2788061da546Spatrick .SetSetLLDBGlobals(false)); 2789061da546Spatrick if (error.Fail()) 2790061da546Spatrick return false; 2791061da546Spatrick 2792061da546Spatrick // if we are here, everything worked 2793061da546Spatrick // call __lldb_init_module(debugger,dict) 2794061da546Spatrick if (!LLDBSwigPythonCallModuleInit(basename.c_str(), 2795061da546Spatrick m_dictionary_name.c_str(), debugger_sp)) { 2796061da546Spatrick error.SetErrorString("calling __lldb_init_module failed"); 2797061da546Spatrick return false; 2798061da546Spatrick } 2799061da546Spatrick 2800061da546Spatrick if (module_sp) { 2801061da546Spatrick // everything went just great, now set the module object 2802061da546Spatrick command_stream.Clear(); 2803061da546Spatrick command_stream.Printf("%s", basename.c_str()); 2804061da546Spatrick void *module_pyobj = nullptr; 2805061da546Spatrick if (ExecuteOneLineWithReturn( 2806061da546Spatrick command_stream.GetData(), 2807061da546Spatrick ScriptInterpreter::eScriptReturnTypeOpaqueObject, 2808061da546Spatrick &module_pyobj) && 2809061da546Spatrick module_pyobj) 2810061da546Spatrick *module_sp = std::make_shared<StructuredPythonObject>(module_pyobj); 2811061da546Spatrick } 2812061da546Spatrick 2813061da546Spatrick return true; 2814061da546Spatrick } 2815061da546Spatrick } 2816061da546Spatrick 2817061da546Spatrick bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) { 2818061da546Spatrick if (!word || !word[0]) 2819061da546Spatrick return false; 2820061da546Spatrick 2821061da546Spatrick llvm::StringRef word_sr(word); 2822061da546Spatrick 2823061da546Spatrick // filter out a few characters that would just confuse us and that are 2824061da546Spatrick // clearly not keyword material anyway 2825061da546Spatrick if (word_sr.find('"') != llvm::StringRef::npos || 2826061da546Spatrick word_sr.find('\'') != llvm::StringRef::npos) 2827061da546Spatrick return false; 2828061da546Spatrick 2829061da546Spatrick StreamString command_stream; 2830061da546Spatrick command_stream.Printf("keyword.iskeyword('%s')", word); 2831061da546Spatrick bool result; 2832061da546Spatrick ExecuteScriptOptions options; 2833061da546Spatrick options.SetEnableIO(false); 2834061da546Spatrick options.SetMaskoutErrors(true); 2835061da546Spatrick options.SetSetLLDBGlobals(false); 2836061da546Spatrick if (ExecuteOneLineWithReturn(command_stream.GetData(), 2837061da546Spatrick ScriptInterpreter::eScriptReturnTypeBool, 2838061da546Spatrick &result, options)) 2839061da546Spatrick return result; 2840061da546Spatrick return false; 2841061da546Spatrick } 2842061da546Spatrick 2843061da546Spatrick ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler( 2844061da546Spatrick lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro) 2845061da546Spatrick : m_debugger_sp(debugger_sp), m_synch_wanted(synchro), 2846061da546Spatrick m_old_asynch(debugger_sp->GetAsyncExecution()) { 2847061da546Spatrick if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous) 2848061da546Spatrick m_debugger_sp->SetAsyncExecution(false); 2849061da546Spatrick else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous) 2850061da546Spatrick m_debugger_sp->SetAsyncExecution(true); 2851061da546Spatrick } 2852061da546Spatrick 2853061da546Spatrick ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() { 2854061da546Spatrick if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue) 2855061da546Spatrick m_debugger_sp->SetAsyncExecution(m_old_asynch); 2856061da546Spatrick } 2857061da546Spatrick 2858061da546Spatrick bool ScriptInterpreterPythonImpl::RunScriptBasedCommand( 2859061da546Spatrick const char *impl_function, llvm::StringRef args, 2860061da546Spatrick ScriptedCommandSynchronicity synchronicity, 2861061da546Spatrick lldb_private::CommandReturnObject &cmd_retobj, Status &error, 2862061da546Spatrick const lldb_private::ExecutionContext &exe_ctx) { 2863061da546Spatrick if (!impl_function) { 2864061da546Spatrick error.SetErrorString("no function to execute"); 2865061da546Spatrick return false; 2866061da546Spatrick } 2867061da546Spatrick 2868061da546Spatrick lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); 2869061da546Spatrick lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); 2870061da546Spatrick 2871061da546Spatrick if (!debugger_sp.get()) { 2872061da546Spatrick error.SetErrorString("invalid Debugger pointer"); 2873061da546Spatrick return false; 2874061da546Spatrick } 2875061da546Spatrick 2876061da546Spatrick bool ret_val = false; 2877061da546Spatrick 2878061da546Spatrick std::string err_msg; 2879061da546Spatrick 2880061da546Spatrick { 2881061da546Spatrick Locker py_lock(this, 2882061da546Spatrick Locker::AcquireLock | Locker::InitSession | 2883061da546Spatrick (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN), 2884061da546Spatrick Locker::FreeLock | Locker::TearDownSession); 2885061da546Spatrick 2886061da546Spatrick SynchronicityHandler synch_handler(debugger_sp, synchronicity); 2887061da546Spatrick 2888061da546Spatrick std::string args_str = args.str(); 2889061da546Spatrick ret_val = LLDBSwigPythonCallCommand( 2890061da546Spatrick impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(), 2891061da546Spatrick cmd_retobj, exe_ctx_ref_sp); 2892061da546Spatrick } 2893061da546Spatrick 2894061da546Spatrick if (!ret_val) 2895061da546Spatrick error.SetErrorString("unable to execute script function"); 2896061da546Spatrick else 2897061da546Spatrick error.Clear(); 2898061da546Spatrick 2899061da546Spatrick return ret_val; 2900061da546Spatrick } 2901061da546Spatrick 2902061da546Spatrick bool ScriptInterpreterPythonImpl::RunScriptBasedCommand( 2903061da546Spatrick StructuredData::GenericSP impl_obj_sp, llvm::StringRef args, 2904061da546Spatrick ScriptedCommandSynchronicity synchronicity, 2905061da546Spatrick lldb_private::CommandReturnObject &cmd_retobj, Status &error, 2906061da546Spatrick const lldb_private::ExecutionContext &exe_ctx) { 2907061da546Spatrick if (!impl_obj_sp || !impl_obj_sp->IsValid()) { 2908061da546Spatrick error.SetErrorString("no function to execute"); 2909061da546Spatrick return false; 2910061da546Spatrick } 2911061da546Spatrick 2912061da546Spatrick lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); 2913061da546Spatrick lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); 2914061da546Spatrick 2915061da546Spatrick if (!debugger_sp.get()) { 2916061da546Spatrick error.SetErrorString("invalid Debugger pointer"); 2917061da546Spatrick return false; 2918061da546Spatrick } 2919061da546Spatrick 2920061da546Spatrick bool ret_val = false; 2921061da546Spatrick 2922061da546Spatrick std::string err_msg; 2923061da546Spatrick 2924061da546Spatrick { 2925061da546Spatrick Locker py_lock(this, 2926061da546Spatrick Locker::AcquireLock | Locker::InitSession | 2927061da546Spatrick (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN), 2928061da546Spatrick Locker::FreeLock | Locker::TearDownSession); 2929061da546Spatrick 2930061da546Spatrick SynchronicityHandler synch_handler(debugger_sp, synchronicity); 2931061da546Spatrick 2932061da546Spatrick std::string args_str = args.str(); 2933061da546Spatrick ret_val = LLDBSwigPythonCallCommandObject(impl_obj_sp->GetValue(), 2934061da546Spatrick debugger_sp, args_str.c_str(), 2935061da546Spatrick cmd_retobj, exe_ctx_ref_sp); 2936061da546Spatrick } 2937061da546Spatrick 2938061da546Spatrick if (!ret_val) 2939061da546Spatrick error.SetErrorString("unable to execute script function"); 2940061da546Spatrick else 2941061da546Spatrick error.Clear(); 2942061da546Spatrick 2943061da546Spatrick return ret_val; 2944061da546Spatrick } 2945061da546Spatrick 2946*dda28197Spatrick /// In Python, a special attribute __doc__ contains the docstring for an object 2947*dda28197Spatrick /// (function, method, class, ...) if any is defined Otherwise, the attribute's 2948*dda28197Spatrick /// value is None. 2949061da546Spatrick bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item, 2950061da546Spatrick std::string &dest) { 2951061da546Spatrick dest.clear(); 2952*dda28197Spatrick 2953061da546Spatrick if (!item || !*item) 2954061da546Spatrick return false; 2955*dda28197Spatrick 2956061da546Spatrick std::string command(item); 2957061da546Spatrick command += ".__doc__"; 2958061da546Spatrick 2959*dda28197Spatrick // Python is going to point this to valid data if ExecuteOneLineWithReturn 2960*dda28197Spatrick // returns successfully. 2961*dda28197Spatrick char *result_ptr = nullptr; 2962061da546Spatrick 2963061da546Spatrick if (ExecuteOneLineWithReturn( 2964*dda28197Spatrick command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone, 2965061da546Spatrick &result_ptr, 2966061da546Spatrick ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false))) { 2967061da546Spatrick if (result_ptr) 2968061da546Spatrick dest.assign(result_ptr); 2969061da546Spatrick return true; 2970061da546Spatrick } 2971*dda28197Spatrick 2972*dda28197Spatrick StreamString str_stream; 2973*dda28197Spatrick str_stream << "Function " << item 2974*dda28197Spatrick << " was not found. Containing module might be missing."; 2975*dda28197Spatrick dest = std::string(str_stream.GetString()); 2976*dda28197Spatrick 2977*dda28197Spatrick return false; 2978061da546Spatrick } 2979061da546Spatrick 2980061da546Spatrick bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject( 2981061da546Spatrick StructuredData::GenericSP cmd_obj_sp, std::string &dest) { 2982061da546Spatrick dest.clear(); 2983061da546Spatrick 2984061da546Spatrick Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 2985061da546Spatrick 2986061da546Spatrick static char callee_name[] = "get_short_help"; 2987061da546Spatrick 2988061da546Spatrick if (!cmd_obj_sp) 2989061da546Spatrick return false; 2990061da546Spatrick 2991061da546Spatrick PythonObject implementor(PyRefType::Borrowed, 2992061da546Spatrick (PyObject *)cmd_obj_sp->GetValue()); 2993061da546Spatrick 2994061da546Spatrick if (!implementor.IsAllocated()) 2995061da546Spatrick return false; 2996061da546Spatrick 2997061da546Spatrick PythonObject pmeth(PyRefType::Owned, 2998061da546Spatrick PyObject_GetAttrString(implementor.get(), callee_name)); 2999061da546Spatrick 3000061da546Spatrick if (PyErr_Occurred()) 3001061da546Spatrick PyErr_Clear(); 3002061da546Spatrick 3003061da546Spatrick if (!pmeth.IsAllocated()) 3004061da546Spatrick return false; 3005061da546Spatrick 3006061da546Spatrick if (PyCallable_Check(pmeth.get()) == 0) { 3007061da546Spatrick if (PyErr_Occurred()) 3008061da546Spatrick PyErr_Clear(); 3009061da546Spatrick return false; 3010061da546Spatrick } 3011061da546Spatrick 3012061da546Spatrick if (PyErr_Occurred()) 3013061da546Spatrick PyErr_Clear(); 3014061da546Spatrick 3015*dda28197Spatrick // Right now we know this function exists and is callable. 3016061da546Spatrick PythonObject py_return( 3017061da546Spatrick PyRefType::Owned, 3018061da546Spatrick PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 3019061da546Spatrick 3020*dda28197Spatrick // If it fails, print the error but otherwise go on. 3021061da546Spatrick if (PyErr_Occurred()) { 3022061da546Spatrick PyErr_Print(); 3023061da546Spatrick PyErr_Clear(); 3024061da546Spatrick } 3025061da546Spatrick 3026061da546Spatrick if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { 3027061da546Spatrick PythonString py_string(PyRefType::Borrowed, py_return.get()); 3028061da546Spatrick llvm::StringRef return_data(py_string.GetString()); 3029061da546Spatrick dest.assign(return_data.data(), return_data.size()); 3030*dda28197Spatrick return true; 3031061da546Spatrick } 3032*dda28197Spatrick 3033*dda28197Spatrick return false; 3034061da546Spatrick } 3035061da546Spatrick 3036061da546Spatrick uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject( 3037061da546Spatrick StructuredData::GenericSP cmd_obj_sp) { 3038061da546Spatrick uint32_t result = 0; 3039061da546Spatrick 3040061da546Spatrick Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 3041061da546Spatrick 3042061da546Spatrick static char callee_name[] = "get_flags"; 3043061da546Spatrick 3044061da546Spatrick if (!cmd_obj_sp) 3045061da546Spatrick return result; 3046061da546Spatrick 3047061da546Spatrick PythonObject implementor(PyRefType::Borrowed, 3048061da546Spatrick (PyObject *)cmd_obj_sp->GetValue()); 3049061da546Spatrick 3050061da546Spatrick if (!implementor.IsAllocated()) 3051061da546Spatrick return result; 3052061da546Spatrick 3053061da546Spatrick PythonObject pmeth(PyRefType::Owned, 3054061da546Spatrick PyObject_GetAttrString(implementor.get(), callee_name)); 3055061da546Spatrick 3056061da546Spatrick if (PyErr_Occurred()) 3057061da546Spatrick PyErr_Clear(); 3058061da546Spatrick 3059061da546Spatrick if (!pmeth.IsAllocated()) 3060061da546Spatrick return result; 3061061da546Spatrick 3062061da546Spatrick if (PyCallable_Check(pmeth.get()) == 0) { 3063061da546Spatrick if (PyErr_Occurred()) 3064061da546Spatrick PyErr_Clear(); 3065061da546Spatrick return result; 3066061da546Spatrick } 3067061da546Spatrick 3068061da546Spatrick if (PyErr_Occurred()) 3069061da546Spatrick PyErr_Clear(); 3070061da546Spatrick 3071*dda28197Spatrick long long py_return = unwrapOrSetPythonException( 3072*dda28197Spatrick As<long long>(implementor.CallMethod(callee_name))); 3073061da546Spatrick 3074061da546Spatrick // if it fails, print the error but otherwise go on 3075061da546Spatrick if (PyErr_Occurred()) { 3076061da546Spatrick PyErr_Print(); 3077061da546Spatrick PyErr_Clear(); 3078*dda28197Spatrick } else { 3079*dda28197Spatrick result = py_return; 3080061da546Spatrick } 3081061da546Spatrick 3082061da546Spatrick return result; 3083061da546Spatrick } 3084061da546Spatrick 3085061da546Spatrick bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject( 3086061da546Spatrick StructuredData::GenericSP cmd_obj_sp, std::string &dest) { 3087061da546Spatrick bool got_string = false; 3088061da546Spatrick dest.clear(); 3089061da546Spatrick 3090061da546Spatrick Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); 3091061da546Spatrick 3092061da546Spatrick static char callee_name[] = "get_long_help"; 3093061da546Spatrick 3094061da546Spatrick if (!cmd_obj_sp) 3095061da546Spatrick return false; 3096061da546Spatrick 3097061da546Spatrick PythonObject implementor(PyRefType::Borrowed, 3098061da546Spatrick (PyObject *)cmd_obj_sp->GetValue()); 3099061da546Spatrick 3100061da546Spatrick if (!implementor.IsAllocated()) 3101061da546Spatrick return false; 3102061da546Spatrick 3103061da546Spatrick PythonObject pmeth(PyRefType::Owned, 3104061da546Spatrick PyObject_GetAttrString(implementor.get(), callee_name)); 3105061da546Spatrick 3106061da546Spatrick if (PyErr_Occurred()) 3107061da546Spatrick PyErr_Clear(); 3108061da546Spatrick 3109061da546Spatrick if (!pmeth.IsAllocated()) 3110061da546Spatrick return false; 3111061da546Spatrick 3112061da546Spatrick if (PyCallable_Check(pmeth.get()) == 0) { 3113061da546Spatrick if (PyErr_Occurred()) 3114061da546Spatrick PyErr_Clear(); 3115061da546Spatrick 3116061da546Spatrick return false; 3117061da546Spatrick } 3118061da546Spatrick 3119061da546Spatrick if (PyErr_Occurred()) 3120061da546Spatrick PyErr_Clear(); 3121061da546Spatrick 3122061da546Spatrick // right now we know this function exists and is callable.. 3123061da546Spatrick PythonObject py_return( 3124061da546Spatrick PyRefType::Owned, 3125061da546Spatrick PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 3126061da546Spatrick 3127061da546Spatrick // if it fails, print the error but otherwise go on 3128061da546Spatrick if (PyErr_Occurred()) { 3129061da546Spatrick PyErr_Print(); 3130061da546Spatrick PyErr_Clear(); 3131061da546Spatrick } 3132061da546Spatrick 3133061da546Spatrick if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { 3134061da546Spatrick PythonString str(PyRefType::Borrowed, py_return.get()); 3135061da546Spatrick llvm::StringRef str_data(str.GetString()); 3136061da546Spatrick dest.assign(str_data.data(), str_data.size()); 3137061da546Spatrick got_string = true; 3138061da546Spatrick } 3139061da546Spatrick 3140061da546Spatrick return got_string; 3141061da546Spatrick } 3142061da546Spatrick 3143061da546Spatrick std::unique_ptr<ScriptInterpreterLocker> 3144061da546Spatrick ScriptInterpreterPythonImpl::AcquireInterpreterLock() { 3145061da546Spatrick std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker( 3146061da546Spatrick this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN, 3147061da546Spatrick Locker::FreeLock | Locker::TearDownSession)); 3148061da546Spatrick return py_lock; 3149061da546Spatrick } 3150061da546Spatrick 3151061da546Spatrick void ScriptInterpreterPythonImpl::InitializePrivate() { 3152061da546Spatrick if (g_initialized) 3153061da546Spatrick return; 3154061da546Spatrick 3155061da546Spatrick g_initialized = true; 3156061da546Spatrick 3157061da546Spatrick static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 3158061da546Spatrick Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); 3159061da546Spatrick 3160061da546Spatrick // RAII-based initialization which correctly handles multiple-initialization, 3161061da546Spatrick // version- specific differences among Python 2 and Python 3, and saving and 3162061da546Spatrick // restoring various other pieces of state that can get mucked with during 3163061da546Spatrick // initialization. 3164061da546Spatrick InitializePythonRAII initialize_guard; 3165061da546Spatrick 3166061da546Spatrick LLDBSwigPyInit(); 3167061da546Spatrick 3168061da546Spatrick // Update the path python uses to search for modules to include the current 3169061da546Spatrick // directory. 3170061da546Spatrick 3171061da546Spatrick PyRun_SimpleString("import sys"); 3172061da546Spatrick AddToSysPath(AddLocation::End, "."); 3173061da546Spatrick 3174061da546Spatrick // Don't denormalize paths when calling file_spec.GetPath(). On platforms 3175061da546Spatrick // that use a backslash as the path separator, this will result in executing 3176061da546Spatrick // python code containing paths with unescaped backslashes. But Python also 3177061da546Spatrick // accepts forward slashes, so to make life easier we just use that. 3178061da546Spatrick if (FileSpec file_spec = GetPythonDir()) 3179061da546Spatrick AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false)); 3180061da546Spatrick if (FileSpec file_spec = HostInfo::GetShlibDir()) 3181061da546Spatrick AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false)); 3182061da546Spatrick 3183061da546Spatrick PyRun_SimpleString("sys.dont_write_bytecode = 1; import " 3184061da546Spatrick "lldb.embedded_interpreter; from " 3185061da546Spatrick "lldb.embedded_interpreter import run_python_interpreter; " 3186061da546Spatrick "from lldb.embedded_interpreter import run_one_line"); 3187061da546Spatrick } 3188061da546Spatrick 3189061da546Spatrick void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location, 3190061da546Spatrick std::string path) { 3191061da546Spatrick std::string path_copy; 3192061da546Spatrick 3193061da546Spatrick std::string statement; 3194061da546Spatrick if (location == AddLocation::Beginning) { 3195061da546Spatrick statement.assign("sys.path.insert(0,\""); 3196061da546Spatrick statement.append(path); 3197061da546Spatrick statement.append("\")"); 3198061da546Spatrick } else { 3199061da546Spatrick statement.assign("sys.path.append(\""); 3200061da546Spatrick statement.append(path); 3201061da546Spatrick statement.append("\")"); 3202061da546Spatrick } 3203061da546Spatrick PyRun_SimpleString(statement.c_str()); 3204061da546Spatrick } 3205061da546Spatrick 3206061da546Spatrick // We are intentionally NOT calling Py_Finalize here (this would be the logical 3207061da546Spatrick // place to call it). Calling Py_Finalize here causes test suite runs to seg 3208061da546Spatrick // fault: The test suite runs in Python. It registers SBDebugger::Terminate to 3209061da546Spatrick // be called 'at_exit'. When the test suite Python harness finishes up, it 3210061da546Spatrick // calls Py_Finalize, which calls all the 'at_exit' registered functions. 3211061da546Spatrick // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate, 3212061da546Spatrick // which calls ScriptInterpreter::Terminate, which calls 3213061da546Spatrick // ScriptInterpreterPythonImpl::Terminate. So if we call Py_Finalize here, we 3214061da546Spatrick // end up with Py_Finalize being called from within Py_Finalize, which results 3215061da546Spatrick // in a seg fault. Since this function only gets called when lldb is shutting 3216061da546Spatrick // down and going away anyway, the fact that we don't actually call Py_Finalize 3217061da546Spatrick // should not cause any problems (everything should shut down/go away anyway 3218061da546Spatrick // when the process exits). 3219061da546Spatrick // 3220061da546Spatrick // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); } 3221061da546Spatrick 3222061da546Spatrick #endif 3223