1254721Semaste//===-- ScriptInterpreterPython.cpp -----------------------------*- C++ -*-===// 2254721Semaste// 3254721Semaste// The LLVM Compiler Infrastructure 4254721Semaste// 5254721Semaste// This file is distributed under the University of Illinois Open Source 6254721Semaste// License. See LICENSE.TXT for details. 7254721Semaste// 8254721Semaste//===----------------------------------------------------------------------===// 9254721Semaste 10254721Semaste// In order to guarantee correct working with Python, Python.h *MUST* be 11254721Semaste// the *FIRST* header file included here. 12254721Semaste#ifdef LLDB_DISABLE_PYTHON 13254721Semaste 14254721Semaste// Python is disabled in this build 15254721Semaste 16254721Semaste#else 17254721Semaste 18263367Semaste#include "lldb/lldb-python.h" 19254721Semaste#include "lldb/Interpreter/ScriptInterpreterPython.h" 20254721Semaste 21254721Semaste#include <stdlib.h> 22254721Semaste#include <stdio.h> 23254721Semaste 24254721Semaste#include <string> 25254721Semaste 26254721Semaste#include "lldb/API/SBValue.h" 27254721Semaste#include "lldb/Breakpoint/BreakpointLocation.h" 28254721Semaste#include "lldb/Breakpoint/StoppointCallbackContext.h" 29254721Semaste#include "lldb/Breakpoint/WatchpointOptions.h" 30269024Semaste#include "lldb/Core/Communication.h" 31269024Semaste#include "lldb/Core/ConnectionFileDescriptor.h" 32254721Semaste#include "lldb/Core/Debugger.h" 33254721Semaste#include "lldb/Core/Timer.h" 34254721Semaste#include "lldb/Host/Host.h" 35254721Semaste#include "lldb/Interpreter/CommandInterpreter.h" 36254721Semaste#include "lldb/Interpreter/CommandReturnObject.h" 37269024Semaste#include "lldb/Interpreter/PythonDataObjects.h" 38254721Semaste#include "lldb/Target/Thread.h" 39254721Semaste 40254721Semasteusing namespace lldb; 41254721Semasteusing namespace lldb_private; 42254721Semaste 43254721Semaste 44254721Semastestatic ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL; 45254721Semastestatic ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL; 46254721Semastestatic ScriptInterpreter::SWIGWatchpointCallbackFunction g_swig_watchpoint_callback = NULL; 47254721Semastestatic ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL; 48254721Semastestatic ScriptInterpreter::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = NULL; 49254721Semastestatic ScriptInterpreter::SWIGPythonCalculateNumChildren g_swig_calc_children = NULL; 50254721Semastestatic ScriptInterpreter::SWIGPythonGetChildAtIndex g_swig_get_child_index = NULL; 51254721Semastestatic ScriptInterpreter::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = NULL; 52254721Semastestatic ScriptInterpreter::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = NULL; 53263363Semastestatic ScriptInterpreter::SWIGPythonGetValueObjectSPFromSBValue g_swig_get_valobj_sp_from_sbvalue = NULL; 54254721Semastestatic ScriptInterpreter::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = NULL; 55254721Semastestatic ScriptInterpreter::SWIGPythonMightHaveChildrenSynthProviderInstance g_swig_mighthavechildren_provider = NULL; 56254721Semastestatic ScriptInterpreter::SWIGPythonCallCommand g_swig_call_command = NULL; 57254721Semastestatic ScriptInterpreter::SWIGPythonCallModuleInit g_swig_call_module_init = NULL; 58254721Semastestatic ScriptInterpreter::SWIGPythonCreateOSPlugin g_swig_create_os_plugin = NULL; 59254721Semastestatic ScriptInterpreter::SWIGPythonScriptKeyword_Process g_swig_run_script_keyword_process = NULL; 60254721Semastestatic ScriptInterpreter::SWIGPythonScriptKeyword_Thread g_swig_run_script_keyword_thread = NULL; 61254721Semastestatic ScriptInterpreter::SWIGPythonScriptKeyword_Target g_swig_run_script_keyword_target = NULL; 62254721Semastestatic ScriptInterpreter::SWIGPythonScriptKeyword_Frame g_swig_run_script_keyword_frame = NULL; 63263363Semastestatic ScriptInterpreter::SWIGPython_GetDynamicSetting g_swig_plugin_get = NULL; 64254721Semaste 65254721Semastestatic int 66254721Semaste_check_and_flush (FILE *stream) 67254721Semaste{ 68254721Semaste int prev_fail = ferror (stream); 69254721Semaste return fflush (stream) || prev_fail ? EOF : 0; 70254721Semaste} 71254721Semaste 72269024Semastestatic std::string 73269024SemasteReadPythonBacktrace (PyObject* py_backtrace); 74269024Semaste 75254721SemasteScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *py_interpreter, 76254721Semaste uint16_t on_entry, 77254721Semaste uint16_t on_leave, 78269024Semaste FILE *in, 79269024Semaste FILE *out, 80269024Semaste FILE *err) : 81254721Semaste ScriptInterpreterLocker (), 82254721Semaste m_teardown_session( (on_leave & TearDownSession) == TearDownSession ), 83269024Semaste m_python_interpreter(py_interpreter) 84254721Semaste{ 85254721Semaste DoAcquireLock(); 86254721Semaste if ((on_entry & InitSession) == InitSession) 87254721Semaste { 88269024Semaste if (DoInitSession(on_entry, in, out, err) == false) 89254721Semaste { 90254721Semaste // Don't teardown the session if we didn't init it. 91254721Semaste m_teardown_session = false; 92254721Semaste } 93254721Semaste } 94254721Semaste} 95254721Semaste 96254721Semastebool 97254721SemasteScriptInterpreterPython::Locker::DoAcquireLock() 98254721Semaste{ 99254721Semaste Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE)); 100254721Semaste m_GILState = PyGILState_Ensure(); 101254721Semaste if (log) 102254721Semaste log->Printf("Ensured PyGILState. Previous state = %slocked\n", m_GILState == PyGILState_UNLOCKED ? "un" : ""); 103254721Semaste return true; 104254721Semaste} 105254721Semaste 106254721Semastebool 107269024SemasteScriptInterpreterPython::Locker::DoInitSession(uint16_t on_entry_flags, FILE *in, FILE *out, FILE *err) 108254721Semaste{ 109254721Semaste if (!m_python_interpreter) 110254721Semaste return false; 111269024Semaste return m_python_interpreter->EnterSession (on_entry_flags, in, out, err); 112254721Semaste} 113254721Semaste 114254721Semastebool 115254721SemasteScriptInterpreterPython::Locker::DoFreeLock() 116254721Semaste{ 117254721Semaste Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE)); 118254721Semaste if (log) 119254721Semaste log->Printf("Releasing PyGILState. Returning to state = %slocked\n", m_GILState == PyGILState_UNLOCKED ? "un" : ""); 120254721Semaste PyGILState_Release(m_GILState); 121254721Semaste return true; 122254721Semaste} 123254721Semaste 124254721Semastebool 125254721SemasteScriptInterpreterPython::Locker::DoTearDownSession() 126254721Semaste{ 127254721Semaste if (!m_python_interpreter) 128254721Semaste return false; 129254721Semaste m_python_interpreter->LeaveSession (); 130254721Semaste return true; 131254721Semaste} 132254721Semaste 133254721SemasteScriptInterpreterPython::Locker::~Locker() 134254721Semaste{ 135254721Semaste if (m_teardown_session) 136254721Semaste DoTearDownSession(); 137254721Semaste DoFreeLock(); 138254721Semaste} 139254721Semaste 140254721Semaste 141254721SemasteScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) : 142254721Semaste ScriptInterpreter (interpreter, eScriptLanguagePython), 143269024Semaste IOHandlerDelegateMultiline("DONE"), 144269024Semaste m_saved_stdin (), 145269024Semaste m_saved_stdout (), 146269024Semaste m_saved_stderr (), 147269024Semaste m_main_module (), 148269024Semaste m_lldb_module (), 149269024Semaste m_session_dict (false), // Don't create an empty dictionary, leave it invalid 150269024Semaste m_sys_module_dict (false), // Don't create an empty dictionary, leave it invalid 151269024Semaste m_run_one_line_function (), 152269024Semaste m_run_one_line_str_global (), 153254721Semaste m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()), 154254721Semaste m_terminal_state (), 155269024Semaste m_active_io_handler (eIOHandlerNone), 156254721Semaste m_session_is_active (false), 157269024Semaste m_pty_slave_is_open (false), 158254721Semaste m_valid_session (true), 159254721Semaste m_command_thread_state (NULL) 160254721Semaste{ 161254721Semaste 162269024Semaste ScriptInterpreterPython::InitializePrivate (); 163254721Semaste 164254721Semaste m_dictionary_name.append("_dict"); 165254721Semaste StreamString run_string; 166254721Semaste run_string.Printf ("%s = dict()", m_dictionary_name.c_str()); 167254721Semaste 168254721Semaste Locker locker(this, 169254721Semaste ScriptInterpreterPython::Locker::AcquireLock, 170254721Semaste ScriptInterpreterPython::Locker::FreeAcquiredLock); 171254721Semaste PyRun_SimpleString (run_string.GetData()); 172254721Semaste 173254721Semaste run_string.Clear(); 174254721Semaste 175254721Semaste // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a 176254721Semaste // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the 177254721Semaste // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final 178254721Semaste // call to Debugger::Terminate is made, the ref-count has the correct value. 179254721Semaste // 180254721Semaste // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in 181254721Semaste // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed. 182254721Semaste 183254721Semaste int old_count = Debugger::TestDebuggerRefCount(); 184254721Semaste 185254721Semaste run_string.Printf ("run_one_line (%s, 'import copy, os, re, sys, uuid, lldb')", m_dictionary_name.c_str()); 186254721Semaste PyRun_SimpleString (run_string.GetData()); 187254721Semaste 188254721Semaste // WARNING: temporary code that loads Cocoa formatters - this should be done on a per-platform basis rather than loading the whole set 189254721Semaste // and letting the individual formatter classes exploit APIs to check whether they can/cannot do their task 190254721Semaste run_string.Clear(); 191254721Semaste run_string.Printf ("run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')", m_dictionary_name.c_str()); 192254721Semaste PyRun_SimpleString (run_string.GetData()); 193269024Semaste run_string.Clear(); 194254721Semaste 195254721Semaste int new_count = Debugger::TestDebuggerRefCount(); 196254721Semaste 197254721Semaste if (new_count > old_count) 198254721Semaste Debugger::Terminate(); 199254721Semaste 200269024Semaste run_string.Printf ("run_one_line (%s, 'import lldb.embedded_interpreter; from lldb.embedded_interpreter import run_python_interpreter; from lldb.embedded_interpreter import run_one_line')", m_dictionary_name.c_str()); 201269024Semaste PyRun_SimpleString (run_string.GetData()); 202254721Semaste run_string.Clear(); 203269024Semaste 204254721Semaste run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64 "; pydoc.pager = pydoc.plainpager')", m_dictionary_name.c_str(), 205254721Semaste interpreter.GetDebugger().GetID()); 206254721Semaste PyRun_SimpleString (run_string.GetData()); 207254721Semaste} 208254721Semaste 209254721SemasteScriptInterpreterPython::~ScriptInterpreterPython () 210254721Semaste{ 211269024Semaste} 212254721Semaste 213269024Semastevoid 214269024SemasteScriptInterpreterPython::IOHandlerActivated (IOHandler &io_handler) 215269024Semaste{ 216269024Semaste const char *instructions = NULL; 217254721Semaste 218269024Semaste switch (m_active_io_handler) 219254721Semaste { 220269024Semaste case eIOHandlerNone: 221269024Semaste break; 222269024Semaste case eIOHandlerBreakpoint: 223269024Semaste instructions = R"(Enter your Python command(s). Type 'DONE' to end. 224269024Semastedef function (frame, bp_loc, internal_dict): 225269024Semaste """frame: the lldb.SBFrame for the location at which you stopped 226269024Semaste bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information 227269024Semaste internal_dict: an LLDB support object not to be used""" 228269024Semaste)"; 229269024Semaste break; 230269024Semaste case eIOHandlerWatchpoint: 231269024Semaste instructions = "Enter your Python command(s). Type 'DONE' to end.\n"; 232269024Semaste break; 233254721Semaste } 234254721Semaste 235269024Semaste if (instructions) 236254721Semaste { 237269024Semaste StreamFileSP output_sp(io_handler.GetOutputStreamFile()); 238269024Semaste if (output_sp) 239269024Semaste { 240269024Semaste output_sp->PutCString(instructions); 241269024Semaste output_sp->Flush(); 242269024Semaste } 243254721Semaste } 244254721Semaste} 245254721Semaste 246254721Semastevoid 247269024SemasteScriptInterpreterPython::IOHandlerInputComplete (IOHandler &io_handler, std::string &data) 248254721Semaste{ 249269024Semaste io_handler.SetIsDone(true); 250269024Semaste bool batch_mode = m_interpreter.GetBatchCommandMode(); 251254721Semaste 252269024Semaste switch (m_active_io_handler) 253269024Semaste { 254269024Semaste case eIOHandlerNone: 255269024Semaste break; 256269024Semaste case eIOHandlerBreakpoint: 257269024Semaste { 258269024Semaste BreakpointOptions *bp_options = (BreakpointOptions *)io_handler.GetUserData(); 259269024Semaste std::unique_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData()); 260269024Semaste if (data_ap.get()) 261269024Semaste { 262269024Semaste data_ap->user_source.SplitIntoLines(data); 263269024Semaste 264269024Semaste if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source)) 265269024Semaste { 266269024Semaste BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release())); 267269024Semaste bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp); 268269024Semaste } 269269024Semaste else if (!batch_mode) 270269024Semaste { 271269024Semaste StreamFileSP error_sp = io_handler.GetErrorStreamFile(); 272269024Semaste if (error_sp) 273269024Semaste { 274269024Semaste error_sp->Printf ("Warning: No command attached to breakpoint.\n"); 275269024Semaste error_sp->Flush(); 276269024Semaste } 277269024Semaste } 278269024Semaste } 279269024Semaste m_active_io_handler = eIOHandlerNone; 280269024Semaste } 281269024Semaste break; 282269024Semaste case eIOHandlerWatchpoint: 283269024Semaste { 284269024Semaste WatchpointOptions *wp_options = (WatchpointOptions *)io_handler.GetUserData(); 285269024Semaste std::unique_ptr<WatchpointOptions::CommandData> data_ap(new WatchpointOptions::CommandData()); 286269024Semaste if (data_ap.get()) 287269024Semaste { 288269024Semaste data_ap->user_source.SplitIntoLines(data); 289269024Semaste 290269024Semaste if (GenerateWatchpointCommandCallbackData (data_ap->user_source, data_ap->script_source)) 291269024Semaste { 292269024Semaste BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release())); 293269024Semaste wp_options->SetCallback (ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp); 294269024Semaste } 295269024Semaste else if (!batch_mode) 296269024Semaste { 297269024Semaste StreamFileSP error_sp = io_handler.GetErrorStreamFile(); 298269024Semaste if (error_sp) 299269024Semaste { 300269024Semaste error_sp->Printf ("Warning: No command attached to breakpoint.\n"); 301269024Semaste error_sp->Flush(); 302269024Semaste } 303269024Semaste } 304269024Semaste } 305269024Semaste m_active_io_handler = eIOHandlerNone; 306269024Semaste } 307269024Semaste break; 308269024Semaste } 309254721Semaste 310269024Semaste 311254721Semaste} 312254721Semaste 313269024Semaste 314254721Semastevoid 315269024SemasteScriptInterpreterPython::ResetOutputFileHandle (FILE *fh) 316269024Semaste{ 317269024Semaste} 318269024Semaste 319269024Semastevoid 320254721SemasteScriptInterpreterPython::SaveTerminalState (int fd) 321254721Semaste{ 322254721Semaste // Python mucks with the terminal state of STDIN. If we can possibly avoid 323254721Semaste // this by setting the file handles up correctly prior to entering the 324254721Semaste // interpreter we should. For now we save and restore the terminal state 325254721Semaste // on the input file handle. 326254721Semaste m_terminal_state.Save (fd, false); 327254721Semaste} 328254721Semaste 329254721Semastevoid 330254721SemasteScriptInterpreterPython::RestoreTerminalState () 331254721Semaste{ 332254721Semaste // Python mucks with the terminal state of STDIN. If we can possibly avoid 333254721Semaste // this by setting the file handles up correctly prior to entering the 334254721Semaste // interpreter we should. For now we save and restore the terminal state 335254721Semaste // on the input file handle. 336254721Semaste m_terminal_state.Restore(); 337254721Semaste} 338254721Semaste 339254721Semastevoid 340254721SemasteScriptInterpreterPython::LeaveSession () 341254721Semaste{ 342254721Semaste Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT)); 343254721Semaste if (log) 344254721Semaste log->PutCString("ScriptInterpreterPython::LeaveSession()"); 345254721Semaste 346254721Semaste // checking that we have a valid thread state - since we use our own threading and locking 347254721Semaste // in some (rare) cases during cleanup Python may end up believing we have no thread state 348254721Semaste // and PyImport_AddModule will crash if that is the case - since that seems to only happen 349254721Semaste // when destroying the SBDebugger, we can make do without clearing up stdout and stderr 350254721Semaste 351254721Semaste // rdar://problem/11292882 352254721Semaste // When the current thread state is NULL, PyThreadState_Get() issues a fatal error. 353254721Semaste if (PyThreadState_GetDict()) 354254721Semaste { 355269024Semaste PythonDictionary &sys_module_dict = GetSysModuleDictionary (); 356269024Semaste if (sys_module_dict) 357254721Semaste { 358269024Semaste if (m_saved_stdin) 359269024Semaste { 360269024Semaste sys_module_dict.SetItemForKey("stdin", m_saved_stdin); 361269024Semaste m_saved_stdin.Reset (); 362269024Semaste } 363269024Semaste if (m_saved_stdout) 364269024Semaste { 365269024Semaste sys_module_dict.SetItemForKey("stdout", m_saved_stdout); 366269024Semaste m_saved_stdout.Reset (); 367269024Semaste } 368269024Semaste if (m_saved_stderr) 369269024Semaste { 370269024Semaste sys_module_dict.SetItemForKey("stderr", m_saved_stderr); 371269024Semaste m_saved_stderr.Reset (); 372269024Semaste } 373254721Semaste } 374254721Semaste } 375254721Semaste 376254721Semaste m_session_is_active = false; 377254721Semaste} 378254721Semaste 379254721Semastebool 380269024SemasteScriptInterpreterPython::EnterSession (uint16_t on_entry_flags, 381269024Semaste FILE *in, 382269024Semaste FILE *out, 383269024Semaste FILE *err) 384254721Semaste{ 385254721Semaste // If we have already entered the session, without having officially 'left' it, then there is no need to 386254721Semaste // 'enter' it again. 387254721Semaste Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT)); 388254721Semaste if (m_session_is_active) 389254721Semaste { 390254721Semaste if (log) 391269024Semaste log->Printf("ScriptInterpreterPython::EnterSession(on_entry_flags=0x%" PRIx16 ") session is already active, returning without doing anything", on_entry_flags); 392254721Semaste return false; 393254721Semaste } 394254721Semaste 395254721Semaste if (log) 396269024Semaste log->Printf("ScriptInterpreterPython::EnterSession(on_entry_flags=0x%" PRIx16 ")", on_entry_flags); 397254721Semaste 398254721Semaste 399254721Semaste m_session_is_active = true; 400254721Semaste 401254721Semaste StreamString run_string; 402254721Semaste 403269024Semaste if (on_entry_flags & Locker::InitGlobals) 404254721Semaste { 405254721Semaste run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID()); 406254721Semaste run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", GetCommandInterpreter().GetDebugger().GetID()); 407254721Semaste run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()"); 408254721Semaste run_string.PutCString ("; lldb.process = lldb.target.GetProcess()"); 409254721Semaste run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()"); 410254721Semaste run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()"); 411254721Semaste run_string.PutCString ("')"); 412254721Semaste } 413254721Semaste else 414254721Semaste { 415254721Semaste // If we aren't initing the globals, we should still always set the debugger (since that is always unique.) 416269024Semaste run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID()); 417254721Semaste run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", GetCommandInterpreter().GetDebugger().GetID()); 418269024Semaste run_string.PutCString ("')"); 419254721Semaste } 420254721Semaste 421254721Semaste PyRun_SimpleString (run_string.GetData()); 422254721Semaste run_string.Clear(); 423254721Semaste 424269024Semaste PythonDictionary &sys_module_dict = GetSysModuleDictionary (); 425269024Semaste if (sys_module_dict) 426269024Semaste { 427269024Semaste lldb::StreamFileSP in_sp; 428269024Semaste lldb::StreamFileSP out_sp; 429269024Semaste lldb::StreamFileSP err_sp; 430269024Semaste if (in == NULL || out == NULL || err == NULL) 431269024Semaste m_interpreter.GetDebugger().AdoptTopIOHandlerFilesIfInvalid (in_sp, out_sp, err_sp); 432254721Semaste 433269024Semaste if (in == NULL && in_sp && (on_entry_flags & Locker::NoSTDIN) == 0) 434269024Semaste in = in_sp->GetFile().GetStream(); 435269024Semaste if (in) 436254721Semaste { 437269024Semaste m_saved_stdin.Reset(sys_module_dict.GetItemForKey("stdin")); 438269024Semaste 439269024Semaste PyObject *new_file = PyFile_FromFile (in, (char *) "", (char *) "r", 0); 440269024Semaste sys_module_dict.SetItemForKey ("stdin", new_file); 441269024Semaste Py_DECREF (new_file); 442254721Semaste } 443269024Semaste else 444269024Semaste m_saved_stdin.Reset(); 445269024Semaste 446269024Semaste if (out == NULL && out_sp) 447269024Semaste out = out_sp->GetFile().GetStream(); 448269024Semaste if (out) 449269024Semaste { 450269024Semaste m_saved_stdout.Reset(sys_module_dict.GetItemForKey("stdout")); 451269024Semaste 452269024Semaste PyObject *new_file = PyFile_FromFile (out, (char *) "", (char *) "w", 0); 453269024Semaste sys_module_dict.SetItemForKey ("stdout", new_file); 454269024Semaste Py_DECREF (new_file); 455269024Semaste } 456269024Semaste else 457269024Semaste m_saved_stdout.Reset(); 458269024Semaste 459269024Semaste if (err == NULL && err_sp) 460269024Semaste err = err_sp->GetFile().GetStream(); 461269024Semaste if (err) 462269024Semaste { 463269024Semaste m_saved_stderr.Reset(sys_module_dict.GetItemForKey("stderr")); 464269024Semaste 465269024Semaste PyObject *new_file = PyFile_FromFile (err, (char *) "", (char *) "w", 0); 466269024Semaste sys_module_dict.SetItemForKey ("stderr", new_file); 467269024Semaste Py_DECREF (new_file); 468269024Semaste } 469269024Semaste else 470269024Semaste m_saved_stderr.Reset(); 471254721Semaste } 472254721Semaste 473254721Semaste if (PyErr_Occurred()) 474254721Semaste PyErr_Clear (); 475254721Semaste 476254721Semaste return true; 477254721Semaste} 478254721Semaste 479269024SemastePythonObject & 480269024SemasteScriptInterpreterPython::GetMainModule () 481254721Semaste{ 482269024Semaste if (!m_main_module) 483269024Semaste m_main_module.Reset(PyImport_AddModule ("__main__")); 484269024Semaste return m_main_module; 485269024Semaste} 486269024Semaste 487269024SemastePythonDictionary & 488269024SemasteScriptInterpreterPython::GetSessionDictionary () 489269024Semaste{ 490269024Semaste if (!m_session_dict) 491254721Semaste { 492269024Semaste PythonObject &main_module = GetMainModule (); 493269024Semaste if (main_module) 494254721Semaste { 495269024Semaste PythonDictionary main_dict(PyModule_GetDict (main_module.get())); 496269024Semaste if (main_dict) 497254721Semaste { 498269024Semaste m_session_dict = main_dict.GetItemForKey(m_dictionary_name.c_str()); 499254721Semaste } 500254721Semaste } 501254721Semaste } 502269024Semaste return m_session_dict; 503254721Semaste} 504254721Semaste 505269024SemastePythonDictionary & 506269024SemasteScriptInterpreterPython::GetSysModuleDictionary () 507269024Semaste{ 508269024Semaste if (!m_sys_module_dict) 509269024Semaste { 510269024Semaste PyObject *sys_module = PyImport_AddModule ("sys"); 511269024Semaste if (sys_module) 512269024Semaste m_sys_module_dict.Reset(PyModule_GetDict (sys_module)); 513269024Semaste } 514269024Semaste return m_sys_module_dict; 515269024Semaste} 516269024Semaste 517254721Semastestatic std::string 518254721SemasteGenerateUniqueName (const char* base_name_wanted, 519254721Semaste uint32_t& functions_counter, 520254721Semaste void* name_token = NULL) 521254721Semaste{ 522254721Semaste StreamString sstr; 523254721Semaste 524254721Semaste if (!base_name_wanted) 525254721Semaste return std::string(); 526254721Semaste 527254721Semaste if (!name_token) 528254721Semaste sstr.Printf ("%s_%d", base_name_wanted, functions_counter++); 529254721Semaste else 530254721Semaste sstr.Printf ("%s_%p", base_name_wanted, name_token); 531254721Semaste 532254721Semaste return sstr.GetString(); 533254721Semaste} 534254721Semaste 535254721Semastebool 536269024SemasteScriptInterpreterPython::GetEmbeddedInterpreterModuleObjects () 537269024Semaste{ 538269024Semaste if (!m_run_one_line_function) 539269024Semaste { 540269024Semaste PyObject *module = PyImport_AddModule ("lldb.embedded_interpreter"); 541269024Semaste if (module != NULL) 542269024Semaste { 543269024Semaste PythonDictionary module_dict (PyModule_GetDict (module)); 544269024Semaste if (module_dict) 545269024Semaste { 546269024Semaste m_run_one_line_function = module_dict.GetItemForKey("run_one_line"); 547269024Semaste m_run_one_line_str_global = module_dict.GetItemForKey("g_run_one_line_str"); 548269024Semaste } 549269024Semaste } 550269024Semaste } 551269024Semaste return (bool)m_run_one_line_function; 552269024Semaste} 553269024Semaste 554269024Semastestatic void 555269024SemasteReadThreadBytesReceived(void *baton, const void *src, size_t src_len) 556269024Semaste{ 557269024Semaste if (src && src_len) 558269024Semaste { 559269024Semaste Stream *strm = (Stream *)baton; 560269024Semaste strm->Write(src, src_len); 561269024Semaste strm->Flush(); 562269024Semaste } 563269024Semaste} 564269024Semaste 565269024Semastebool 566254721SemasteScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result, const ExecuteScriptOptions &options) 567254721Semaste{ 568254721Semaste if (!m_valid_session) 569254721Semaste return false; 570269024Semaste 571269024Semaste if (command && command[0]) 572269024Semaste { 573269024Semaste // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through 574269024Semaste // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside 575269024Semaste // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated 576269024Semaste // method to pass the command string directly down to Python. 577269024Semaste Debugger &debugger = m_interpreter.GetDebugger(); 578254721Semaste 579269024Semaste StreamFileSP input_file_sp; 580269024Semaste StreamFileSP output_file_sp; 581269024Semaste StreamFileSP error_file_sp; 582269024Semaste Communication output_comm ("lldb.ScriptInterpreterPython.ExecuteOneLine.comm"); 583269024Semaste int pipe_fds[2] = { -1, -1 }; 584269024Semaste 585269024Semaste if (options.GetEnableIO()) 586254721Semaste { 587269024Semaste if (result) 588254721Semaste { 589269024Semaste input_file_sp = debugger.GetInputFile(); 590269024Semaste // Set output to a temporary file so we can forward the results on to the result object 591269024Semaste 592269024Semaste int err = pipe(pipe_fds); 593269024Semaste if (err == 0) 594254721Semaste { 595269024Semaste std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor(pipe_fds[0], true)); 596269024Semaste if (conn_ap->IsConnected()) 597254721Semaste { 598269024Semaste output_comm.SetConnection(conn_ap.release()); 599269024Semaste output_comm.SetReadThreadBytesReceivedCallback(ReadThreadBytesReceived, &result->GetOutputStream()); 600269024Semaste output_comm.StartReadThread(); 601269024Semaste FILE *outfile_handle = fdopen (pipe_fds[1], "w"); 602269024Semaste output_file_sp.reset(new StreamFile(outfile_handle, true)); 603269024Semaste error_file_sp = output_file_sp; 604269024Semaste if (outfile_handle) 605269024Semaste ::setbuf (outfile_handle, NULL); 606254721Semaste 607269024Semaste result->SetImmediateOutputFile(debugger.GetOutputFile()->GetFile().GetStream()); 608269024Semaste result->SetImmediateErrorFile(debugger.GetErrorFile()->GetFile().GetStream()); 609254721Semaste } 610269024Semaste } 611269024Semaste } 612269024Semaste if (!input_file_sp || !output_file_sp || !error_file_sp) 613269024Semaste debugger.AdoptTopIOHandlerFilesIfInvalid(input_file_sp, output_file_sp, error_file_sp); 614269024Semaste } 615269024Semaste else 616269024Semaste { 617269024Semaste input_file_sp.reset (new StreamFile ()); 618269024Semaste input_file_sp->GetFile().Open("/dev/null", File::eOpenOptionRead); 619269024Semaste output_file_sp.reset (new StreamFile ()); 620269024Semaste output_file_sp->GetFile().Open("/dev/null", File::eOpenOptionWrite); 621269024Semaste error_file_sp = output_file_sp; 622269024Semaste } 623269024Semaste 624269024Semaste FILE *in_file = input_file_sp->GetFile().GetStream(); 625269024Semaste FILE *out_file = output_file_sp->GetFile().GetStream(); 626269024Semaste FILE *err_file = error_file_sp->GetFile().GetStream(); 627269024Semaste Locker locker(this, 628269024Semaste ScriptInterpreterPython::Locker::AcquireLock | 629269024Semaste ScriptInterpreterPython::Locker::InitSession | 630269024Semaste (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::InitGlobals : 0), 631269024Semaste ScriptInterpreterPython::Locker::FreeAcquiredLock | 632269024Semaste ScriptInterpreterPython::Locker::TearDownSession, 633269024Semaste in_file, 634269024Semaste out_file, 635269024Semaste err_file); 636269024Semaste 637269024Semaste bool success = false; 638269024Semaste 639269024Semaste // Find the correct script interpreter dictionary in the main module. 640269024Semaste PythonDictionary &session_dict = GetSessionDictionary (); 641269024Semaste if (session_dict) 642269024Semaste { 643269024Semaste if (GetEmbeddedInterpreterModuleObjects ()) 644269024Semaste { 645269024Semaste PyObject *pfunc = m_run_one_line_function.get(); 646269024Semaste 647269024Semaste if (pfunc && PyCallable_Check (pfunc)) 648269024Semaste { 649269024Semaste PythonObject pargs (Py_BuildValue("(Os)", session_dict.get(), command)); 650269024Semaste if (pargs) 651254721Semaste { 652269024Semaste PythonObject return_value(PyObject_CallObject (pfunc, pargs.get())); 653269024Semaste if (return_value) 654269024Semaste success = true; 655269024Semaste else if (options.GetMaskoutErrors() && PyErr_Occurred ()) 656254721Semaste { 657269024Semaste PyErr_Print(); 658269024Semaste PyErr_Clear(); 659254721Semaste } 660254721Semaste } 661254721Semaste } 662254721Semaste } 663254721Semaste } 664254721Semaste 665269024Semaste // Flush our output and error file handles 666269024Semaste ::fflush (out_file); 667269024Semaste if (out_file != err_file) 668269024Semaste ::fflush (err_file); 669269024Semaste 670269024Semaste if (pipe_fds[0] != -1) 671269024Semaste { 672269024Semaste // Close the write end of the pipe since we are done with our 673269024Semaste // one line script. This should cause the read thread that 674269024Semaste // output_comm is using to exit 675269024Semaste output_file_sp->GetFile().Close(); 676269024Semaste // The close above should cause this thread to exit when it gets 677269024Semaste // to the end of file, so let it get all its data 678269024Semaste output_comm.JoinReadThread(); 679269024Semaste // Now we can close the read end of the pipe 680269024Semaste output_comm.Disconnect(); 681269024Semaste } 682269024Semaste 683269024Semaste 684254721Semaste if (success) 685254721Semaste return true; 686254721Semaste 687254721Semaste // The one-liner failed. Append the error message. 688254721Semaste if (result) 689254721Semaste result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command); 690254721Semaste return false; 691254721Semaste } 692254721Semaste 693254721Semaste if (result) 694254721Semaste result->AppendError ("empty command passed to python\n"); 695254721Semaste return false; 696254721Semaste} 697254721Semaste 698269024Semaste 699269024Semasteclass IOHandlerPythonInterpreter : 700269024Semaste public IOHandler 701254721Semaste{ 702269024Semastepublic: 703269024Semaste 704269024Semaste IOHandlerPythonInterpreter (Debugger &debugger, 705269024Semaste ScriptInterpreterPython *python) : 706269024Semaste IOHandler (debugger), 707269024Semaste m_python(python) 708269024Semaste { 709254721Semaste 710269024Semaste } 711254721Semaste 712269024Semaste virtual 713269024Semaste ~IOHandlerPythonInterpreter() 714269024Semaste { 715269024Semaste 716269024Semaste } 717254721Semaste 718269024Semaste virtual ConstString 719269024Semaste GetControlSequence (char ch) 720254721Semaste { 721269024Semaste if (ch == 'd') 722269024Semaste return ConstString("quit()\n"); 723269024Semaste return ConstString(); 724269024Semaste } 725269024Semaste 726269024Semaste virtual void 727269024Semaste Run () 728269024Semaste { 729269024Semaste if (m_python) 730254721Semaste { 731269024Semaste int stdin_fd = GetInputFD(); 732269024Semaste if (stdin_fd >= 0) 733254721Semaste { 734269024Semaste Terminal terminal(stdin_fd); 735269024Semaste TerminalState terminal_state; 736269024Semaste const bool is_a_tty = terminal.IsATerminal(); 737269024Semaste 738269024Semaste if (is_a_tty) 739254721Semaste { 740269024Semaste terminal_state.Save (stdin_fd, false); 741269024Semaste terminal.SetCanonical(false); 742269024Semaste terminal.SetEcho(true); 743254721Semaste } 744269024Semaste 745269024Semaste ScriptInterpreterPython::Locker locker (m_python, 746269024Semaste ScriptInterpreterPython::Locker::AcquireLock | 747269024Semaste ScriptInterpreterPython::Locker::InitSession | 748269024Semaste ScriptInterpreterPython::Locker::InitGlobals, 749269024Semaste ScriptInterpreterPython::Locker::FreeAcquiredLock | 750269024Semaste ScriptInterpreterPython::Locker::TearDownSession); 751269024Semaste 752269024Semaste // The following call drops into the embedded interpreter loop and stays there until the 753269024Semaste // user chooses to exit from the Python interpreter. 754269024Semaste // This embedded interpreter will, as any Python code that performs I/O, unlock the GIL before 755269024Semaste // a system call that can hang, and lock it when the syscall has returned. 756269024Semaste 757269024Semaste // We need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and 758269024Semaste // PyGILState_Release (using the Locker above). This is because Python has a global lock which must be held whenever we want 759269024Semaste // to touch any Python objects. Otherwise, if the user calls Python code, the interpreter state will be off, 760269024Semaste // and things could hang (it's happened before). 761269024Semaste 762269024Semaste StreamString run_string; 763269024Semaste run_string.Printf ("run_python_interpreter (%s)", m_python->GetDictionaryName ()); 764269024Semaste PyRun_SimpleString (run_string.GetData()); 765269024Semaste 766269024Semaste if (is_a_tty) 767269024Semaste terminal_state.Restore(); 768254721Semaste } 769254721Semaste } 770269024Semaste SetIsDone(true); 771269024Semaste } 772254721Semaste 773269024Semaste virtual void 774269024Semaste Hide () 775269024Semaste { 776254721Semaste 777269024Semaste } 778269024Semaste 779269024Semaste virtual void 780269024Semaste Refresh () 781269024Semaste { 782254721Semaste 783269024Semaste } 784269024Semaste 785269024Semaste virtual void 786269024Semaste Cancel () 787269024Semaste { 788254721Semaste 789269024Semaste } 790254721Semaste 791269024Semaste virtual void 792269024Semaste Interrupt () 793269024Semaste { 794254721Semaste 795254721Semaste } 796269024Semaste 797269024Semaste virtual void 798269024Semaste GotEOF() 799269024Semaste { 800269024Semaste 801269024Semaste } 802269024Semasteprotected: 803269024Semaste ScriptInterpreterPython *m_python; 804269024Semaste}; 805254721Semaste 806254721Semaste 807254721Semastevoid 808254721SemasteScriptInterpreterPython::ExecuteInterpreterLoop () 809254721Semaste{ 810254721Semaste Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); 811254721Semaste 812254721Semaste Debugger &debugger = GetCommandInterpreter().GetDebugger(); 813254721Semaste 814254721Semaste // At the moment, the only time the debugger does not have an input file handle is when this is called 815254721Semaste // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to 816254721Semaste // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't 817254721Semaste // do it. 818254721Semaste 819269024Semaste if (!debugger.GetInputFile()->GetFile().IsValid()) 820254721Semaste return; 821254721Semaste 822269024Semaste IOHandlerSP io_handler_sp (new IOHandlerPythonInterpreter (debugger, this)); 823269024Semaste if (io_handler_sp) 824254721Semaste { 825269024Semaste debugger.PushIOHandler(io_handler_sp); 826254721Semaste } 827254721Semaste} 828254721Semaste 829254721Semastebool 830254721SemasteScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string, 831254721Semaste ScriptInterpreter::ScriptReturnType return_type, 832254721Semaste void *ret_value, 833254721Semaste const ExecuteScriptOptions &options) 834254721Semaste{ 835254721Semaste 836254721Semaste Locker locker(this, 837254721Semaste ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::InitGlobals : 0), 838254721Semaste ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession); 839254721Semaste 840254721Semaste PyObject *py_return = NULL; 841269024Semaste PythonObject &main_module = GetMainModule (); 842269024Semaste PythonDictionary globals (PyModule_GetDict(main_module.get())); 843254721Semaste PyObject *py_error = NULL; 844254721Semaste bool ret_success = false; 845254721Semaste int success; 846254721Semaste 847269024Semaste PythonDictionary locals = GetSessionDictionary (); 848254721Semaste 849269024Semaste if (!locals) 850254721Semaste { 851269024Semaste locals = PyObject_GetAttrString (globals.get(), m_dictionary_name.c_str()); 852254721Semaste } 853254721Semaste 854269024Semaste if (!locals) 855254721Semaste locals = globals; 856254721Semaste 857254721Semaste py_error = PyErr_Occurred(); 858254721Semaste if (py_error != NULL) 859254721Semaste PyErr_Clear(); 860254721Semaste 861254721Semaste if (in_string != NULL) 862254721Semaste { 863254721Semaste { // scope for PythonInputReaderManager 864269024Semaste //PythonInputReaderManager py_input(options.GetEnableIO() ? this : NULL); 865269024Semaste py_return = PyRun_String (in_string, Py_eval_input, globals.get(), locals.get()); 866254721Semaste if (py_return == NULL) 867254721Semaste { 868254721Semaste py_error = PyErr_Occurred (); 869254721Semaste if (py_error != NULL) 870254721Semaste PyErr_Clear (); 871254721Semaste 872269024Semaste py_return = PyRun_String (in_string, Py_single_input, globals.get(), locals.get()); 873254721Semaste } 874254721Semaste } 875254721Semaste 876254721Semaste if (py_return != NULL) 877254721Semaste { 878254721Semaste switch (return_type) 879254721Semaste { 880254721Semaste case eScriptReturnTypeCharPtr: // "char *" 881254721Semaste { 882254721Semaste const char format[3] = "s#"; 883254721Semaste success = PyArg_Parse (py_return, format, (char **) ret_value); 884254721Semaste break; 885254721Semaste } 886254721Semaste case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None 887254721Semaste { 888254721Semaste const char format[3] = "z"; 889254721Semaste success = PyArg_Parse (py_return, format, (char **) ret_value); 890254721Semaste break; 891254721Semaste } 892254721Semaste case eScriptReturnTypeBool: 893254721Semaste { 894254721Semaste const char format[2] = "b"; 895254721Semaste success = PyArg_Parse (py_return, format, (bool *) ret_value); 896254721Semaste break; 897254721Semaste } 898254721Semaste case eScriptReturnTypeShortInt: 899254721Semaste { 900254721Semaste const char format[2] = "h"; 901254721Semaste success = PyArg_Parse (py_return, format, (short *) ret_value); 902254721Semaste break; 903254721Semaste } 904254721Semaste case eScriptReturnTypeShortIntUnsigned: 905254721Semaste { 906254721Semaste const char format[2] = "H"; 907254721Semaste success = PyArg_Parse (py_return, format, (unsigned short *) ret_value); 908254721Semaste break; 909254721Semaste } 910254721Semaste case eScriptReturnTypeInt: 911254721Semaste { 912254721Semaste const char format[2] = "i"; 913254721Semaste success = PyArg_Parse (py_return, format, (int *) ret_value); 914254721Semaste break; 915254721Semaste } 916254721Semaste case eScriptReturnTypeIntUnsigned: 917254721Semaste { 918254721Semaste const char format[2] = "I"; 919254721Semaste success = PyArg_Parse (py_return, format, (unsigned int *) ret_value); 920254721Semaste break; 921254721Semaste } 922254721Semaste case eScriptReturnTypeLongInt: 923254721Semaste { 924254721Semaste const char format[2] = "l"; 925254721Semaste success = PyArg_Parse (py_return, format, (long *) ret_value); 926254721Semaste break; 927254721Semaste } 928254721Semaste case eScriptReturnTypeLongIntUnsigned: 929254721Semaste { 930254721Semaste const char format[2] = "k"; 931254721Semaste success = PyArg_Parse (py_return, format, (unsigned long *) ret_value); 932254721Semaste break; 933254721Semaste } 934254721Semaste case eScriptReturnTypeLongLong: 935254721Semaste { 936254721Semaste const char format[2] = "L"; 937254721Semaste success = PyArg_Parse (py_return, format, (long long *) ret_value); 938254721Semaste break; 939254721Semaste } 940254721Semaste case eScriptReturnTypeLongLongUnsigned: 941254721Semaste { 942254721Semaste const char format[2] = "K"; 943254721Semaste success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value); 944254721Semaste break; 945254721Semaste } 946254721Semaste case eScriptReturnTypeFloat: 947254721Semaste { 948254721Semaste const char format[2] = "f"; 949254721Semaste success = PyArg_Parse (py_return, format, (float *) ret_value); 950254721Semaste break; 951254721Semaste } 952254721Semaste case eScriptReturnTypeDouble: 953254721Semaste { 954254721Semaste const char format[2] = "d"; 955254721Semaste success = PyArg_Parse (py_return, format, (double *) ret_value); 956254721Semaste break; 957254721Semaste } 958254721Semaste case eScriptReturnTypeChar: 959254721Semaste { 960254721Semaste const char format[2] = "c"; 961254721Semaste success = PyArg_Parse (py_return, format, (char *) ret_value); 962254721Semaste break; 963254721Semaste } 964263363Semaste case eScriptReturnTypeOpaqueObject: 965263363Semaste { 966263363Semaste success = true; 967263363Semaste Py_XINCREF(py_return); 968263363Semaste *((PyObject**)ret_value) = py_return; 969263363Semaste break; 970263363Semaste } 971254721Semaste } 972254721Semaste Py_XDECREF (py_return); 973254721Semaste if (success) 974254721Semaste ret_success = true; 975254721Semaste else 976254721Semaste ret_success = false; 977254721Semaste } 978254721Semaste } 979254721Semaste 980254721Semaste py_error = PyErr_Occurred(); 981254721Semaste if (py_error != NULL) 982254721Semaste { 983254721Semaste ret_success = false; 984254721Semaste if (options.GetMaskoutErrors()) 985254721Semaste { 986254721Semaste if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError)) 987254721Semaste PyErr_Print (); 988254721Semaste PyErr_Clear(); 989254721Semaste } 990254721Semaste } 991254721Semaste 992254721Semaste return ret_success; 993254721Semaste} 994254721Semaste 995269024SemasteError 996254721SemasteScriptInterpreterPython::ExecuteMultipleLines (const char *in_string, const ExecuteScriptOptions &options) 997254721Semaste{ 998269024Semaste Error error; 999254721Semaste 1000254721Semaste Locker locker(this, 1001254721Semaste ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::InitGlobals : 0), 1002254721Semaste ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession); 1003254721Semaste 1004254721Semaste bool success = false; 1005269024Semaste PythonObject return_value; 1006269024Semaste PythonObject &main_module = GetMainModule (); 1007269024Semaste PythonDictionary globals (PyModule_GetDict(main_module.get())); 1008254721Semaste PyObject *py_error = NULL; 1009254721Semaste 1010269024Semaste PythonDictionary locals = GetSessionDictionary (); 1011254721Semaste 1012269024Semaste if (!locals) 1013254721Semaste { 1014269024Semaste locals = PyObject_GetAttrString (globals.get(), m_dictionary_name.c_str()); 1015254721Semaste } 1016254721Semaste 1017269024Semaste if (!locals) 1018254721Semaste { 1019254721Semaste locals = globals; 1020254721Semaste } 1021254721Semaste 1022254721Semaste py_error = PyErr_Occurred(); 1023254721Semaste if (py_error != NULL) 1024254721Semaste PyErr_Clear(); 1025254721Semaste 1026254721Semaste if (in_string != NULL) 1027254721Semaste { 1028254721Semaste struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input); 1029254721Semaste if (compiled_node) 1030254721Semaste { 1031254721Semaste PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py"); 1032254721Semaste if (compiled_code) 1033254721Semaste { 1034254721Semaste { // scope for PythonInputReaderManager 1035269024Semaste //PythonInputReaderManager py_input(options.GetEnableIO() ? this : NULL); 1036269024Semaste return_value.Reset(PyEval_EvalCode (compiled_code, globals.get(), locals.get())); 1037254721Semaste } 1038269024Semaste if (return_value) 1039254721Semaste success = true; 1040254721Semaste } 1041254721Semaste } 1042254721Semaste } 1043254721Semaste 1044254721Semaste py_error = PyErr_Occurred (); 1045254721Semaste if (py_error != NULL) 1046254721Semaste { 1047269024Semaste// puts(in_string); 1048269024Semaste// _PyObject_Dump (py_error); 1049269024Semaste// PyErr_Print(); 1050269024Semaste// success = false; 1051254721Semaste 1052269024Semaste PyObject *type = NULL; 1053269024Semaste PyObject *value = NULL; 1054269024Semaste PyObject *traceback = NULL; 1055269024Semaste PyErr_Fetch (&type,&value,&traceback); 1056254721Semaste 1057269024Semaste // get the backtrace 1058269024Semaste std::string bt = ReadPythonBacktrace(traceback); 1059254721Semaste 1060269024Semaste if (value && value != Py_None) 1061269024Semaste error.SetErrorStringWithFormat("%s\n%s", PyString_AsString(PyObject_Str(value)),bt.c_str()); 1062269024Semaste else 1063269024Semaste error.SetErrorStringWithFormat("%s",bt.c_str()); 1064269024Semaste Py_XDECREF(type); 1065269024Semaste Py_XDECREF(value); 1066269024Semaste Py_XDECREF(traceback); 1067269024Semaste if (options.GetMaskoutErrors()) 1068254721Semaste { 1069269024Semaste PyErr_Clear(); 1070254721Semaste } 1071254721Semaste } 1072254721Semaste 1073269024Semaste return error; 1074254721Semaste} 1075254721Semaste 1076254721Semaste 1077254721Semastevoid 1078254721SemasteScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options, 1079254721Semaste CommandReturnObject &result) 1080254721Semaste{ 1081269024Semaste m_active_io_handler = eIOHandlerBreakpoint; 1082269024Semaste m_interpreter.GetPythonCommandsFromIOHandler (" ", *this, true, bp_options); 1083254721Semaste} 1084254721Semaste 1085254721Semastevoid 1086254721SemasteScriptInterpreterPython::CollectDataForWatchpointCommandCallback (WatchpointOptions *wp_options, 1087254721Semaste CommandReturnObject &result) 1088254721Semaste{ 1089269024Semaste m_active_io_handler = eIOHandlerWatchpoint; 1090269024Semaste m_interpreter.GetPythonCommandsFromIOHandler (" ", *this, true, wp_options); 1091254721Semaste} 1092254721Semaste 1093254721Semaste// Set a Python one-liner as the callback for the breakpoint. 1094254721Semastevoid 1095254721SemasteScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options, 1096254721Semaste const char *oneliner) 1097254721Semaste{ 1098254721Semaste std::unique_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData()); 1099254721Semaste 1100254721Semaste // It's necessary to set both user_source and script_source to the oneliner. 1101254721Semaste // The former is used to generate callback description (as in breakpoint command list) 1102254721Semaste // while the latter is used for Python to interpret during the actual callback. 1103254721Semaste 1104254721Semaste data_ap->user_source.AppendString (oneliner); 1105254721Semaste data_ap->script_source.assign (oneliner); 1106254721Semaste 1107254721Semaste if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source)) 1108254721Semaste { 1109254721Semaste BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release())); 1110254721Semaste bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp); 1111254721Semaste } 1112254721Semaste 1113254721Semaste return; 1114254721Semaste} 1115254721Semaste 1116254721Semaste// Set a Python one-liner as the callback for the watchpoint. 1117254721Semastevoid 1118254721SemasteScriptInterpreterPython::SetWatchpointCommandCallback (WatchpointOptions *wp_options, 1119254721Semaste const char *oneliner) 1120254721Semaste{ 1121254721Semaste std::unique_ptr<WatchpointOptions::CommandData> data_ap(new WatchpointOptions::CommandData()); 1122254721Semaste 1123254721Semaste // It's necessary to set both user_source and script_source to the oneliner. 1124254721Semaste // The former is used to generate callback description (as in watchpoint command list) 1125254721Semaste // while the latter is used for Python to interpret during the actual callback. 1126254721Semaste 1127254721Semaste data_ap->user_source.AppendString (oneliner); 1128254721Semaste data_ap->script_source.assign (oneliner); 1129254721Semaste 1130254721Semaste if (GenerateWatchpointCommandCallbackData (data_ap->user_source, data_ap->script_source)) 1131254721Semaste { 1132254721Semaste BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release())); 1133254721Semaste wp_options->SetCallback (ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp); 1134254721Semaste } 1135254721Semaste 1136254721Semaste return; 1137254721Semaste} 1138254721Semaste 1139254721Semastebool 1140254721SemasteScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def) 1141254721Semaste{ 1142254721Semaste // Convert StringList to one long, newline delimited, const char *. 1143254721Semaste std::string function_def_string(function_def.CopyList()); 1144254721Semaste 1145269024Semaste return ExecuteMultipleLines (function_def_string.c_str(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false)).Success(); 1146254721Semaste} 1147254721Semaste 1148254721Semastebool 1149254721SemasteScriptInterpreterPython::GenerateFunction(const char *signature, const StringList &input) 1150254721Semaste{ 1151254721Semaste int num_lines = input.GetSize (); 1152254721Semaste if (num_lines == 0) 1153254721Semaste return false; 1154254721Semaste 1155254721Semaste if (!signature || *signature == 0) 1156254721Semaste return false; 1157254721Semaste 1158254721Semaste StreamString sstr; 1159254721Semaste StringList auto_generated_function; 1160254721Semaste auto_generated_function.AppendString (signature); 1161254721Semaste auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary 1162254721Semaste auto_generated_function.AppendString (" new_keys = internal_dict.keys()"); // Make a list of keys in the session dict 1163254721Semaste auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict 1164254721Semaste auto_generated_function.AppendString (" global_dict.update (internal_dict)"); // Add the session dictionary to the 1165254721Semaste // global dictionary. 1166254721Semaste 1167254721Semaste // Wrap everything up inside the function, increasing the indentation. 1168254721Semaste 1169254721Semaste auto_generated_function.AppendString(" if True:"); 1170254721Semaste for (int i = 0; i < num_lines; ++i) 1171254721Semaste { 1172254721Semaste sstr.Clear (); 1173254721Semaste sstr.Printf (" %s", input.GetStringAtIndex (i)); 1174254721Semaste auto_generated_function.AppendString (sstr.GetData()); 1175254721Semaste } 1176254721Semaste auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict 1177254721Semaste auto_generated_function.AppendString (" internal_dict[key] = global_dict[key]"); // Update session dict values 1178254721Semaste auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict 1179254721Semaste auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict 1180254721Semaste 1181254721Semaste // Verify that the results are valid Python. 1182254721Semaste 1183254721Semaste if (!ExportFunctionDefinitionToInterpreter (auto_generated_function)) 1184254721Semaste return false; 1185254721Semaste 1186254721Semaste return true; 1187254721Semaste 1188254721Semaste} 1189254721Semaste 1190254721Semastebool 1191254721SemasteScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, std::string& output, void* name_token) 1192254721Semaste{ 1193254721Semaste static uint32_t num_created_functions = 0; 1194254721Semaste user_input.RemoveBlankLines (); 1195254721Semaste StreamString sstr; 1196254721Semaste 1197254721Semaste // Check to see if we have any data; if not, just return. 1198254721Semaste if (user_input.GetSize() == 0) 1199254721Semaste return false; 1200254721Semaste 1201254721Semaste // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the 1202254721Semaste // ValueObject as parameter to the function. 1203254721Semaste 1204254721Semaste std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_type_print_func", num_created_functions, name_token)); 1205254721Semaste sstr.Printf ("def %s (valobj, internal_dict):", auto_generated_function_name.c_str()); 1206254721Semaste 1207254721Semaste if (!GenerateFunction(sstr.GetData(), user_input)) 1208254721Semaste return false; 1209254721Semaste 1210254721Semaste // Store the name of the auto-generated function to be called. 1211254721Semaste output.assign(auto_generated_function_name); 1212254721Semaste return true; 1213254721Semaste} 1214254721Semaste 1215254721Semastebool 1216254721SemasteScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, std::string &output) 1217254721Semaste{ 1218254721Semaste static uint32_t num_created_functions = 0; 1219254721Semaste user_input.RemoveBlankLines (); 1220254721Semaste StreamString sstr; 1221254721Semaste 1222254721Semaste // Check to see if we have any data; if not, just return. 1223254721Semaste if (user_input.GetSize() == 0) 1224254721Semaste return false; 1225254721Semaste 1226254721Semaste std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_cmd_alias_func", num_created_functions)); 1227254721Semaste 1228254721Semaste sstr.Printf ("def %s (debugger, args, result, internal_dict):", auto_generated_function_name.c_str()); 1229254721Semaste 1230254721Semaste if (!GenerateFunction(sstr.GetData(),user_input)) 1231254721Semaste return false; 1232254721Semaste 1233254721Semaste // Store the name of the auto-generated function to be called. 1234254721Semaste output.assign(auto_generated_function_name); 1235254721Semaste return true; 1236254721Semaste} 1237254721Semaste 1238254721Semaste 1239254721Semastebool 1240254721SemasteScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, std::string &output, void* name_token) 1241254721Semaste{ 1242254721Semaste static uint32_t num_created_classes = 0; 1243254721Semaste user_input.RemoveBlankLines (); 1244254721Semaste int num_lines = user_input.GetSize (); 1245254721Semaste StreamString sstr; 1246254721Semaste 1247254721Semaste // Check to see if we have any data; if not, just return. 1248254721Semaste if (user_input.GetSize() == 0) 1249254721Semaste return false; 1250254721Semaste 1251254721Semaste // Wrap all user input into a Python class 1252254721Semaste 1253254721Semaste std::string auto_generated_class_name(GenerateUniqueName("lldb_autogen_python_type_synth_class",num_created_classes,name_token)); 1254254721Semaste 1255254721Semaste StringList auto_generated_class; 1256254721Semaste 1257254721Semaste // Create the function name & definition string. 1258254721Semaste 1259254721Semaste sstr.Printf ("class %s:", auto_generated_class_name.c_str()); 1260254721Semaste auto_generated_class.AppendString (sstr.GetData()); 1261254721Semaste 1262254721Semaste // Wrap everything up inside the class, increasing the indentation. 1263254721Semaste // we don't need to play any fancy indentation tricks here because there is no 1264254721Semaste // surrounding code whose indentation we need to honor 1265254721Semaste for (int i = 0; i < num_lines; ++i) 1266254721Semaste { 1267254721Semaste sstr.Clear (); 1268254721Semaste sstr.Printf (" %s", user_input.GetStringAtIndex (i)); 1269254721Semaste auto_generated_class.AppendString (sstr.GetData()); 1270254721Semaste } 1271254721Semaste 1272254721Semaste 1273254721Semaste // Verify that the results are valid Python. 1274254721Semaste // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported) 1275254721Semaste // (TODO: rename that method to ExportDefinitionToInterpreter) 1276254721Semaste if (!ExportFunctionDefinitionToInterpreter (auto_generated_class)) 1277254721Semaste return false; 1278254721Semaste 1279254721Semaste // Store the name of the auto-generated class 1280254721Semaste 1281254721Semaste output.assign(auto_generated_class_name); 1282254721Semaste return true; 1283254721Semaste} 1284254721Semaste 1285254721Semastelldb::ScriptInterpreterObjectSP 1286254721SemasteScriptInterpreterPython::OSPlugin_CreatePluginObject (const char *class_name, lldb::ProcessSP process_sp) 1287254721Semaste{ 1288254721Semaste if (class_name == NULL || class_name[0] == '\0') 1289254721Semaste return lldb::ScriptInterpreterObjectSP(); 1290254721Semaste 1291254721Semaste if (!process_sp) 1292254721Semaste return lldb::ScriptInterpreterObjectSP(); 1293254721Semaste 1294254721Semaste void* ret_val; 1295254721Semaste 1296254721Semaste { 1297269024Semaste Locker py_lock (this, 1298269024Semaste Locker::AcquireLock | Locker::NoSTDIN, 1299269024Semaste Locker::FreeLock); 1300254721Semaste ret_val = g_swig_create_os_plugin (class_name, 1301254721Semaste m_dictionary_name.c_str(), 1302254721Semaste process_sp); 1303254721Semaste } 1304254721Semaste 1305254721Semaste return MakeScriptObject(ret_val); 1306254721Semaste} 1307254721Semaste 1308254721Semastelldb::ScriptInterpreterObjectSP 1309254721SemasteScriptInterpreterPython::OSPlugin_RegisterInfo (lldb::ScriptInterpreterObjectSP os_plugin_object_sp) 1310254721Semaste{ 1311269024Semaste Locker py_lock(this, 1312269024Semaste Locker::AcquireLock | Locker::NoSTDIN, 1313269024Semaste Locker::FreeLock); 1314254721Semaste 1315254721Semaste static char callee_name[] = "get_register_info"; 1316254721Semaste 1317254721Semaste if (!os_plugin_object_sp) 1318254721Semaste return lldb::ScriptInterpreterObjectSP(); 1319254721Semaste 1320254721Semaste PyObject* implementor = (PyObject*)os_plugin_object_sp->GetObject(); 1321254721Semaste 1322254721Semaste if (implementor == NULL || implementor == Py_None) 1323254721Semaste return lldb::ScriptInterpreterObjectSP(); 1324254721Semaste 1325254721Semaste PyObject* pmeth = PyObject_GetAttrString(implementor, callee_name); 1326254721Semaste 1327254721Semaste if (PyErr_Occurred()) 1328254721Semaste { 1329254721Semaste PyErr_Clear(); 1330254721Semaste } 1331254721Semaste 1332254721Semaste if (pmeth == NULL || pmeth == Py_None) 1333254721Semaste { 1334254721Semaste Py_XDECREF(pmeth); 1335254721Semaste return lldb::ScriptInterpreterObjectSP(); 1336254721Semaste } 1337254721Semaste 1338254721Semaste if (PyCallable_Check(pmeth) == 0) 1339254721Semaste { 1340254721Semaste if (PyErr_Occurred()) 1341254721Semaste { 1342254721Semaste PyErr_Clear(); 1343254721Semaste } 1344254721Semaste 1345254721Semaste Py_XDECREF(pmeth); 1346254721Semaste return lldb::ScriptInterpreterObjectSP(); 1347254721Semaste } 1348254721Semaste 1349254721Semaste if (PyErr_Occurred()) 1350254721Semaste { 1351254721Semaste PyErr_Clear(); 1352254721Semaste } 1353254721Semaste 1354254721Semaste Py_XDECREF(pmeth); 1355254721Semaste 1356254721Semaste // right now we know this function exists and is callable.. 1357254721Semaste PyObject* py_return = PyObject_CallMethod(implementor, callee_name, NULL); 1358254721Semaste 1359254721Semaste // if it fails, print the error but otherwise go on 1360254721Semaste if (PyErr_Occurred()) 1361254721Semaste { 1362254721Semaste PyErr_Print(); 1363254721Semaste PyErr_Clear(); 1364254721Semaste } 1365254721Semaste 1366254721Semaste return MakeScriptObject(py_return); 1367254721Semaste} 1368254721Semaste 1369254721Semastelldb::ScriptInterpreterObjectSP 1370254721SemasteScriptInterpreterPython::OSPlugin_ThreadsInfo (lldb::ScriptInterpreterObjectSP os_plugin_object_sp) 1371254721Semaste{ 1372269024Semaste Locker py_lock (this, 1373269024Semaste Locker::AcquireLock | Locker::NoSTDIN, 1374269024Semaste Locker::FreeLock); 1375254721Semaste 1376254721Semaste static char callee_name[] = "get_thread_info"; 1377254721Semaste 1378254721Semaste if (!os_plugin_object_sp) 1379254721Semaste return lldb::ScriptInterpreterObjectSP(); 1380254721Semaste 1381254721Semaste PyObject* implementor = (PyObject*)os_plugin_object_sp->GetObject(); 1382254721Semaste 1383254721Semaste if (implementor == NULL || implementor == Py_None) 1384254721Semaste return lldb::ScriptInterpreterObjectSP(); 1385254721Semaste 1386254721Semaste PyObject* pmeth = PyObject_GetAttrString(implementor, callee_name); 1387254721Semaste 1388254721Semaste if (PyErr_Occurred()) 1389254721Semaste { 1390254721Semaste PyErr_Clear(); 1391254721Semaste } 1392254721Semaste 1393254721Semaste if (pmeth == NULL || pmeth == Py_None) 1394254721Semaste { 1395254721Semaste Py_XDECREF(pmeth); 1396254721Semaste return lldb::ScriptInterpreterObjectSP(); 1397254721Semaste } 1398254721Semaste 1399254721Semaste if (PyCallable_Check(pmeth) == 0) 1400254721Semaste { 1401254721Semaste if (PyErr_Occurred()) 1402254721Semaste { 1403254721Semaste PyErr_Clear(); 1404254721Semaste } 1405254721Semaste 1406254721Semaste Py_XDECREF(pmeth); 1407254721Semaste return lldb::ScriptInterpreterObjectSP(); 1408254721Semaste } 1409254721Semaste 1410254721Semaste if (PyErr_Occurred()) 1411254721Semaste { 1412254721Semaste PyErr_Clear(); 1413254721Semaste } 1414254721Semaste 1415254721Semaste Py_XDECREF(pmeth); 1416254721Semaste 1417254721Semaste // right now we know this function exists and is callable.. 1418254721Semaste PyObject* py_return = PyObject_CallMethod(implementor, callee_name, NULL); 1419254721Semaste 1420254721Semaste // if it fails, print the error but otherwise go on 1421254721Semaste if (PyErr_Occurred()) 1422254721Semaste { 1423254721Semaste PyErr_Print(); 1424254721Semaste PyErr_Clear(); 1425254721Semaste } 1426254721Semaste 1427254721Semaste return MakeScriptObject(py_return); 1428254721Semaste} 1429254721Semaste 1430254721Semaste// GetPythonValueFormatString provides a system independent type safe way to 1431254721Semaste// convert a variable's type into a python value format. Python value formats 1432254721Semaste// are defined in terms of builtin C types and could change from system to 1433254721Semaste// as the underlying typedef for uint* types, size_t, off_t and other values 1434254721Semaste// change. 1435254721Semaste 1436254721Semastetemplate <typename T> 1437254721Semasteconst char *GetPythonValueFormatString(T t) 1438254721Semaste{ 1439254721Semaste assert(!"Unhandled type passed to GetPythonValueFormatString(T), make a specialization of GetPythonValueFormatString() to support this type."); 1440254721Semaste return NULL; 1441254721Semaste} 1442254721Semastetemplate <> const char *GetPythonValueFormatString (char *) { return "s"; } 1443254721Semastetemplate <> const char *GetPythonValueFormatString (char) { return "b"; } 1444254721Semastetemplate <> const char *GetPythonValueFormatString (unsigned char) { return "B"; } 1445254721Semastetemplate <> const char *GetPythonValueFormatString (short) { return "h"; } 1446254721Semastetemplate <> const char *GetPythonValueFormatString (unsigned short) { return "H"; } 1447254721Semastetemplate <> const char *GetPythonValueFormatString (int) { return "i"; } 1448254721Semastetemplate <> const char *GetPythonValueFormatString (unsigned int) { return "I"; } 1449254721Semastetemplate <> const char *GetPythonValueFormatString (long) { return "l"; } 1450254721Semastetemplate <> const char *GetPythonValueFormatString (unsigned long) { return "k"; } 1451254721Semastetemplate <> const char *GetPythonValueFormatString (long long) { return "L"; } 1452254721Semastetemplate <> const char *GetPythonValueFormatString (unsigned long long) { return "K"; } 1453254721Semastetemplate <> const char *GetPythonValueFormatString (float t) { return "f"; } 1454254721Semastetemplate <> const char *GetPythonValueFormatString (double t) { return "d"; } 1455254721Semaste 1456254721Semastelldb::ScriptInterpreterObjectSP 1457254721SemasteScriptInterpreterPython::OSPlugin_RegisterContextData (lldb::ScriptInterpreterObjectSP os_plugin_object_sp, 1458254721Semaste lldb::tid_t tid) 1459254721Semaste{ 1460269024Semaste Locker py_lock (this, 1461269024Semaste Locker::AcquireLock | Locker::NoSTDIN, 1462269024Semaste Locker::FreeLock); 1463254721Semaste 1464254721Semaste static char callee_name[] = "get_register_data"; 1465254721Semaste static char *param_format = const_cast<char *>(GetPythonValueFormatString(tid)); 1466254721Semaste 1467254721Semaste if (!os_plugin_object_sp) 1468254721Semaste return lldb::ScriptInterpreterObjectSP(); 1469254721Semaste 1470254721Semaste PyObject* implementor = (PyObject*)os_plugin_object_sp->GetObject(); 1471254721Semaste 1472254721Semaste if (implementor == NULL || implementor == Py_None) 1473254721Semaste return lldb::ScriptInterpreterObjectSP(); 1474254721Semaste 1475254721Semaste PyObject* pmeth = PyObject_GetAttrString(implementor, callee_name); 1476254721Semaste 1477254721Semaste if (PyErr_Occurred()) 1478254721Semaste { 1479254721Semaste PyErr_Clear(); 1480254721Semaste } 1481254721Semaste 1482254721Semaste if (pmeth == NULL || pmeth == Py_None) 1483254721Semaste { 1484254721Semaste Py_XDECREF(pmeth); 1485254721Semaste return lldb::ScriptInterpreterObjectSP(); 1486254721Semaste } 1487254721Semaste 1488254721Semaste if (PyCallable_Check(pmeth) == 0) 1489254721Semaste { 1490254721Semaste if (PyErr_Occurred()) 1491254721Semaste { 1492254721Semaste PyErr_Clear(); 1493254721Semaste } 1494254721Semaste 1495254721Semaste Py_XDECREF(pmeth); 1496254721Semaste return lldb::ScriptInterpreterObjectSP(); 1497254721Semaste } 1498254721Semaste 1499254721Semaste if (PyErr_Occurred()) 1500254721Semaste { 1501254721Semaste PyErr_Clear(); 1502254721Semaste } 1503254721Semaste 1504254721Semaste Py_XDECREF(pmeth); 1505254721Semaste 1506254721Semaste // right now we know this function exists and is callable.. 1507254721Semaste PyObject* py_return = PyObject_CallMethod(implementor, callee_name, param_format, tid); 1508254721Semaste 1509254721Semaste // if it fails, print the error but otherwise go on 1510254721Semaste if (PyErr_Occurred()) 1511254721Semaste { 1512254721Semaste PyErr_Print(); 1513254721Semaste PyErr_Clear(); 1514254721Semaste } 1515254721Semaste 1516254721Semaste return MakeScriptObject(py_return); 1517254721Semaste} 1518254721Semaste 1519254721Semastelldb::ScriptInterpreterObjectSP 1520254721SemasteScriptInterpreterPython::OSPlugin_CreateThread (lldb::ScriptInterpreterObjectSP os_plugin_object_sp, 1521254721Semaste lldb::tid_t tid, 1522254721Semaste lldb::addr_t context) 1523254721Semaste{ 1524269024Semaste Locker py_lock(this, 1525269024Semaste Locker::AcquireLock | Locker::NoSTDIN, 1526269024Semaste Locker::FreeLock); 1527254721Semaste 1528254721Semaste static char callee_name[] = "create_thread"; 1529254721Semaste std::string param_format; 1530254721Semaste param_format += GetPythonValueFormatString(tid); 1531254721Semaste param_format += GetPythonValueFormatString(context); 1532254721Semaste 1533254721Semaste if (!os_plugin_object_sp) 1534254721Semaste return lldb::ScriptInterpreterObjectSP(); 1535254721Semaste 1536254721Semaste PyObject* implementor = (PyObject*)os_plugin_object_sp->GetObject(); 1537254721Semaste 1538254721Semaste if (implementor == NULL || implementor == Py_None) 1539254721Semaste return lldb::ScriptInterpreterObjectSP(); 1540254721Semaste 1541254721Semaste PyObject* pmeth = PyObject_GetAttrString(implementor, callee_name); 1542254721Semaste 1543254721Semaste if (PyErr_Occurred()) 1544254721Semaste { 1545254721Semaste PyErr_Clear(); 1546254721Semaste } 1547254721Semaste 1548254721Semaste if (pmeth == NULL || pmeth == Py_None) 1549254721Semaste { 1550254721Semaste Py_XDECREF(pmeth); 1551254721Semaste return lldb::ScriptInterpreterObjectSP(); 1552254721Semaste } 1553254721Semaste 1554254721Semaste if (PyCallable_Check(pmeth) == 0) 1555254721Semaste { 1556254721Semaste if (PyErr_Occurred()) 1557254721Semaste { 1558254721Semaste PyErr_Clear(); 1559254721Semaste } 1560254721Semaste 1561254721Semaste Py_XDECREF(pmeth); 1562254721Semaste return lldb::ScriptInterpreterObjectSP(); 1563254721Semaste } 1564254721Semaste 1565254721Semaste if (PyErr_Occurred()) 1566254721Semaste { 1567254721Semaste PyErr_Clear(); 1568254721Semaste } 1569254721Semaste 1570254721Semaste Py_XDECREF(pmeth); 1571254721Semaste 1572254721Semaste // right now we know this function exists and is callable.. 1573254721Semaste PyObject* py_return = PyObject_CallMethod(implementor, callee_name, ¶m_format[0], tid, context); 1574254721Semaste 1575254721Semaste // if it fails, print the error but otherwise go on 1576254721Semaste if (PyErr_Occurred()) 1577254721Semaste { 1578254721Semaste PyErr_Print(); 1579254721Semaste PyErr_Clear(); 1580254721Semaste } 1581254721Semaste 1582254721Semaste return MakeScriptObject(py_return); 1583254721Semaste} 1584254721Semaste 1585254721Semastelldb::ScriptInterpreterObjectSP 1586263363SemasteScriptInterpreterPython::LoadPluginModule (const FileSpec& file_spec, 1587263363Semaste lldb_private::Error& error) 1588263363Semaste{ 1589263363Semaste if (!file_spec.Exists()) 1590263363Semaste { 1591263363Semaste error.SetErrorString("no such file"); 1592263363Semaste return lldb::ScriptInterpreterObjectSP(); 1593263363Semaste } 1594263363Semaste 1595263363Semaste ScriptInterpreterObjectSP module_sp; 1596263363Semaste 1597263363Semaste if (LoadScriptingModule(file_spec.GetPath().c_str(),true,true,error,&module_sp)) 1598263363Semaste return module_sp; 1599263363Semaste 1600263363Semaste return lldb::ScriptInterpreterObjectSP(); 1601263363Semaste} 1602263363Semaste 1603263363Semastelldb::ScriptInterpreterObjectSP 1604263363SemasteScriptInterpreterPython::GetDynamicSettings (lldb::ScriptInterpreterObjectSP plugin_module_sp, 1605263363Semaste Target* target, 1606263363Semaste const char* setting_name, 1607263363Semaste lldb_private::Error& error) 1608263363Semaste{ 1609263363Semaste if (!plugin_module_sp || !target || !setting_name || !setting_name[0]) 1610263363Semaste return lldb::ScriptInterpreterObjectSP(); 1611263363Semaste 1612263363Semaste if (!g_swig_plugin_get) 1613263363Semaste return lldb::ScriptInterpreterObjectSP(); 1614263363Semaste 1615263363Semaste PyObject *reply_pyobj = nullptr; 1616263363Semaste 1617263363Semaste { 1618269024Semaste Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1619263363Semaste TargetSP target_sp(target->shared_from_this()); 1620263363Semaste reply_pyobj = (PyObject*)g_swig_plugin_get(plugin_module_sp->GetObject(),setting_name,target_sp); 1621263363Semaste } 1622263363Semaste 1623263363Semaste return MakeScriptObject(reply_pyobj); 1624263363Semaste} 1625263363Semaste 1626263363Semastelldb::ScriptInterpreterObjectSP 1627254721SemasteScriptInterpreterPython::CreateSyntheticScriptedProvider (const char *class_name, 1628254721Semaste lldb::ValueObjectSP valobj) 1629254721Semaste{ 1630254721Semaste if (class_name == NULL || class_name[0] == '\0') 1631254721Semaste return lldb::ScriptInterpreterObjectSP(); 1632254721Semaste 1633254721Semaste if (!valobj.get()) 1634254721Semaste return lldb::ScriptInterpreterObjectSP(); 1635254721Semaste 1636254721Semaste ExecutionContext exe_ctx (valobj->GetExecutionContextRef()); 1637254721Semaste Target *target = exe_ctx.GetTargetPtr(); 1638254721Semaste 1639254721Semaste if (!target) 1640254721Semaste return lldb::ScriptInterpreterObjectSP(); 1641254721Semaste 1642254721Semaste Debugger &debugger = target->GetDebugger(); 1643254721Semaste ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter(); 1644254721Semaste ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter; 1645254721Semaste 1646254721Semaste if (!script_interpreter) 1647254721Semaste return lldb::ScriptInterpreterObjectSP(); 1648254721Semaste 1649254721Semaste void* ret_val; 1650254721Semaste 1651254721Semaste { 1652269024Semaste Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1653254721Semaste ret_val = g_swig_synthetic_script (class_name, 1654254721Semaste python_interpreter->m_dictionary_name.c_str(), 1655254721Semaste valobj); 1656254721Semaste } 1657254721Semaste 1658254721Semaste return MakeScriptObject(ret_val); 1659254721Semaste} 1660254721Semaste 1661254721Semastebool 1662254721SemasteScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, std::string& output, void* name_token) 1663254721Semaste{ 1664254721Semaste StringList input; 1665254721Semaste input.SplitIntoLines(oneliner, strlen(oneliner)); 1666254721Semaste return GenerateTypeScriptFunction(input, output, name_token); 1667254721Semaste} 1668254721Semaste 1669254721Semastebool 1670254721SemasteScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, std::string& output, void* name_token) 1671254721Semaste{ 1672254721Semaste StringList input; 1673254721Semaste input.SplitIntoLines(oneliner, strlen(oneliner)); 1674254721Semaste return GenerateTypeSynthClass(input, output, name_token); 1675254721Semaste} 1676254721Semaste 1677254721Semaste 1678254721Semastebool 1679254721SemasteScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, std::string& output) 1680254721Semaste{ 1681254721Semaste static uint32_t num_created_functions = 0; 1682254721Semaste user_input.RemoveBlankLines (); 1683254721Semaste StreamString sstr; 1684254721Semaste 1685254721Semaste if (user_input.GetSize() == 0) 1686254721Semaste return false; 1687254721Semaste 1688254721Semaste std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_bp_callback_func_",num_created_functions)); 1689254721Semaste sstr.Printf ("def %s (frame, bp_loc, internal_dict):", auto_generated_function_name.c_str()); 1690254721Semaste 1691254721Semaste if (!GenerateFunction(sstr.GetData(), user_input)) 1692254721Semaste return false; 1693254721Semaste 1694254721Semaste // Store the name of the auto-generated function to be called. 1695254721Semaste output.assign(auto_generated_function_name); 1696254721Semaste return true; 1697254721Semaste} 1698254721Semaste 1699254721Semastebool 1700254721SemasteScriptInterpreterPython::GenerateWatchpointCommandCallbackData (StringList &user_input, std::string& output) 1701254721Semaste{ 1702254721Semaste static uint32_t num_created_functions = 0; 1703254721Semaste user_input.RemoveBlankLines (); 1704254721Semaste StreamString sstr; 1705254721Semaste 1706254721Semaste if (user_input.GetSize() == 0) 1707254721Semaste return false; 1708254721Semaste 1709254721Semaste std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_wp_callback_func_",num_created_functions)); 1710254721Semaste sstr.Printf ("def %s (frame, wp, internal_dict):", auto_generated_function_name.c_str()); 1711254721Semaste 1712254721Semaste if (!GenerateFunction(sstr.GetData(), user_input)) 1713254721Semaste return false; 1714254721Semaste 1715254721Semaste // Store the name of the auto-generated function to be called. 1716254721Semaste output.assign(auto_generated_function_name); 1717254721Semaste return true; 1718254721Semaste} 1719254721Semaste 1720254721Semastebool 1721254721SemasteScriptInterpreterPython::GetScriptedSummary (const char *python_function_name, 1722254721Semaste lldb::ValueObjectSP valobj, 1723254721Semaste lldb::ScriptInterpreterObjectSP& callee_wrapper_sp, 1724254721Semaste std::string& retval) 1725254721Semaste{ 1726254721Semaste 1727254721Semaste Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); 1728254721Semaste 1729254721Semaste if (!valobj.get()) 1730254721Semaste { 1731254721Semaste retval.assign("<no object>"); 1732254721Semaste return false; 1733254721Semaste } 1734254721Semaste 1735254721Semaste void* old_callee = (callee_wrapper_sp ? callee_wrapper_sp->GetObject() : NULL); 1736254721Semaste void* new_callee = old_callee; 1737254721Semaste 1738254721Semaste bool ret_val; 1739254721Semaste if (python_function_name 1740254721Semaste && *python_function_name) 1741254721Semaste { 1742254721Semaste { 1743269024Semaste Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1744254721Semaste { 1745269024Semaste Timer scoped_timer ("g_swig_typescript_callback","g_swig_typescript_callback"); 1746269024Semaste ret_val = g_swig_typescript_callback (python_function_name, 1747269024Semaste GetSessionDictionary().get(), 1748269024Semaste valobj, 1749269024Semaste &new_callee, 1750269024Semaste retval); 1751254721Semaste } 1752254721Semaste } 1753254721Semaste } 1754254721Semaste else 1755254721Semaste { 1756254721Semaste retval.assign("<no function name>"); 1757254721Semaste return false; 1758254721Semaste } 1759254721Semaste 1760254721Semaste if (new_callee && old_callee != new_callee) 1761254721Semaste callee_wrapper_sp = MakeScriptObject(new_callee); 1762254721Semaste 1763254721Semaste return ret_val; 1764254721Semaste 1765254721Semaste} 1766254721Semaste 1767254721Semastebool 1768254721SemasteScriptInterpreterPython::BreakpointCallbackFunction 1769254721Semaste( 1770254721Semaste void *baton, 1771254721Semaste StoppointCallbackContext *context, 1772254721Semaste user_id_t break_id, 1773254721Semaste user_id_t break_loc_id 1774254721Semaste) 1775254721Semaste{ 1776254721Semaste BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton; 1777254721Semaste const char *python_function_name = bp_option_data->script_source.c_str(); 1778254721Semaste 1779254721Semaste if (!context) 1780254721Semaste return true; 1781254721Semaste 1782254721Semaste ExecutionContext exe_ctx (context->exe_ctx_ref); 1783254721Semaste Target *target = exe_ctx.GetTargetPtr(); 1784254721Semaste 1785254721Semaste if (!target) 1786254721Semaste return true; 1787254721Semaste 1788254721Semaste Debugger &debugger = target->GetDebugger(); 1789254721Semaste ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter(); 1790254721Semaste ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter; 1791254721Semaste 1792254721Semaste if (!script_interpreter) 1793254721Semaste return true; 1794254721Semaste 1795269024Semaste if (python_function_name && python_function_name[0]) 1796254721Semaste { 1797254721Semaste const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP()); 1798254721Semaste BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id); 1799254721Semaste if (breakpoint_sp) 1800254721Semaste { 1801254721Semaste const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id)); 1802254721Semaste 1803254721Semaste if (stop_frame_sp && bp_loc_sp) 1804254721Semaste { 1805254721Semaste bool ret_val = true; 1806254721Semaste { 1807269024Semaste Locker py_lock(python_interpreter, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1808269024Semaste ret_val = g_swig_breakpoint_callback (python_function_name, 1809254721Semaste python_interpreter->m_dictionary_name.c_str(), 1810254721Semaste stop_frame_sp, 1811254721Semaste bp_loc_sp); 1812254721Semaste } 1813254721Semaste return ret_val; 1814254721Semaste } 1815254721Semaste } 1816254721Semaste } 1817254721Semaste // We currently always true so we stop in case anything goes wrong when 1818254721Semaste // trying to call the script function 1819254721Semaste return true; 1820254721Semaste} 1821254721Semaste 1822254721Semastebool 1823254721SemasteScriptInterpreterPython::WatchpointCallbackFunction 1824254721Semaste( 1825254721Semaste void *baton, 1826254721Semaste StoppointCallbackContext *context, 1827254721Semaste user_id_t watch_id 1828254721Semaste) 1829254721Semaste{ 1830254721Semaste WatchpointOptions::CommandData *wp_option_data = (WatchpointOptions::CommandData *) baton; 1831254721Semaste const char *python_function_name = wp_option_data->script_source.c_str(); 1832254721Semaste 1833254721Semaste if (!context) 1834254721Semaste return true; 1835254721Semaste 1836254721Semaste ExecutionContext exe_ctx (context->exe_ctx_ref); 1837254721Semaste Target *target = exe_ctx.GetTargetPtr(); 1838254721Semaste 1839254721Semaste if (!target) 1840254721Semaste return true; 1841254721Semaste 1842254721Semaste Debugger &debugger = target->GetDebugger(); 1843254721Semaste ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter(); 1844254721Semaste ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter; 1845254721Semaste 1846254721Semaste if (!script_interpreter) 1847254721Semaste return true; 1848254721Semaste 1849269024Semaste if (python_function_name && python_function_name[0]) 1850254721Semaste { 1851254721Semaste const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP()); 1852254721Semaste WatchpointSP wp_sp = target->GetWatchpointList().FindByID (watch_id); 1853254721Semaste if (wp_sp) 1854254721Semaste { 1855254721Semaste if (stop_frame_sp && wp_sp) 1856254721Semaste { 1857254721Semaste bool ret_val = true; 1858254721Semaste { 1859269024Semaste Locker py_lock(python_interpreter, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1860269024Semaste ret_val = g_swig_watchpoint_callback (python_function_name, 1861254721Semaste python_interpreter->m_dictionary_name.c_str(), 1862254721Semaste stop_frame_sp, 1863254721Semaste wp_sp); 1864254721Semaste } 1865254721Semaste return ret_val; 1866254721Semaste } 1867254721Semaste } 1868254721Semaste } 1869254721Semaste // We currently always true so we stop in case anything goes wrong when 1870254721Semaste // trying to call the script function 1871254721Semaste return true; 1872254721Semaste} 1873254721Semaste 1874254721Semastesize_t 1875254721SemasteScriptInterpreterPython::CalculateNumChildren (const lldb::ScriptInterpreterObjectSP& implementor_sp) 1876254721Semaste{ 1877254721Semaste if (!implementor_sp) 1878254721Semaste return 0; 1879254721Semaste 1880254721Semaste void* implementor = implementor_sp->GetObject(); 1881254721Semaste 1882254721Semaste if (!implementor) 1883254721Semaste return 0; 1884254721Semaste 1885254721Semaste if (!g_swig_calc_children) 1886254721Semaste return 0; 1887254721Semaste 1888254721Semaste uint32_t ret_val = 0; 1889254721Semaste 1890254721Semaste { 1891269024Semaste Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1892254721Semaste ret_val = g_swig_calc_children (implementor); 1893254721Semaste } 1894254721Semaste 1895254721Semaste return ret_val; 1896254721Semaste} 1897254721Semaste 1898254721Semastelldb::ValueObjectSP 1899254721SemasteScriptInterpreterPython::GetChildAtIndex (const lldb::ScriptInterpreterObjectSP& implementor_sp, uint32_t idx) 1900254721Semaste{ 1901254721Semaste if (!implementor_sp) 1902254721Semaste return lldb::ValueObjectSP(); 1903254721Semaste 1904254721Semaste void* implementor = implementor_sp->GetObject(); 1905254721Semaste 1906254721Semaste if (!implementor) 1907254721Semaste return lldb::ValueObjectSP(); 1908254721Semaste 1909254721Semaste if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue) 1910254721Semaste return lldb::ValueObjectSP(); 1911254721Semaste 1912254721Semaste lldb::ValueObjectSP ret_val; 1913254721Semaste 1914254721Semaste { 1915269024Semaste Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1916263363Semaste void* child_ptr = g_swig_get_child_index (implementor,idx); 1917254721Semaste if (child_ptr != NULL && child_ptr != Py_None) 1918254721Semaste { 1919263363Semaste lldb::SBValue* sb_value_ptr = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr); 1920263363Semaste if (sb_value_ptr == NULL) 1921254721Semaste Py_XDECREF(child_ptr); 1922254721Semaste else 1923263363Semaste ret_val = g_swig_get_valobj_sp_from_sbvalue (sb_value_ptr); 1924254721Semaste } 1925254721Semaste else 1926254721Semaste { 1927254721Semaste Py_XDECREF(child_ptr); 1928254721Semaste } 1929254721Semaste } 1930254721Semaste 1931254721Semaste return ret_val; 1932254721Semaste} 1933254721Semaste 1934254721Semasteint 1935254721SemasteScriptInterpreterPython::GetIndexOfChildWithName (const lldb::ScriptInterpreterObjectSP& implementor_sp, const char* child_name) 1936254721Semaste{ 1937254721Semaste if (!implementor_sp) 1938254721Semaste return UINT32_MAX; 1939254721Semaste 1940254721Semaste void* implementor = implementor_sp->GetObject(); 1941254721Semaste 1942254721Semaste if (!implementor) 1943254721Semaste return UINT32_MAX; 1944254721Semaste 1945254721Semaste if (!g_swig_get_index_child) 1946254721Semaste return UINT32_MAX; 1947254721Semaste 1948254721Semaste int ret_val = UINT32_MAX; 1949254721Semaste 1950254721Semaste { 1951269024Semaste Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1952254721Semaste ret_val = g_swig_get_index_child (implementor, child_name); 1953254721Semaste } 1954254721Semaste 1955254721Semaste return ret_val; 1956254721Semaste} 1957254721Semaste 1958254721Semastebool 1959254721SemasteScriptInterpreterPython::UpdateSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp) 1960254721Semaste{ 1961254721Semaste bool ret_val = false; 1962254721Semaste 1963254721Semaste if (!implementor_sp) 1964254721Semaste return ret_val; 1965254721Semaste 1966254721Semaste void* implementor = implementor_sp->GetObject(); 1967254721Semaste 1968254721Semaste if (!implementor) 1969254721Semaste return ret_val; 1970254721Semaste 1971254721Semaste if (!g_swig_update_provider) 1972254721Semaste return ret_val; 1973254721Semaste 1974254721Semaste { 1975269024Semaste Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1976254721Semaste ret_val = g_swig_update_provider (implementor); 1977254721Semaste } 1978254721Semaste 1979254721Semaste return ret_val; 1980254721Semaste} 1981254721Semaste 1982254721Semastebool 1983254721SemasteScriptInterpreterPython::MightHaveChildrenSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp) 1984254721Semaste{ 1985254721Semaste bool ret_val = false; 1986254721Semaste 1987254721Semaste if (!implementor_sp) 1988254721Semaste return ret_val; 1989254721Semaste 1990254721Semaste void* implementor = implementor_sp->GetObject(); 1991254721Semaste 1992254721Semaste if (!implementor) 1993254721Semaste return ret_val; 1994254721Semaste 1995254721Semaste if (!g_swig_mighthavechildren_provider) 1996254721Semaste return ret_val; 1997254721Semaste 1998254721Semaste { 1999269024Semaste Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2000254721Semaste ret_val = g_swig_mighthavechildren_provider (implementor); 2001254721Semaste } 2002254721Semaste 2003254721Semaste return ret_val; 2004254721Semaste} 2005254721Semaste 2006254721Semastestatic std::string 2007254721SemasteReadPythonBacktrace (PyObject* py_backtrace) 2008254721Semaste{ 2009254721Semaste PyObject* traceback_module = NULL, 2010254721Semaste *stringIO_module = NULL, 2011254721Semaste *stringIO_builder = NULL, 2012254721Semaste *stringIO_buffer = NULL, 2013254721Semaste *printTB = NULL, 2014254721Semaste *printTB_args = NULL, 2015254721Semaste *printTB_result = NULL, 2016254721Semaste *stringIO_getvalue = NULL, 2017254721Semaste *printTB_string = NULL; 2018254721Semaste 2019254721Semaste std::string retval("backtrace unavailable"); 2020254721Semaste 2021254721Semaste if (py_backtrace && py_backtrace != Py_None) 2022254721Semaste { 2023254721Semaste traceback_module = PyImport_ImportModule("traceback"); 2024254721Semaste stringIO_module = PyImport_ImportModule("StringIO"); 2025254721Semaste 2026254721Semaste if (traceback_module && traceback_module != Py_None && stringIO_module && stringIO_module != Py_None) 2027254721Semaste { 2028254721Semaste stringIO_builder = PyObject_GetAttrString(stringIO_module, "StringIO"); 2029254721Semaste if (stringIO_builder && stringIO_builder != Py_None) 2030254721Semaste { 2031254721Semaste stringIO_buffer = PyObject_CallObject(stringIO_builder, NULL); 2032254721Semaste if (stringIO_buffer && stringIO_buffer != Py_None) 2033254721Semaste { 2034254721Semaste printTB = PyObject_GetAttrString(traceback_module, "print_tb"); 2035254721Semaste if (printTB && printTB != Py_None) 2036254721Semaste { 2037254721Semaste printTB_args = Py_BuildValue("OOO",py_backtrace,Py_None,stringIO_buffer); 2038254721Semaste printTB_result = PyObject_CallObject(printTB, printTB_args); 2039254721Semaste stringIO_getvalue = PyObject_GetAttrString(stringIO_buffer, "getvalue"); 2040254721Semaste if (stringIO_getvalue && stringIO_getvalue != Py_None) 2041254721Semaste { 2042254721Semaste printTB_string = PyObject_CallObject (stringIO_getvalue,NULL); 2043254721Semaste if (printTB_string && printTB_string != Py_None && PyString_Check(printTB_string)) 2044254721Semaste retval.assign(PyString_AsString(printTB_string)); 2045254721Semaste } 2046254721Semaste } 2047254721Semaste } 2048254721Semaste } 2049254721Semaste } 2050254721Semaste } 2051254721Semaste Py_XDECREF(traceback_module); 2052254721Semaste Py_XDECREF(stringIO_module); 2053254721Semaste Py_XDECREF(stringIO_builder); 2054254721Semaste Py_XDECREF(stringIO_buffer); 2055254721Semaste Py_XDECREF(printTB); 2056254721Semaste Py_XDECREF(printTB_args); 2057254721Semaste Py_XDECREF(printTB_result); 2058254721Semaste Py_XDECREF(stringIO_getvalue); 2059254721Semaste Py_XDECREF(printTB_string); 2060254721Semaste return retval; 2061254721Semaste} 2062254721Semaste 2063254721Semastebool 2064254721SemasteScriptInterpreterPython::RunScriptFormatKeyword (const char* impl_function, 2065254721Semaste Process* process, 2066254721Semaste std::string& output, 2067254721Semaste Error& error) 2068254721Semaste{ 2069254721Semaste bool ret_val; 2070254721Semaste if (!process) 2071254721Semaste { 2072254721Semaste error.SetErrorString("no process"); 2073254721Semaste return false; 2074254721Semaste } 2075254721Semaste if (!impl_function || !impl_function[0]) 2076254721Semaste { 2077254721Semaste error.SetErrorString("no function to execute"); 2078254721Semaste return false; 2079254721Semaste } 2080254721Semaste if (!g_swig_run_script_keyword_process) 2081254721Semaste { 2082254721Semaste error.SetErrorString("internal helper function missing"); 2083254721Semaste return false; 2084254721Semaste } 2085254721Semaste { 2086254721Semaste ProcessSP process_sp(process->shared_from_this()); 2087269024Semaste Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2088254721Semaste ret_val = g_swig_run_script_keyword_process (impl_function, m_dictionary_name.c_str(), process_sp, output); 2089254721Semaste if (!ret_val) 2090254721Semaste error.SetErrorString("python script evaluation failed"); 2091254721Semaste } 2092254721Semaste return ret_val; 2093254721Semaste} 2094254721Semaste 2095254721Semastebool 2096254721SemasteScriptInterpreterPython::RunScriptFormatKeyword (const char* impl_function, 2097254721Semaste Thread* thread, 2098254721Semaste std::string& output, 2099254721Semaste Error& error) 2100254721Semaste{ 2101254721Semaste bool ret_val; 2102254721Semaste if (!thread) 2103254721Semaste { 2104254721Semaste error.SetErrorString("no thread"); 2105254721Semaste return false; 2106254721Semaste } 2107254721Semaste if (!impl_function || !impl_function[0]) 2108254721Semaste { 2109254721Semaste error.SetErrorString("no function to execute"); 2110254721Semaste return false; 2111254721Semaste } 2112254721Semaste if (!g_swig_run_script_keyword_thread) 2113254721Semaste { 2114254721Semaste error.SetErrorString("internal helper function missing"); 2115254721Semaste return false; 2116254721Semaste } 2117254721Semaste { 2118254721Semaste ThreadSP thread_sp(thread->shared_from_this()); 2119269024Semaste Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2120254721Semaste ret_val = g_swig_run_script_keyword_thread (impl_function, m_dictionary_name.c_str(), thread_sp, output); 2121254721Semaste if (!ret_val) 2122254721Semaste error.SetErrorString("python script evaluation failed"); 2123254721Semaste } 2124254721Semaste return ret_val; 2125254721Semaste} 2126254721Semaste 2127254721Semastebool 2128254721SemasteScriptInterpreterPython::RunScriptFormatKeyword (const char* impl_function, 2129254721Semaste Target* target, 2130254721Semaste std::string& output, 2131254721Semaste Error& error) 2132254721Semaste{ 2133254721Semaste bool ret_val; 2134254721Semaste if (!target) 2135254721Semaste { 2136254721Semaste error.SetErrorString("no thread"); 2137254721Semaste return false; 2138254721Semaste } 2139254721Semaste if (!impl_function || !impl_function[0]) 2140254721Semaste { 2141254721Semaste error.SetErrorString("no function to execute"); 2142254721Semaste return false; 2143254721Semaste } 2144254721Semaste if (!g_swig_run_script_keyword_target) 2145254721Semaste { 2146254721Semaste error.SetErrorString("internal helper function missing"); 2147254721Semaste return false; 2148254721Semaste } 2149254721Semaste { 2150254721Semaste TargetSP target_sp(target->shared_from_this()); 2151269024Semaste Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2152254721Semaste ret_val = g_swig_run_script_keyword_target (impl_function, m_dictionary_name.c_str(), target_sp, output); 2153254721Semaste if (!ret_val) 2154254721Semaste error.SetErrorString("python script evaluation failed"); 2155254721Semaste } 2156254721Semaste return ret_val; 2157254721Semaste} 2158254721Semaste 2159254721Semastebool 2160254721SemasteScriptInterpreterPython::RunScriptFormatKeyword (const char* impl_function, 2161254721Semaste StackFrame* frame, 2162254721Semaste std::string& output, 2163254721Semaste Error& error) 2164254721Semaste{ 2165254721Semaste bool ret_val; 2166254721Semaste if (!frame) 2167254721Semaste { 2168254721Semaste error.SetErrorString("no frame"); 2169254721Semaste return false; 2170254721Semaste } 2171254721Semaste if (!impl_function || !impl_function[0]) 2172254721Semaste { 2173254721Semaste error.SetErrorString("no function to execute"); 2174254721Semaste return false; 2175254721Semaste } 2176254721Semaste if (!g_swig_run_script_keyword_frame) 2177254721Semaste { 2178254721Semaste error.SetErrorString("internal helper function missing"); 2179254721Semaste return false; 2180254721Semaste } 2181254721Semaste { 2182254721Semaste StackFrameSP frame_sp(frame->shared_from_this()); 2183269024Semaste Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2184254721Semaste ret_val = g_swig_run_script_keyword_frame (impl_function, m_dictionary_name.c_str(), frame_sp, output); 2185254721Semaste if (!ret_val) 2186254721Semaste error.SetErrorString("python script evaluation failed"); 2187254721Semaste } 2188254721Semaste return ret_val; 2189254721Semaste} 2190254721Semaste 2191254721Semasteuint64_t replace_all(std::string& str, const std::string& oldStr, const std::string& newStr) 2192254721Semaste{ 2193254721Semaste size_t pos = 0; 2194254721Semaste uint64_t matches = 0; 2195254721Semaste while((pos = str.find(oldStr, pos)) != std::string::npos) 2196254721Semaste { 2197254721Semaste matches++; 2198254721Semaste str.replace(pos, oldStr.length(), newStr); 2199254721Semaste pos += newStr.length(); 2200254721Semaste } 2201254721Semaste return matches; 2202254721Semaste} 2203254721Semaste 2204254721Semastebool 2205254721SemasteScriptInterpreterPython::LoadScriptingModule (const char* pathname, 2206254721Semaste bool can_reload, 2207254721Semaste bool init_session, 2208263363Semaste lldb_private::Error& error, 2209263363Semaste lldb::ScriptInterpreterObjectSP* module_sp) 2210254721Semaste{ 2211254721Semaste if (!pathname || !pathname[0]) 2212254721Semaste { 2213254721Semaste error.SetErrorString("invalid pathname"); 2214254721Semaste return false; 2215254721Semaste } 2216254721Semaste 2217254721Semaste if (!g_swig_call_module_init) 2218254721Semaste { 2219254721Semaste error.SetErrorString("internal helper function missing"); 2220254721Semaste return false; 2221254721Semaste } 2222254721Semaste 2223254721Semaste lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this(); 2224254721Semaste 2225254721Semaste { 2226254721Semaste FileSpec target_file(pathname, true); 2227254721Semaste std::string basename(target_file.GetFilename().GetCString()); 2228254721Semaste 2229254721Semaste StreamString command_stream; 2230254721Semaste 2231254721Semaste // Before executing Pyton code, lock the GIL. 2232254721Semaste Locker py_lock (this, 2233269024Semaste Locker::AcquireLock | (init_session ? Locker::InitSession : 0) | Locker::NoSTDIN, 2234254721Semaste Locker::FreeAcquiredLock | (init_session ? Locker::TearDownSession : 0)); 2235254721Semaste 2236254721Semaste if (target_file.GetFileType() == FileSpec::eFileTypeInvalid || 2237254721Semaste target_file.GetFileType() == FileSpec::eFileTypeUnknown) 2238254721Semaste { 2239254721Semaste // if not a valid file of any sort, check if it might be a filename still 2240254721Semaste // dot can't be used but / and \ can, and if either is found, reject 2241254721Semaste if (strchr(pathname,'\\') || strchr(pathname,'/')) 2242254721Semaste { 2243254721Semaste error.SetErrorString("invalid pathname"); 2244254721Semaste return false; 2245254721Semaste } 2246254721Semaste basename = pathname; // not a filename, probably a package of some sort, let it go through 2247254721Semaste } 2248254721Semaste else if (target_file.GetFileType() == FileSpec::eFileTypeDirectory || 2249254721Semaste target_file.GetFileType() == FileSpec::eFileTypeRegular || 2250254721Semaste target_file.GetFileType() == FileSpec::eFileTypeSymbolicLink) 2251254721Semaste { 2252254721Semaste std::string directory(target_file.GetDirectory().GetCString()); 2253254721Semaste replace_all(directory,"'","\\'"); 2254254721Semaste 2255254721Semaste // now make sure that Python has "directory" in the search path 2256254721Semaste StreamString command_stream; 2257254721Semaste command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.insert(1,'%s');\n\n", 2258254721Semaste directory.c_str(), 2259254721Semaste directory.c_str()); 2260269024Semaste bool syspath_retval = ExecuteMultipleLines(command_stream.GetData(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false).SetSetLLDBGlobals(false)).Success(); 2261254721Semaste if (!syspath_retval) 2262254721Semaste { 2263254721Semaste error.SetErrorString("Python sys.path handling failed"); 2264254721Semaste return false; 2265254721Semaste } 2266254721Semaste 2267254721Semaste // strip .py or .pyc extension 2268254721Semaste ConstString extension = target_file.GetFileNameExtension(); 2269254721Semaste if (extension) 2270254721Semaste { 2271254721Semaste if (::strcmp(extension.GetCString(), "py") == 0) 2272254721Semaste basename.resize(basename.length()-3); 2273254721Semaste else if(::strcmp(extension.GetCString(), "pyc") == 0) 2274254721Semaste basename.resize(basename.length()-4); 2275254721Semaste } 2276254721Semaste } 2277254721Semaste else 2278254721Semaste { 2279254721Semaste error.SetErrorString("no known way to import this module specification"); 2280254721Semaste return false; 2281254721Semaste } 2282254721Semaste 2283254721Semaste // check if the module is already import-ed 2284254721Semaste command_stream.Clear(); 2285254721Semaste command_stream.Printf("sys.modules.__contains__('%s')",basename.c_str()); 2286254721Semaste bool does_contain = false; 2287254721Semaste // this call will succeed if the module was ever imported in any Debugger in the lifetime of the process 2288254721Semaste // in which this LLDB framework is living 2289254721Semaste bool was_imported_globally = (ExecuteOneLineWithReturn(command_stream.GetData(), 2290254721Semaste ScriptInterpreterPython::eScriptReturnTypeBool, 2291254721Semaste &does_contain, 2292254721Semaste ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false).SetSetLLDBGlobals(false)) && does_contain); 2293254721Semaste // this call will fail if the module was not imported in this Debugger before 2294254721Semaste command_stream.Clear(); 2295254721Semaste command_stream.Printf("sys.getrefcount(%s)",basename.c_str()); 2296269024Semaste bool was_imported_locally = !(GetSessionDictionary().GetItemForKey(basename.c_str()).IsNULLOrNone()); 2297254721Semaste 2298254721Semaste bool was_imported = (was_imported_globally || was_imported_locally); 2299254721Semaste 2300254721Semaste if (was_imported == true && can_reload == false) 2301254721Semaste { 2302254721Semaste error.SetErrorString("module already imported"); 2303254721Semaste return false; 2304254721Semaste } 2305254721Semaste 2306254721Semaste // now actually do the import 2307254721Semaste command_stream.Clear(); 2308254721Semaste 2309254721Semaste if (was_imported) 2310254721Semaste { 2311254721Semaste if (!was_imported_locally) 2312254721Semaste command_stream.Printf("import %s ; reload(%s)",basename.c_str(),basename.c_str()); 2313254721Semaste else 2314254721Semaste command_stream.Printf("reload(%s)",basename.c_str()); 2315254721Semaste } 2316254721Semaste else 2317254721Semaste command_stream.Printf("import %s",basename.c_str()); 2318254721Semaste 2319269024Semaste error = ExecuteMultipleLines(command_stream.GetData(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false).SetSetLLDBGlobals(false)); 2320269024Semaste if (error.Fail()) 2321254721Semaste return false; 2322254721Semaste 2323254721Semaste // if we are here, everything worked 2324254721Semaste // call __lldb_init_module(debugger,dict) 2325254721Semaste if (!g_swig_call_module_init (basename.c_str(), 2326254721Semaste m_dictionary_name.c_str(), 2327254721Semaste debugger_sp)) 2328254721Semaste { 2329254721Semaste error.SetErrorString("calling __lldb_init_module failed"); 2330254721Semaste return false; 2331254721Semaste } 2332263363Semaste 2333263363Semaste if (module_sp) 2334263363Semaste { 2335263363Semaste // everything went just great, now set the module object 2336263363Semaste command_stream.Clear(); 2337263363Semaste command_stream.Printf("%s",basename.c_str()); 2338263363Semaste void* module_pyobj = nullptr; 2339263363Semaste if (ExecuteOneLineWithReturn(command_stream.GetData(),ScriptInterpreter::eScriptReturnTypeOpaqueObject,&module_pyobj) && module_pyobj) 2340263363Semaste *module_sp = MakeScriptObject(module_pyobj); 2341263363Semaste } 2342263363Semaste 2343254721Semaste return true; 2344254721Semaste } 2345254721Semaste} 2346254721Semaste 2347254721Semastelldb::ScriptInterpreterObjectSP 2348254721SemasteScriptInterpreterPython::MakeScriptObject (void* object) 2349254721Semaste{ 2350254721Semaste return lldb::ScriptInterpreterObjectSP(new ScriptInterpreterPythonObject(object)); 2351254721Semaste} 2352254721Semaste 2353254721SemasteScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp, 2354254721Semaste ScriptedCommandSynchronicity synchro) : 2355254721Semaste m_debugger_sp(debugger_sp), 2356254721Semaste m_synch_wanted(synchro), 2357254721Semaste m_old_asynch(debugger_sp->GetAsyncExecution()) 2358254721Semaste{ 2359254721Semaste if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous) 2360254721Semaste m_debugger_sp->SetAsyncExecution(false); 2361254721Semaste else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous) 2362254721Semaste m_debugger_sp->SetAsyncExecution(true); 2363254721Semaste} 2364254721Semaste 2365254721SemasteScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler() 2366254721Semaste{ 2367254721Semaste if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue) 2368254721Semaste m_debugger_sp->SetAsyncExecution(m_old_asynch); 2369254721Semaste} 2370254721Semaste 2371254721Semastebool 2372254721SemasteScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function, 2373254721Semaste const char* args, 2374254721Semaste ScriptedCommandSynchronicity synchronicity, 2375254721Semaste lldb_private::CommandReturnObject& cmd_retobj, 2376254721Semaste Error& error) 2377254721Semaste{ 2378254721Semaste if (!impl_function) 2379254721Semaste { 2380254721Semaste error.SetErrorString("no function to execute"); 2381254721Semaste return false; 2382254721Semaste } 2383254721Semaste 2384254721Semaste if (!g_swig_call_command) 2385254721Semaste { 2386254721Semaste error.SetErrorString("no helper function to run scripted commands"); 2387254721Semaste return false; 2388254721Semaste } 2389254721Semaste 2390254721Semaste lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this(); 2391254721Semaste 2392254721Semaste if (!debugger_sp.get()) 2393254721Semaste { 2394254721Semaste error.SetErrorString("invalid Debugger pointer"); 2395254721Semaste return false; 2396254721Semaste } 2397254721Semaste 2398254721Semaste bool ret_val = false; 2399254721Semaste 2400254721Semaste std::string err_msg; 2401254721Semaste 2402254721Semaste { 2403254721Semaste Locker py_lock(this, 2404254721Semaste Locker::AcquireLock | Locker::InitSession, 2405254721Semaste Locker::FreeLock | Locker::TearDownSession); 2406254721Semaste 2407254721Semaste SynchronicityHandler synch_handler(debugger_sp, 2408254721Semaste synchronicity); 2409254721Semaste 2410254721Semaste // we need to save the thread state when we first start the command 2411254721Semaste // because we might decide to interrupt it while some action is taking 2412254721Semaste // place outside of Python (e.g. printing to screen, waiting for the network, ...) 2413254721Semaste // in that case, _PyThreadState_Current will be NULL - and we would be unable 2414254721Semaste // to set the asynchronous exception - not a desirable situation 2415254721Semaste m_command_thread_state = _PyThreadState_Current; 2416254721Semaste 2417269024Semaste //PythonInputReaderManager py_input(this); 2418254721Semaste 2419254721Semaste ret_val = g_swig_call_command (impl_function, 2420254721Semaste m_dictionary_name.c_str(), 2421254721Semaste debugger_sp, 2422254721Semaste args, 2423254721Semaste cmd_retobj); 2424254721Semaste } 2425254721Semaste 2426254721Semaste if (!ret_val) 2427254721Semaste error.SetErrorString("unable to execute script function"); 2428254721Semaste else 2429254721Semaste error.Clear(); 2430254721Semaste 2431254721Semaste return ret_val; 2432254721Semaste} 2433254721Semaste 2434254721Semaste// in Python, a special attribute __doc__ contains the docstring 2435254721Semaste// for an object (function, method, class, ...) if any is defined 2436254721Semaste// Otherwise, the attribute's value is None 2437254721Semastebool 2438254721SemasteScriptInterpreterPython::GetDocumentationForItem(const char* item, std::string& dest) 2439254721Semaste{ 2440254721Semaste dest.clear(); 2441254721Semaste if (!item || !*item) 2442254721Semaste return false; 2443254721Semaste std::string command(item); 2444254721Semaste command += ".__doc__"; 2445254721Semaste 2446254721Semaste char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully 2447254721Semaste 2448254721Semaste if (ExecuteOneLineWithReturn (command.c_str(), 2449254721Semaste ScriptInterpreter::eScriptReturnTypeCharStrOrNone, 2450254721Semaste &result_ptr, 2451254721Semaste ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false))) 2452254721Semaste { 2453254721Semaste if (result_ptr) 2454254721Semaste dest.assign(result_ptr); 2455254721Semaste return true; 2456254721Semaste } 2457254721Semaste else 2458254721Semaste { 2459254721Semaste StreamString str_stream; 2460254721Semaste str_stream.Printf("Function %s was not found. Containing module might be missing.",item); 2461254721Semaste dest.assign(str_stream.GetData()); 2462254721Semaste return false; 2463254721Semaste } 2464254721Semaste} 2465254721Semaste 2466254721Semastestd::unique_ptr<ScriptInterpreterLocker> 2467254721SemasteScriptInterpreterPython::AcquireInterpreterLock () 2468254721Semaste{ 2469254721Semaste std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(this, 2470269024Semaste Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN, 2471269024Semaste Locker::FreeLock | Locker::TearDownSession)); 2472254721Semaste return py_lock; 2473254721Semaste} 2474254721Semaste 2475254721Semastevoid 2476263363SemasteScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback swig_init_callback, 2477263363Semaste SWIGBreakpointCallbackFunction swig_breakpoint_callback, 2478263363Semaste SWIGWatchpointCallbackFunction swig_watchpoint_callback, 2479263363Semaste SWIGPythonTypeScriptCallbackFunction swig_typescript_callback, 2480263363Semaste SWIGPythonCreateSyntheticProvider swig_synthetic_script, 2481263363Semaste SWIGPythonCalculateNumChildren swig_calc_children, 2482263363Semaste SWIGPythonGetChildAtIndex swig_get_child_index, 2483263363Semaste SWIGPythonGetIndexOfChildWithName swig_get_index_child, 2484263363Semaste SWIGPythonCastPyObjectToSBValue swig_cast_to_sbvalue , 2485263363Semaste SWIGPythonGetValueObjectSPFromSBValue swig_get_valobj_sp_from_sbvalue, 2486263363Semaste SWIGPythonUpdateSynthProviderInstance swig_update_provider, 2487263363Semaste SWIGPythonMightHaveChildrenSynthProviderInstance swig_mighthavechildren_provider, 2488263363Semaste SWIGPythonCallCommand swig_call_command, 2489263363Semaste SWIGPythonCallModuleInit swig_call_module_init, 2490263363Semaste SWIGPythonCreateOSPlugin swig_create_os_plugin, 2491263363Semaste SWIGPythonScriptKeyword_Process swig_run_script_keyword_process, 2492263363Semaste SWIGPythonScriptKeyword_Thread swig_run_script_keyword_thread, 2493263363Semaste SWIGPythonScriptKeyword_Target swig_run_script_keyword_target, 2494263363Semaste SWIGPythonScriptKeyword_Frame swig_run_script_keyword_frame, 2495263363Semaste SWIGPython_GetDynamicSetting swig_plugin_get) 2496254721Semaste{ 2497263363Semaste g_swig_init_callback = swig_init_callback; 2498263363Semaste g_swig_breakpoint_callback = swig_breakpoint_callback; 2499263363Semaste g_swig_watchpoint_callback = swig_watchpoint_callback; 2500263363Semaste g_swig_typescript_callback = swig_typescript_callback; 2501263363Semaste g_swig_synthetic_script = swig_synthetic_script; 2502263363Semaste g_swig_calc_children = swig_calc_children; 2503263363Semaste g_swig_get_child_index = swig_get_child_index; 2504263363Semaste g_swig_get_index_child = swig_get_index_child; 2505263363Semaste g_swig_cast_to_sbvalue = swig_cast_to_sbvalue; 2506263363Semaste g_swig_get_valobj_sp_from_sbvalue = swig_get_valobj_sp_from_sbvalue; 2507263363Semaste g_swig_update_provider = swig_update_provider; 2508263363Semaste g_swig_mighthavechildren_provider = swig_mighthavechildren_provider; 2509263363Semaste g_swig_call_command = swig_call_command; 2510263363Semaste g_swig_call_module_init = swig_call_module_init; 2511263363Semaste g_swig_create_os_plugin = swig_create_os_plugin; 2512263363Semaste g_swig_run_script_keyword_process = swig_run_script_keyword_process; 2513263363Semaste g_swig_run_script_keyword_thread = swig_run_script_keyword_thread; 2514263363Semaste g_swig_run_script_keyword_target = swig_run_script_keyword_target; 2515263363Semaste g_swig_run_script_keyword_frame = swig_run_script_keyword_frame; 2516263363Semaste g_swig_plugin_get = swig_plugin_get; 2517254721Semaste} 2518254721Semaste 2519254721Semastevoid 2520254721SemasteScriptInterpreterPython::InitializePrivate () 2521254721Semaste{ 2522269024Semaste static int g_initialized = false; 2523269024Semaste 2524269024Semaste if (g_initialized) 2525269024Semaste return; 2526269024Semaste 2527269024Semaste g_initialized = true; 2528269024Semaste 2529254721Semaste Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); 2530254721Semaste 2531254721Semaste // Python will muck with STDIN terminal state, so save off any current TTY 2532254721Semaste // settings so we can restore them. 2533254721Semaste TerminalState stdin_tty_state; 2534254721Semaste stdin_tty_state.Save(STDIN_FILENO, false); 2535254721Semaste 2536254721Semaste PyGILState_STATE gstate; 2537254721Semaste Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE)); 2538254721Semaste bool threads_already_initialized = false; 2539254721Semaste if (PyEval_ThreadsInitialized ()) { 2540254721Semaste gstate = PyGILState_Ensure (); 2541254721Semaste if (log) 2542254721Semaste log->Printf("Ensured PyGILState. Previous state = %slocked\n", gstate == PyGILState_UNLOCKED ? "un" : ""); 2543254721Semaste threads_already_initialized = true; 2544254721Semaste } else { 2545254721Semaste // InitThreads acquires the GIL if it hasn't been called before. 2546254721Semaste PyEval_InitThreads (); 2547254721Semaste } 2548254721Semaste Py_InitializeEx (0); 2549254721Semaste 2550254721Semaste // Initialize SWIG after setting up python 2551269024Semaste if (g_swig_init_callback) 2552269024Semaste g_swig_init_callback (); 2553254721Semaste 2554254721Semaste // Update the path python uses to search for modules to include the current directory. 2555254721Semaste 2556254721Semaste PyRun_SimpleString ("import sys"); 2557254721Semaste PyRun_SimpleString ("sys.path.append ('.')"); 2558254721Semaste 2559254721Semaste // Find the module that owns this code and use that path we get to 2560254721Semaste // set the sys.path appropriately. 2561254721Semaste 2562254721Semaste FileSpec file_spec; 2563254721Semaste char python_dir_path[PATH_MAX]; 2564254721Semaste if (Host::GetLLDBPath (ePathTypePythonDir, file_spec)) 2565254721Semaste { 2566254721Semaste std::string python_path("sys.path.insert(0,\""); 2567254721Semaste size_t orig_len = python_path.length(); 2568254721Semaste if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path))) 2569254721Semaste { 2570254721Semaste python_path.append (python_dir_path); 2571254721Semaste python_path.append ("\")"); 2572254721Semaste PyRun_SimpleString (python_path.c_str()); 2573254721Semaste python_path.resize (orig_len); 2574254721Semaste } 2575254721Semaste 2576254721Semaste if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec)) 2577254721Semaste { 2578254721Semaste if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path))) 2579254721Semaste { 2580254721Semaste python_path.append (python_dir_path); 2581254721Semaste python_path.append ("\")"); 2582254721Semaste PyRun_SimpleString (python_path.c_str()); 2583254721Semaste python_path.resize (orig_len); 2584254721Semaste } 2585254721Semaste } 2586254721Semaste } 2587254721Semaste 2588254721Semaste PyRun_SimpleString ("sys.dont_write_bytecode = 1; import lldb.embedded_interpreter; from lldb.embedded_interpreter import run_python_interpreter; from lldb.embedded_interpreter import run_one_line; from termios import *"); 2589254721Semaste 2590254721Semaste if (threads_already_initialized) { 2591254721Semaste if (log) 2592254721Semaste log->Printf("Releasing PyGILState. Returning to state = %slocked\n", gstate == PyGILState_UNLOCKED ? "un" : ""); 2593254721Semaste PyGILState_Release (gstate); 2594254721Semaste } else { 2595254721Semaste // We initialized the threads in this function, just unlock the GIL. 2596254721Semaste PyEval_SaveThread(); 2597254721Semaste } 2598254721Semaste 2599254721Semaste stdin_tty_state.Restore(); 2600254721Semaste} 2601254721Semaste 2602254721Semaste//void 2603254721Semaste//ScriptInterpreterPython::Terminate () 2604254721Semaste//{ 2605254721Semaste// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling 2606254721Semaste// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers 2607254721Semaste// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls 2608254721Semaste// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate, 2609254721Semaste// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls 2610254721Semaste// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from 2611254721Semaste// // within Py_Finalize, which results in a seg fault. 2612254721Semaste// // 2613254721Semaste// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't 2614254721Semaste// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the 2615254721Semaste// // process exits). 2616254721Semaste// // 2617254721Semaste//// Py_Finalize (); 2618254721Semaste//} 2619254721Semaste 2620254721Semaste#endif // #ifdef LLDB_DISABLE_PYTHON 2621