1 //===-- ScriptInterpreterPython.cpp -----------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #ifdef LLDB_DISABLE_PYTHON 11 12 // Python is disabled in this build 13 14 #else 15 16 #include "lldb-python.h" 17 #include "ScriptInterpreterPython.h" 18 #include "PythonDataObjects.h" 19 20 #include <stdlib.h> 21 #include <stdio.h> 22 23 #include <mutex> 24 #include <string> 25 26 #include "lldb/API/SBValue.h" 27 #include "lldb/Breakpoint/BreakpointLocation.h" 28 #include "lldb/Breakpoint/StoppointCallbackContext.h" 29 #include "lldb/Breakpoint/WatchpointOptions.h" 30 #include "lldb/Core/Communication.h" 31 #include "lldb/Core/Debugger.h" 32 #include "lldb/Core/PluginManager.h" 33 #include "lldb/Core/Timer.h" 34 #include "lldb/Core/ValueObject.h" 35 #include "lldb/DataFormatters/TypeSummary.h" 36 #include "lldb/Host/ConnectionFileDescriptor.h" 37 #include "lldb/Host/HostInfo.h" 38 #include "lldb/Host/Pipe.h" 39 #include "lldb/Interpreter/CommandInterpreter.h" 40 #include "lldb/Interpreter/CommandReturnObject.h" 41 #include "lldb/Target/Thread.h" 42 #include "lldb/Target/ThreadPlan.h" 43 44 #if defined(_WIN32) 45 #include "lldb/Host/windows/ConnectionGenericFileWindows.h" 46 #endif 47 48 #include "llvm/ADT/StringRef.h" 49 #include "llvm/ADT/STLExtras.h" 50 51 using namespace lldb; 52 using namespace lldb_private; 53 54 static ScriptInterpreterPython::SWIGInitCallback g_swig_init_callback = nullptr; 55 static ScriptInterpreterPython::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = nullptr; 56 static ScriptInterpreterPython::SWIGWatchpointCallbackFunction g_swig_watchpoint_callback = nullptr; 57 static ScriptInterpreterPython::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = nullptr; 58 static ScriptInterpreterPython::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = nullptr; 59 static ScriptInterpreterPython::SWIGPythonCreateCommandObject g_swig_create_cmd = nullptr; 60 static ScriptInterpreterPython::SWIGPythonCalculateNumChildren g_swig_calc_children = nullptr; 61 static ScriptInterpreterPython::SWIGPythonGetChildAtIndex g_swig_get_child_index = nullptr; 62 static ScriptInterpreterPython::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = nullptr; 63 static ScriptInterpreterPython::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = nullptr; 64 static ScriptInterpreterPython::SWIGPythonGetValueObjectSPFromSBValue g_swig_get_valobj_sp_from_sbvalue = nullptr; 65 static ScriptInterpreterPython::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = nullptr; 66 static ScriptInterpreterPython::SWIGPythonMightHaveChildrenSynthProviderInstance g_swig_mighthavechildren_provider = nullptr; 67 static ScriptInterpreterPython::SWIGPythonGetValueSynthProviderInstance g_swig_getvalue_provider = nullptr; 68 static ScriptInterpreterPython::SWIGPythonCallCommand g_swig_call_command = nullptr; 69 static ScriptInterpreterPython::SWIGPythonCallCommandObject g_swig_call_command_object = nullptr; 70 static ScriptInterpreterPython::SWIGPythonCallModuleInit g_swig_call_module_init = nullptr; 71 static ScriptInterpreterPython::SWIGPythonCreateOSPlugin g_swig_create_os_plugin = nullptr; 72 static ScriptInterpreterPython::SWIGPythonScriptKeyword_Process g_swig_run_script_keyword_process = nullptr; 73 static ScriptInterpreterPython::SWIGPythonScriptKeyword_Thread g_swig_run_script_keyword_thread = nullptr; 74 static ScriptInterpreterPython::SWIGPythonScriptKeyword_Target g_swig_run_script_keyword_target = nullptr; 75 static ScriptInterpreterPython::SWIGPythonScriptKeyword_Frame g_swig_run_script_keyword_frame = nullptr; 76 static ScriptInterpreterPython::SWIGPythonScriptKeyword_Value g_swig_run_script_keyword_value = nullptr; 77 static ScriptInterpreterPython::SWIGPython_GetDynamicSetting g_swig_plugin_get = nullptr; 78 static ScriptInterpreterPython::SWIGPythonCreateScriptedThreadPlan g_swig_thread_plan_script = nullptr; 79 static ScriptInterpreterPython::SWIGPythonCallThreadPlan g_swig_call_thread_plan = nullptr; 80 81 static bool g_initialized = false; 82 83 namespace 84 { 85 86 // Initializing Python is not a straightforward process. We cannot control what 87 // external code may have done before getting to this point in LLDB, including 88 // potentially having already initialized Python, so we need to do a lot of work 89 // to ensure that the existing state of the system is maintained across our 90 // initialization. We do this by using an RAII pattern where we save off initial 91 // state at the beginning, and restore it at the end 92 struct InitializePythonRAII 93 { 94 public: 95 InitializePythonRAII() : 96 m_was_already_initialized(false), 97 m_gil_state(PyGILState_UNLOCKED) 98 { 99 // Python will muck with STDIN terminal state, so save off any current TTY 100 // settings so we can restore them. 101 m_stdin_tty_state.Save(STDIN_FILENO, false); 102 103 InitializePythonHome(); 104 105 // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for 106 // calling `Py_Initialize` and `PyEval_InitThreads`. < 3.2 requires that you 107 // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last. 108 #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3) 109 Py_InitializeEx(0); 110 InitializeThreadsPrivate(); 111 #else 112 InitializeThreadsPrivate(); 113 Py_InitializeEx(0); 114 #endif 115 } 116 117 ~InitializePythonRAII() 118 { 119 if (m_was_already_initialized) 120 { 121 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE)); 122 123 if (log) 124 { 125 log->Printf("Releasing PyGILState. Returning to state = %slocked\n", 126 m_was_already_initialized == PyGILState_UNLOCKED ? "un" : ""); 127 } 128 PyGILState_Release(m_gil_state); 129 } 130 else 131 { 132 // We initialized the threads in this function, just unlock the GIL. 133 PyEval_SaveThread(); 134 } 135 136 m_stdin_tty_state.Restore(); 137 } 138 139 private: 140 void InitializePythonHome() 141 { 142 #if defined(LLDB_PYTHON_HOME) 143 #if PY_MAJOR_VERSION >= 3 144 size_t size = 0; 145 static wchar_t *g_python_home = Py_DecodeLocale(LLDB_PYTHON_HOME, &size); 146 #else 147 static char *g_python_home = LLDB_PYTHON_HOME; 148 #endif 149 Py_SetPythonHome(g_python_home); 150 #endif 151 } 152 153 void InitializeThreadsPrivate() 154 { 155 if (PyEval_ThreadsInitialized()) 156 { 157 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE)); 158 159 m_was_already_initialized = true; 160 m_gil_state = PyGILState_Ensure(); 161 if (log) 162 { 163 log->Printf("Ensured PyGILState. Previous state = %slocked\n", 164 m_gil_state == PyGILState_UNLOCKED ? "un" : ""); 165 } 166 return; 167 } 168 169 // InitThreads acquires the GIL if it hasn't been called before. 170 PyEval_InitThreads(); 171 } 172 173 TerminalState m_stdin_tty_state; 174 PyGILState_STATE m_gil_state; 175 bool m_was_already_initialized; 176 }; 177 178 } 179 180 static std::string ReadPythonBacktrace(PythonObject py_backtrace); 181 182 ScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *py_interpreter, 183 uint16_t on_entry, 184 uint16_t on_leave, 185 FILE *in, 186 FILE *out, 187 FILE *err) : 188 ScriptInterpreterLocker (), 189 m_teardown_session( (on_leave & TearDownSession) == TearDownSession ), 190 m_python_interpreter(py_interpreter) 191 { 192 DoAcquireLock(); 193 if ((on_entry & InitSession) == InitSession) 194 { 195 if (DoInitSession(on_entry, in, out, err) == false) 196 { 197 // Don't teardown the session if we didn't init it. 198 m_teardown_session = false; 199 } 200 } 201 } 202 203 bool 204 ScriptInterpreterPython::Locker::DoAcquireLock() 205 { 206 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE)); 207 m_GILState = PyGILState_Ensure(); 208 if (log) 209 log->Printf("Ensured PyGILState. Previous state = %slocked\n", m_GILState == PyGILState_UNLOCKED ? "un" : ""); 210 211 // we need to save the thread state when we first start the command 212 // because we might decide to interrupt it while some action is taking 213 // place outside of Python (e.g. printing to screen, waiting for the network, ...) 214 // in that case, _PyThreadState_Current will be NULL - and we would be unable 215 // to set the asynchronous exception - not a desirable situation 216 m_python_interpreter->SetThreadState(PyThreadState_Get()); 217 m_python_interpreter->IncrementLockCount(); 218 return true; 219 } 220 221 bool 222 ScriptInterpreterPython::Locker::DoInitSession(uint16_t on_entry_flags, FILE *in, FILE *out, FILE *err) 223 { 224 if (!m_python_interpreter) 225 return false; 226 return m_python_interpreter->EnterSession (on_entry_flags, in, out, err); 227 } 228 229 bool 230 ScriptInterpreterPython::Locker::DoFreeLock() 231 { 232 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE)); 233 if (log) 234 log->Printf("Releasing PyGILState. Returning to state = %slocked\n", m_GILState == PyGILState_UNLOCKED ? "un" : ""); 235 PyGILState_Release(m_GILState); 236 m_python_interpreter->DecrementLockCount(); 237 return true; 238 } 239 240 bool 241 ScriptInterpreterPython::Locker::DoTearDownSession() 242 { 243 if (!m_python_interpreter) 244 return false; 245 m_python_interpreter->LeaveSession (); 246 return true; 247 } 248 249 ScriptInterpreterPython::Locker::~Locker() 250 { 251 if (m_teardown_session) 252 DoTearDownSession(); 253 DoFreeLock(); 254 } 255 256 ScriptInterpreterPython::ScriptInterpreterPython(CommandInterpreter &interpreter) : 257 ScriptInterpreter(interpreter, eScriptLanguagePython), 258 IOHandlerDelegateMultiline("DONE"), 259 m_saved_stdin(), 260 m_saved_stdout(), 261 m_saved_stderr(), 262 m_main_module(), 263 m_lldb_module(), 264 m_session_dict(PyInitialValue::Invalid), 265 m_sys_module_dict(PyInitialValue::Invalid), 266 m_run_one_line_function(), 267 m_run_one_line_str_global(), 268 m_dictionary_name(interpreter.GetDebugger().GetInstanceName().AsCString()), 269 m_terminal_state(), 270 m_active_io_handler(eIOHandlerNone), 271 m_session_is_active(false), 272 m_pty_slave_is_open(false), 273 m_valid_session(true), 274 m_lock_count(0), 275 m_command_thread_state(nullptr) 276 { 277 assert(g_initialized && "ScriptInterpreterPython created but InitializePrivate has not been called!"); 278 279 m_dictionary_name.append("_dict"); 280 StreamString run_string; 281 run_string.Printf ("%s = dict()", m_dictionary_name.c_str()); 282 283 Locker locker(this, 284 ScriptInterpreterPython::Locker::AcquireLock, 285 ScriptInterpreterPython::Locker::FreeAcquiredLock); 286 PyRun_SimpleString (run_string.GetData()); 287 288 run_string.Clear(); 289 290 run_string.Printf ("run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')", m_dictionary_name.c_str()); 291 PyRun_SimpleString (run_string.GetData()); 292 293 // WARNING: temporary code that loads Cocoa formatters - this should be done on a per-platform basis rather than loading the whole set 294 // and letting the individual formatter classes exploit APIs to check whether they can/cannot do their task 295 run_string.Clear(); 296 run_string.Printf ("run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')", m_dictionary_name.c_str()); 297 PyRun_SimpleString (run_string.GetData()); 298 run_string.Clear(); 299 300 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()); 301 PyRun_SimpleString (run_string.GetData()); 302 run_string.Clear(); 303 304 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64 "; pydoc.pager = pydoc.plainpager')", m_dictionary_name.c_str(), 305 interpreter.GetDebugger().GetID()); 306 PyRun_SimpleString (run_string.GetData()); 307 } 308 309 ScriptInterpreterPython::~ScriptInterpreterPython () 310 { 311 // the session dictionary may hold objects with complex state 312 // which means that they may need to be torn down with some level of smarts 313 // and that, in turn, requires a valid thread state 314 // force Python to procure itself such a thread state, nuke the session dictionary 315 // and then release it for others to use and proceed with the rest of the shutdown 316 auto gil_state = PyGILState_Ensure(); 317 m_session_dict.Reset(); 318 PyGILState_Release(gil_state); 319 } 320 321 void 322 ScriptInterpreterPython::Initialize() 323 { 324 static std::once_flag g_once_flag; 325 326 std::call_once(g_once_flag, []() 327 { 328 InitializePrivate(); 329 330 PluginManager::RegisterPlugin(GetPluginNameStatic(), 331 GetPluginDescriptionStatic(), 332 lldb::eScriptLanguagePython, 333 CreateInstance); 334 }); 335 } 336 337 void 338 ScriptInterpreterPython::Terminate() 339 { 340 341 } 342 343 lldb::ScriptInterpreterSP 344 ScriptInterpreterPython::CreateInstance(CommandInterpreter &interpreter) 345 { 346 return std::make_shared<ScriptInterpreterPython>(interpreter); 347 } 348 349 lldb_private::ConstString 350 ScriptInterpreterPython::GetPluginNameStatic() 351 { 352 static ConstString g_name("script-python"); 353 return g_name; 354 } 355 356 const char * 357 ScriptInterpreterPython::GetPluginDescriptionStatic() 358 { 359 return "Embedded Python interpreter"; 360 } 361 362 lldb_private::ConstString 363 ScriptInterpreterPython::GetPluginName() 364 { 365 return GetPluginNameStatic(); 366 } 367 368 uint32_t 369 ScriptInterpreterPython::GetPluginVersion() 370 { 371 return 1; 372 } 373 374 void 375 ScriptInterpreterPython::IOHandlerActivated (IOHandler &io_handler) 376 { 377 const char *instructions = nullptr; 378 379 switch (m_active_io_handler) 380 { 381 case eIOHandlerNone: 382 break; 383 case eIOHandlerBreakpoint: 384 instructions = R"(Enter your Python command(s). Type 'DONE' to end. 385 def function (frame, bp_loc, internal_dict): 386 """frame: the lldb.SBFrame for the location at which you stopped 387 bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information 388 internal_dict: an LLDB support object not to be used""" 389 )"; 390 break; 391 case eIOHandlerWatchpoint: 392 instructions = "Enter your Python command(s). Type 'DONE' to end.\n"; 393 break; 394 } 395 396 if (instructions) 397 { 398 StreamFileSP output_sp(io_handler.GetOutputStreamFile()); 399 if (output_sp) 400 { 401 output_sp->PutCString(instructions); 402 output_sp->Flush(); 403 } 404 } 405 } 406 407 void 408 ScriptInterpreterPython::IOHandlerInputComplete (IOHandler &io_handler, std::string &data) 409 { 410 io_handler.SetIsDone(true); 411 bool batch_mode = m_interpreter.GetBatchCommandMode(); 412 413 switch (m_active_io_handler) 414 { 415 case eIOHandlerNone: 416 break; 417 case eIOHandlerBreakpoint: 418 { 419 std::vector<BreakpointOptions *> *bp_options_vec = (std::vector<BreakpointOptions *> *)io_handler.GetUserData(); 420 for (auto bp_options : *bp_options_vec) 421 { 422 if (!bp_options) 423 continue; 424 425 std::unique_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData()); 426 if (data_ap.get()) 427 { 428 data_ap->user_source.SplitIntoLines(data); 429 430 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source).Success()) 431 { 432 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release())); 433 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp); 434 } 435 else if (!batch_mode) 436 { 437 StreamFileSP error_sp = io_handler.GetErrorStreamFile(); 438 if (error_sp) 439 { 440 error_sp->Printf ("Warning: No command attached to breakpoint.\n"); 441 error_sp->Flush(); 442 } 443 } 444 } 445 } 446 m_active_io_handler = eIOHandlerNone; 447 } 448 break; 449 case eIOHandlerWatchpoint: 450 { 451 WatchpointOptions *wp_options = (WatchpointOptions *)io_handler.GetUserData(); 452 std::unique_ptr<WatchpointOptions::CommandData> data_ap(new WatchpointOptions::CommandData()); 453 if (data_ap.get()) 454 { 455 data_ap->user_source.SplitIntoLines(data); 456 457 if (GenerateWatchpointCommandCallbackData (data_ap->user_source, data_ap->script_source)) 458 { 459 BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release())); 460 wp_options->SetCallback (ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp); 461 } 462 else if (!batch_mode) 463 { 464 StreamFileSP error_sp = io_handler.GetErrorStreamFile(); 465 if (error_sp) 466 { 467 error_sp->Printf ("Warning: No command attached to breakpoint.\n"); 468 error_sp->Flush(); 469 } 470 } 471 } 472 m_active_io_handler = eIOHandlerNone; 473 } 474 break; 475 } 476 } 477 478 479 void 480 ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh) 481 { 482 } 483 484 void 485 ScriptInterpreterPython::SaveTerminalState (int fd) 486 { 487 // Python mucks with the terminal state of STDIN. If we can possibly avoid 488 // this by setting the file handles up correctly prior to entering the 489 // interpreter we should. For now we save and restore the terminal state 490 // on the input file handle. 491 m_terminal_state.Save (fd, false); 492 } 493 494 void 495 ScriptInterpreterPython::RestoreTerminalState () 496 { 497 // Python mucks with the terminal state of STDIN. If we can possibly avoid 498 // this by setting the file handles up correctly prior to entering the 499 // interpreter we should. For now we save and restore the terminal state 500 // on the input file handle. 501 m_terminal_state.Restore(); 502 } 503 504 void 505 ScriptInterpreterPython::LeaveSession () 506 { 507 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT)); 508 if (log) 509 log->PutCString("ScriptInterpreterPython::LeaveSession()"); 510 511 // checking that we have a valid thread state - since we use our own threading and locking 512 // in some (rare) cases during cleanup Python may end up believing we have no thread state 513 // and PyImport_AddModule will crash if that is the case - since that seems to only happen 514 // when destroying the SBDebugger, we can make do without clearing up stdout and stderr 515 516 // rdar://problem/11292882 517 // When the current thread state is NULL, PyThreadState_Get() issues a fatal error. 518 if (PyThreadState_GetDict()) 519 { 520 PythonDictionary &sys_module_dict = GetSysModuleDictionary (); 521 if (sys_module_dict.IsValid()) 522 { 523 if (m_saved_stdin.IsValid()) 524 { 525 sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin); 526 m_saved_stdin.Reset (); 527 } 528 if (m_saved_stdout.IsValid()) 529 { 530 sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout); 531 m_saved_stdout.Reset (); 532 } 533 if (m_saved_stderr.IsValid()) 534 { 535 sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr); 536 m_saved_stderr.Reset (); 537 } 538 } 539 } 540 541 m_session_is_active = false; 542 } 543 544 static PythonObject 545 PyFile_FromFile_Const(FILE *fp, const char *mode) 546 { 547 char *cmode = const_cast<char*>(mode); 548 #if PY_MAJOR_VERSION >= 3 549 #if defined(LLVM_ON_WIN32) 550 int fd = _fileno(fp); 551 #else 552 int fd = fileno(fp); 553 #endif 554 555 return PythonObject(PyRefType::Owned, 556 PyFile_FromFd(fd, nullptr, cmode, -1, nullptr, "ignore", nullptr, 0)); 557 #else 558 // Read through the Python source, doesn't seem to modify these strings 559 return PythonObject(PyRefType::Owned, 560 PyFile_FromFile(fp, const_cast<char*>(""), cmode, nullptr)); 561 #endif 562 } 563 564 bool 565 ScriptInterpreterPython::EnterSession (uint16_t on_entry_flags, 566 FILE *in, 567 FILE *out, 568 FILE *err) 569 { 570 // If we have already entered the session, without having officially 'left' it, then there is no need to 571 // 'enter' it again. 572 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT)); 573 if (m_session_is_active) 574 { 575 if (log) 576 log->Printf("ScriptInterpreterPython::EnterSession(on_entry_flags=0x%" PRIx16 ") session is already active, returning without doing anything", on_entry_flags); 577 return false; 578 } 579 580 if (log) 581 log->Printf("ScriptInterpreterPython::EnterSession(on_entry_flags=0x%" PRIx16 ")", on_entry_flags); 582 583 584 m_session_is_active = true; 585 586 StreamString run_string; 587 588 if (on_entry_flags & Locker::InitGlobals) 589 { 590 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID()); 591 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", GetCommandInterpreter().GetDebugger().GetID()); 592 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()"); 593 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()"); 594 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()"); 595 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()"); 596 run_string.PutCString ("')"); 597 } 598 else 599 { 600 // If we aren't initing the globals, we should still always set the debugger (since that is always unique.) 601 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID()); 602 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", GetCommandInterpreter().GetDebugger().GetID()); 603 run_string.PutCString ("')"); 604 } 605 606 PyRun_SimpleString (run_string.GetData()); 607 run_string.Clear(); 608 609 PythonDictionary &sys_module_dict = GetSysModuleDictionary (); 610 if (sys_module_dict.IsValid()) 611 { 612 lldb::StreamFileSP in_sp; 613 lldb::StreamFileSP out_sp; 614 lldb::StreamFileSP err_sp; 615 if (in == nullptr || out == nullptr || err == nullptr) 616 m_interpreter.GetDebugger().AdoptTopIOHandlerFilesIfInvalid (in_sp, out_sp, err_sp); 617 618 m_saved_stdin.Reset(); 619 620 if ((on_entry_flags & Locker::NoSTDIN) == 0) 621 { 622 // STDIN is enabled 623 if (in == nullptr && in_sp) 624 in = in_sp->GetFile().GetStream(); 625 if (in) 626 { 627 m_saved_stdin = sys_module_dict.GetItemForKey(PythonString("stdin")); 628 // This call can deadlock your process if the file is locked 629 PythonObject new_file = PyFile_FromFile_Const(in, "r"); 630 sys_module_dict.SetItemForKey (PythonString("stdin"), new_file); 631 } 632 } 633 634 if (out == nullptr && out_sp) 635 out = out_sp->GetFile().GetStream(); 636 if (out) 637 { 638 m_saved_stdout = sys_module_dict.GetItemForKey(PythonString("stdout")); 639 640 PythonObject new_file = PyFile_FromFile_Const(out, "w"); 641 sys_module_dict.SetItemForKey (PythonString("stdout"), new_file); 642 } 643 else 644 m_saved_stdout.Reset(); 645 646 if (err == nullptr && err_sp) 647 err = err_sp->GetFile().GetStream(); 648 if (err) 649 { 650 m_saved_stderr = sys_module_dict.GetItemForKey(PythonString("stderr")); 651 652 PythonObject new_file = PyFile_FromFile_Const(err, "w"); 653 sys_module_dict.SetItemForKey (PythonString("stderr"), new_file); 654 } 655 else 656 m_saved_stderr.Reset(); 657 } 658 659 if (PyErr_Occurred()) 660 PyErr_Clear (); 661 662 return true; 663 } 664 665 PythonObject & 666 ScriptInterpreterPython::GetMainModule() 667 { 668 if (!m_main_module.IsValid()) 669 m_main_module.Reset(PyRefType::Borrowed, PyImport_AddModule("__main__")); 670 return m_main_module; 671 } 672 673 PythonDictionary & 674 ScriptInterpreterPython::GetSessionDictionary () 675 { 676 if (m_session_dict.IsValid()) 677 return m_session_dict; 678 679 PythonObject &main_module = GetMainModule(); 680 if (!main_module.IsValid()) 681 return m_session_dict; 682 683 PythonDictionary main_dict(PyRefType::Borrowed, PyModule_GetDict(main_module.get())); 684 if (!main_dict.IsValid()) 685 return m_session_dict; 686 687 PythonObject item = main_dict.GetItemForKey(PythonString(m_dictionary_name)); 688 m_session_dict.Reset(PyRefType::Borrowed, item.get()); 689 return m_session_dict; 690 } 691 692 PythonDictionary & 693 ScriptInterpreterPython::GetSysModuleDictionary () 694 { 695 if (m_sys_module_dict.IsValid()) 696 return m_sys_module_dict; 697 698 PythonObject sys_module(PyRefType::Borrowed, PyImport_AddModule("sys")); 699 if (sys_module.IsValid()) 700 m_sys_module_dict.Reset(PyRefType::Borrowed, PyModule_GetDict(sys_module.get())); 701 return m_sys_module_dict; 702 } 703 704 static std::string 705 GenerateUniqueName (const char* base_name_wanted, 706 uint32_t& functions_counter, 707 const void* name_token = nullptr) 708 { 709 StreamString sstr; 710 711 if (!base_name_wanted) 712 return std::string(); 713 714 if (!name_token) 715 sstr.Printf ("%s_%d", base_name_wanted, functions_counter++); 716 else 717 sstr.Printf ("%s_%p", base_name_wanted, name_token); 718 719 return sstr.GetString(); 720 } 721 722 bool 723 ScriptInterpreterPython::GetEmbeddedInterpreterModuleObjects () 724 { 725 if (m_run_one_line_function.IsValid()) 726 return true; 727 728 PythonObject module(PyRefType::Borrowed, PyImport_AddModule ("lldb.embedded_interpreter")); 729 if (!module.IsValid()) 730 return false; 731 732 PythonDictionary module_dict(PyRefType::Borrowed, PyModule_GetDict(module.get())); 733 if (!module_dict.IsValid()) 734 return false; 735 736 m_run_one_line_function = module_dict.GetItemForKey(PythonString("run_one_line")); 737 m_run_one_line_str_global = module_dict.GetItemForKey(PythonString("g_run_one_line_str")); 738 return m_run_one_line_function.IsValid(); 739 } 740 741 static void 742 ReadThreadBytesReceived(void *baton, const void *src, size_t src_len) 743 { 744 if (src && src_len) 745 { 746 Stream *strm = (Stream *)baton; 747 strm->Write(src, src_len); 748 strm->Flush(); 749 } 750 } 751 752 bool 753 ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result, const ExecuteScriptOptions &options) 754 { 755 if (!m_valid_session) 756 return false; 757 758 if (command && command[0]) 759 { 760 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through 761 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside 762 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated 763 // method to pass the command string directly down to Python. 764 Debugger &debugger = m_interpreter.GetDebugger(); 765 766 StreamFileSP input_file_sp; 767 StreamFileSP output_file_sp; 768 StreamFileSP error_file_sp; 769 Communication output_comm ("lldb.ScriptInterpreterPython.ExecuteOneLine.comm"); 770 bool join_read_thread = false; 771 if (options.GetEnableIO()) 772 { 773 if (result) 774 { 775 input_file_sp = debugger.GetInputFile(); 776 // Set output to a temporary file so we can forward the results on to the result object 777 778 Pipe pipe; 779 Error pipe_result = pipe.CreateNew(false); 780 if (pipe_result.Success()) 781 { 782 #if defined(_WIN32) 783 lldb::file_t read_file = pipe.GetReadNativeHandle(); 784 pipe.ReleaseReadFileDescriptor(); 785 std::unique_ptr<ConnectionGenericFile> conn_ap(new ConnectionGenericFile(read_file, true)); 786 #else 787 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor(pipe.ReleaseReadFileDescriptor(), true)); 788 #endif 789 if (conn_ap->IsConnected()) 790 { 791 output_comm.SetConnection(conn_ap.release()); 792 output_comm.SetReadThreadBytesReceivedCallback(ReadThreadBytesReceived, &result->GetOutputStream()); 793 output_comm.StartReadThread(); 794 join_read_thread = true; 795 FILE *outfile_handle = fdopen (pipe.ReleaseWriteFileDescriptor(), "w"); 796 output_file_sp.reset(new StreamFile(outfile_handle, true)); 797 error_file_sp = output_file_sp; 798 if (outfile_handle) 799 ::setbuf (outfile_handle, nullptr); 800 801 result->SetImmediateOutputFile(debugger.GetOutputFile()->GetFile().GetStream()); 802 result->SetImmediateErrorFile(debugger.GetErrorFile()->GetFile().GetStream()); 803 } 804 } 805 } 806 if (!input_file_sp || !output_file_sp || !error_file_sp) 807 debugger.AdoptTopIOHandlerFilesIfInvalid(input_file_sp, output_file_sp, error_file_sp); 808 } 809 else 810 { 811 input_file_sp.reset (new StreamFile ()); 812 input_file_sp->GetFile().Open("/dev/null", File::eOpenOptionRead); 813 output_file_sp.reset (new StreamFile ()); 814 output_file_sp->GetFile().Open("/dev/null", File::eOpenOptionWrite); 815 error_file_sp = output_file_sp; 816 } 817 818 FILE *in_file = input_file_sp->GetFile().GetStream(); 819 FILE *out_file = output_file_sp->GetFile().GetStream(); 820 FILE *err_file = error_file_sp->GetFile().GetStream(); 821 Locker locker(this, 822 ScriptInterpreterPython::Locker::AcquireLock | 823 ScriptInterpreterPython::Locker::InitSession | 824 (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::InitGlobals : 0) | 825 ((result && result->GetInteractive()) ? 0: Locker::NoSTDIN), 826 ScriptInterpreterPython::Locker::FreeAcquiredLock | 827 ScriptInterpreterPython::Locker::TearDownSession, 828 in_file, 829 out_file, 830 err_file); 831 832 bool success = false; 833 834 // Find the correct script interpreter dictionary in the main module. 835 PythonDictionary &session_dict = GetSessionDictionary (); 836 if (session_dict.IsValid()) 837 { 838 if (GetEmbeddedInterpreterModuleObjects ()) 839 { 840 if (PyCallable_Check(m_run_one_line_function.get())) 841 { 842 PythonObject pargs(PyRefType::Owned, Py_BuildValue("(Os)", session_dict.get(), command)); 843 if (pargs.IsValid()) 844 { 845 PythonObject return_value(PyRefType::Owned, 846 PyObject_CallObject(m_run_one_line_function.get(), pargs.get())); 847 if (return_value.IsValid()) 848 success = true; 849 else if (options.GetMaskoutErrors() && PyErr_Occurred ()) 850 { 851 PyErr_Print(); 852 PyErr_Clear(); 853 } 854 } 855 } 856 } 857 } 858 859 // Flush our output and error file handles 860 ::fflush (out_file); 861 if (out_file != err_file) 862 ::fflush (err_file); 863 864 if (join_read_thread) 865 { 866 // Close the write end of the pipe since we are done with our 867 // one line script. This should cause the read thread that 868 // output_comm is using to exit 869 output_file_sp->GetFile().Close(); 870 // The close above should cause this thread to exit when it gets 871 // to the end of file, so let it get all its data 872 output_comm.JoinReadThread(); 873 // Now we can close the read end of the pipe 874 output_comm.Disconnect(); 875 } 876 877 878 if (success) 879 return true; 880 881 // The one-liner failed. Append the error message. 882 if (result) 883 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command); 884 return false; 885 } 886 887 if (result) 888 result->AppendError ("empty command passed to python\n"); 889 return false; 890 } 891 892 893 class IOHandlerPythonInterpreter : 894 public IOHandler 895 { 896 public: 897 898 IOHandlerPythonInterpreter (Debugger &debugger, 899 ScriptInterpreterPython *python) : 900 IOHandler (debugger, IOHandler::Type::PythonInterpreter), 901 m_python(python) 902 { 903 904 } 905 906 ~IOHandlerPythonInterpreter() override 907 { 908 909 } 910 911 ConstString 912 GetControlSequence (char ch) override 913 { 914 if (ch == 'd') 915 return ConstString("quit()\n"); 916 return ConstString(); 917 } 918 919 void 920 Run () override 921 { 922 if (m_python) 923 { 924 int stdin_fd = GetInputFD(); 925 if (stdin_fd >= 0) 926 { 927 Terminal terminal(stdin_fd); 928 TerminalState terminal_state; 929 const bool is_a_tty = terminal.IsATerminal(); 930 931 if (is_a_tty) 932 { 933 terminal_state.Save (stdin_fd, false); 934 terminal.SetCanonical(false); 935 terminal.SetEcho(true); 936 } 937 938 ScriptInterpreterPython::Locker locker (m_python, 939 ScriptInterpreterPython::Locker::AcquireLock | 940 ScriptInterpreterPython::Locker::InitSession | 941 ScriptInterpreterPython::Locker::InitGlobals, 942 ScriptInterpreterPython::Locker::FreeAcquiredLock | 943 ScriptInterpreterPython::Locker::TearDownSession); 944 945 // The following call drops into the embedded interpreter loop and stays there until the 946 // user chooses to exit from the Python interpreter. 947 // This embedded interpreter will, as any Python code that performs I/O, unlock the GIL before 948 // a system call that can hang, and lock it when the syscall has returned. 949 950 // We need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and 951 // PyGILState_Release (using the Locker above). This is because Python has a global lock which must be held whenever we want 952 // to touch any Python objects. Otherwise, if the user calls Python code, the interpreter state will be off, 953 // and things could hang (it's happened before). 954 955 StreamString run_string; 956 run_string.Printf ("run_python_interpreter (%s)", m_python->GetDictionaryName ()); 957 PyRun_SimpleString (run_string.GetData()); 958 959 if (is_a_tty) 960 terminal_state.Restore(); 961 } 962 } 963 SetIsDone(true); 964 } 965 966 void 967 Cancel () override 968 { 969 970 } 971 972 bool 973 Interrupt () override 974 { 975 return m_python->Interrupt(); 976 } 977 978 void 979 GotEOF() override 980 { 981 982 } 983 protected: 984 ScriptInterpreterPython *m_python; 985 }; 986 987 988 void 989 ScriptInterpreterPython::ExecuteInterpreterLoop () 990 { 991 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); 992 993 Debugger &debugger = GetCommandInterpreter().GetDebugger(); 994 995 // At the moment, the only time the debugger does not have an input file handle is when this is called 996 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to 997 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't 998 // do it. 999 1000 if (!debugger.GetInputFile()->GetFile().IsValid()) 1001 return; 1002 1003 IOHandlerSP io_handler_sp (new IOHandlerPythonInterpreter (debugger, this)); 1004 if (io_handler_sp) 1005 { 1006 debugger.PushIOHandler(io_handler_sp); 1007 } 1008 } 1009 1010 bool 1011 ScriptInterpreterPython::Interrupt() 1012 { 1013 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT)); 1014 1015 if (IsExecutingPython()) 1016 { 1017 PyThreadState *state = PyThreadState_Get(); 1018 if (!state) 1019 state = GetThreadState(); 1020 if (state) 1021 { 1022 long tid = state->thread_id; 1023 PyThreadState_Swap(state); 1024 int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt); 1025 if (log) 1026 log->Printf("ScriptInterpreterPython::Interrupt() sending PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...", tid, num_threads); 1027 return true; 1028 } 1029 } 1030 if (log) 1031 log->Printf("ScriptInterpreterPython::Interrupt() python code not running, can't interrupt"); 1032 return false; 1033 1034 } 1035 bool 1036 ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string, 1037 ScriptInterpreter::ScriptReturnType return_type, 1038 void *ret_value, 1039 const ExecuteScriptOptions &options) 1040 { 1041 1042 Locker locker(this, 1043 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::InitGlobals : 0) | Locker::NoSTDIN, 1044 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession); 1045 1046 PythonObject py_return; 1047 PythonObject &main_module = GetMainModule(); 1048 PythonDictionary globals(PyRefType::Borrowed, PyModule_GetDict(main_module.get())); 1049 PythonObject py_error; 1050 bool ret_success = false; 1051 int success; 1052 1053 PythonDictionary locals = GetSessionDictionary (); 1054 1055 if (!locals.IsValid()) 1056 { 1057 locals.Reset(PyRefType::Owned, PyObject_GetAttrString(globals.get(), m_dictionary_name.c_str())); 1058 } 1059 1060 if (!locals.IsValid()) 1061 locals = globals; 1062 1063 py_error.Reset(PyRefType::Borrowed, PyErr_Occurred()); 1064 if (py_error.IsValid()) 1065 PyErr_Clear(); 1066 1067 if (in_string != nullptr) 1068 { 1069 { // scope for PythonInputReaderManager 1070 //PythonInputReaderManager py_input(options.GetEnableIO() ? this : NULL); 1071 py_return.Reset(PyRefType::Owned, PyRun_String(in_string, Py_eval_input, globals.get(), locals.get())); 1072 if (!py_return.IsValid()) 1073 { 1074 py_error.Reset(PyRefType::Borrowed, PyErr_Occurred()); 1075 if (py_error.IsValid()) 1076 PyErr_Clear(); 1077 1078 py_return.Reset(PyRefType::Owned, PyRun_String(in_string, Py_single_input, globals.get(), locals.get())); 1079 } 1080 } 1081 1082 if (py_return.IsValid()) 1083 { 1084 switch (return_type) 1085 { 1086 case eScriptReturnTypeCharPtr: // "char *" 1087 { 1088 const char format[3] = "s#"; 1089 success = PyArg_Parse (py_return.get(), format, (char **) ret_value); 1090 break; 1091 } 1092 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None 1093 { 1094 const char format[3] = "z"; 1095 success = PyArg_Parse (py_return.get(), format, (char **) ret_value); 1096 break; 1097 } 1098 case eScriptReturnTypeBool: 1099 { 1100 const char format[2] = "b"; 1101 success = PyArg_Parse (py_return.get(), format, (bool *) ret_value); 1102 break; 1103 } 1104 case eScriptReturnTypeShortInt: 1105 { 1106 const char format[2] = "h"; 1107 success = PyArg_Parse (py_return.get(), format, (short *) ret_value); 1108 break; 1109 } 1110 case eScriptReturnTypeShortIntUnsigned: 1111 { 1112 const char format[2] = "H"; 1113 success = PyArg_Parse (py_return.get(), format, (unsigned short *) ret_value); 1114 break; 1115 } 1116 case eScriptReturnTypeInt: 1117 { 1118 const char format[2] = "i"; 1119 success = PyArg_Parse (py_return.get(), format, (int *) ret_value); 1120 break; 1121 } 1122 case eScriptReturnTypeIntUnsigned: 1123 { 1124 const char format[2] = "I"; 1125 success = PyArg_Parse (py_return.get(), format, (unsigned int *) ret_value); 1126 break; 1127 } 1128 case eScriptReturnTypeLongInt: 1129 { 1130 const char format[2] = "l"; 1131 success = PyArg_Parse (py_return.get(), format, (long *) ret_value); 1132 break; 1133 } 1134 case eScriptReturnTypeLongIntUnsigned: 1135 { 1136 const char format[2] = "k"; 1137 success = PyArg_Parse (py_return.get(), format, (unsigned long *) ret_value); 1138 break; 1139 } 1140 case eScriptReturnTypeLongLong: 1141 { 1142 const char format[2] = "L"; 1143 success = PyArg_Parse (py_return.get(), format, (long long *) ret_value); 1144 break; 1145 } 1146 case eScriptReturnTypeLongLongUnsigned: 1147 { 1148 const char format[2] = "K"; 1149 success = PyArg_Parse (py_return.get(), format, (unsigned long long *) ret_value); 1150 break; 1151 } 1152 case eScriptReturnTypeFloat: 1153 { 1154 const char format[2] = "f"; 1155 success = PyArg_Parse (py_return.get(), format, (float *) ret_value); 1156 break; 1157 } 1158 case eScriptReturnTypeDouble: 1159 { 1160 const char format[2] = "d"; 1161 success = PyArg_Parse (py_return.get(), format, (double *) ret_value); 1162 break; 1163 } 1164 case eScriptReturnTypeChar: 1165 { 1166 const char format[2] = "c"; 1167 success = PyArg_Parse (py_return.get(), format, (char *) ret_value); 1168 break; 1169 } 1170 case eScriptReturnTypeOpaqueObject: 1171 { 1172 success = true; 1173 PyObject *saved_value = py_return.get(); 1174 Py_XINCREF(saved_value); 1175 *((PyObject **)ret_value) = saved_value; 1176 break; 1177 } 1178 } 1179 1180 if (success) 1181 ret_success = true; 1182 else 1183 ret_success = false; 1184 } 1185 } 1186 1187 py_error.Reset(PyRefType::Borrowed, PyErr_Occurred()); 1188 if (py_error.IsValid()) 1189 { 1190 ret_success = false; 1191 if (options.GetMaskoutErrors()) 1192 { 1193 if (PyErr_GivenExceptionMatches (py_error.get(), PyExc_SyntaxError)) 1194 PyErr_Print (); 1195 PyErr_Clear(); 1196 } 1197 } 1198 1199 return ret_success; 1200 } 1201 1202 Error 1203 ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string, const ExecuteScriptOptions &options) 1204 { 1205 Error error; 1206 1207 Locker locker(this, 1208 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::InitGlobals : 0) | Locker::NoSTDIN, 1209 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession); 1210 1211 PythonObject return_value; 1212 PythonObject &main_module = GetMainModule(); 1213 PythonDictionary globals(PyRefType::Borrowed, PyModule_GetDict(main_module.get())); 1214 PythonObject py_error; 1215 1216 PythonDictionary locals = GetSessionDictionary(); 1217 1218 if (!locals.IsValid()) 1219 locals.Reset(PyRefType::Owned, PyObject_GetAttrString(globals.get(), m_dictionary_name.c_str())); 1220 1221 if (!locals.IsValid()) 1222 locals = globals; 1223 1224 py_error.Reset(PyRefType::Borrowed, PyErr_Occurred()); 1225 if (py_error.IsValid()) 1226 PyErr_Clear(); 1227 1228 if (in_string != nullptr) 1229 { 1230 PythonObject code_object; 1231 code_object.Reset(PyRefType::Owned, Py_CompileString(in_string, "temp.py", Py_file_input)); 1232 1233 if (code_object.IsValid()) 1234 { 1235 // In Python 2.x, PyEval_EvalCode takes a PyCodeObject, but in Python 3.x, it takes 1236 // a PyObject. They are convertible (hence the function PyCode_Check(PyObject*), so 1237 // we have to do the cast for Python 2.x 1238 #if PY_MAJOR_VERSION >= 3 1239 PyObject *py_code_obj = code_object.get(); 1240 #else 1241 PyCodeObject *py_code_obj = reinterpret_cast<PyCodeObject *>(code_object.get()); 1242 #endif 1243 return_value.Reset(PyRefType::Owned, PyEval_EvalCode(py_code_obj, globals.get(), locals.get())); 1244 } 1245 } 1246 1247 py_error.Reset(PyRefType::Borrowed, PyErr_Occurred()); 1248 if (py_error.IsValid()) 1249 { 1250 // puts(in_string); 1251 // _PyObject_Dump (py_error); 1252 // PyErr_Print(); 1253 // success = false; 1254 1255 PyObject *py_type = nullptr; 1256 PyObject *py_value = nullptr; 1257 PyObject *py_traceback = nullptr; 1258 PyErr_Fetch(&py_type, &py_value, &py_traceback); 1259 1260 PythonObject type(PyRefType::Owned, py_type); 1261 PythonObject value(PyRefType::Owned, py_value); 1262 PythonObject traceback(PyRefType::Owned, py_traceback); 1263 1264 // get the backtrace 1265 std::string bt = ReadPythonBacktrace(traceback); 1266 1267 if (value.IsAllocated()) 1268 { 1269 PythonString str = value.Str(); 1270 llvm::StringRef value_str(str.GetString()); 1271 error.SetErrorStringWithFormat("%s\n%s", value_str.str().c_str(), bt.c_str()); 1272 } 1273 else 1274 error.SetErrorStringWithFormat("%s",bt.c_str()); 1275 if (options.GetMaskoutErrors()) 1276 PyErr_Clear(); 1277 } 1278 1279 return error; 1280 } 1281 1282 1283 void 1284 ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (std::vector<BreakpointOptions *> &bp_options_vec, 1285 CommandReturnObject &result) 1286 { 1287 m_active_io_handler = eIOHandlerBreakpoint; 1288 m_interpreter.GetPythonCommandsFromIOHandler (" ", *this, true, &bp_options_vec); 1289 } 1290 1291 void 1292 ScriptInterpreterPython::CollectDataForWatchpointCommandCallback (WatchpointOptions *wp_options, 1293 CommandReturnObject &result) 1294 { 1295 m_active_io_handler = eIOHandlerWatchpoint; 1296 m_interpreter.GetPythonCommandsFromIOHandler (" ", *this, true, wp_options); 1297 } 1298 1299 void 1300 ScriptInterpreterPython::SetBreakpointCommandCallbackFunction (BreakpointOptions *bp_options, 1301 const char *function_name) 1302 { 1303 // For now just cons up a oneliner that calls the provided function. 1304 std::string oneliner("return "); 1305 oneliner += function_name; 1306 oneliner += "(frame, bp_loc, internal_dict)"; 1307 m_interpreter.GetScriptInterpreter()->SetBreakpointCommandCallback (bp_options, 1308 oneliner.c_str()); 1309 } 1310 1311 // Set a Python one-liner as the callback for the breakpoint. 1312 Error 1313 ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options, 1314 const char *command_body_text) 1315 { 1316 std::unique_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData()); 1317 1318 // Split the command_body_text into lines, and pass that to GenerateBreakpointCommandCallbackData. That will 1319 // wrap the body in an auto-generated function, and return the function name in script_source. That is what 1320 // the callback will actually invoke. 1321 1322 data_ap->user_source.SplitIntoLines(command_body_text); 1323 Error error = GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source); 1324 if (error.Success()) 1325 { 1326 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release())); 1327 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp); 1328 return error; 1329 } 1330 else 1331 return error; 1332 } 1333 1334 // Set a Python one-liner as the callback for the watchpoint. 1335 void 1336 ScriptInterpreterPython::SetWatchpointCommandCallback (WatchpointOptions *wp_options, 1337 const char *oneliner) 1338 { 1339 std::unique_ptr<WatchpointOptions::CommandData> data_ap(new WatchpointOptions::CommandData()); 1340 1341 // It's necessary to set both user_source and script_source to the oneliner. 1342 // The former is used to generate callback description (as in watchpoint command list) 1343 // while the latter is used for Python to interpret during the actual callback. 1344 1345 data_ap->user_source.AppendString (oneliner); 1346 data_ap->script_source.assign (oneliner); 1347 1348 if (GenerateWatchpointCommandCallbackData (data_ap->user_source, data_ap->script_source)) 1349 { 1350 BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release())); 1351 wp_options->SetCallback (ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp); 1352 } 1353 1354 return; 1355 } 1356 1357 Error 1358 ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def) 1359 { 1360 // Convert StringList to one long, newline delimited, const char *. 1361 std::string function_def_string(function_def.CopyList()); 1362 1363 Error error = ExecuteMultipleLines (function_def_string.c_str(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false)); 1364 return error; 1365 } 1366 1367 Error 1368 ScriptInterpreterPython::GenerateFunction(const char *signature, const StringList &input) 1369 { 1370 Error error; 1371 int num_lines = input.GetSize (); 1372 if (num_lines == 0) 1373 { 1374 error.SetErrorString ("No input data."); 1375 return error; 1376 } 1377 1378 if (!signature || *signature == 0) 1379 { 1380 error.SetErrorString("No output function name."); 1381 return error; 1382 } 1383 1384 StreamString sstr; 1385 StringList auto_generated_function; 1386 auto_generated_function.AppendString (signature); 1387 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary 1388 auto_generated_function.AppendString (" new_keys = internal_dict.keys()"); // Make a list of keys in the session dict 1389 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict 1390 auto_generated_function.AppendString (" global_dict.update (internal_dict)"); // Add the session dictionary to the 1391 // global dictionary. 1392 1393 // Wrap everything up inside the function, increasing the indentation. 1394 1395 auto_generated_function.AppendString(" if True:"); 1396 for (int i = 0; i < num_lines; ++i) 1397 { 1398 sstr.Clear (); 1399 sstr.Printf (" %s", input.GetStringAtIndex (i)); 1400 auto_generated_function.AppendString (sstr.GetData()); 1401 } 1402 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict 1403 auto_generated_function.AppendString (" internal_dict[key] = global_dict[key]"); // Update session dict values 1404 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict 1405 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict 1406 1407 // Verify that the results are valid Python. 1408 1409 error = ExportFunctionDefinitionToInterpreter (auto_generated_function); 1410 1411 return error; 1412 } 1413 1414 bool 1415 ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, std::string& output, const void* name_token) 1416 { 1417 static uint32_t num_created_functions = 0; 1418 user_input.RemoveBlankLines (); 1419 StreamString sstr; 1420 1421 // Check to see if we have any data; if not, just return. 1422 if (user_input.GetSize() == 0) 1423 return false; 1424 1425 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the 1426 // ValueObject as parameter to the function. 1427 1428 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_type_print_func", num_created_functions, name_token)); 1429 sstr.Printf ("def %s (valobj, internal_dict):", auto_generated_function_name.c_str()); 1430 1431 if (!GenerateFunction(sstr.GetData(), user_input).Success()) 1432 return false; 1433 1434 // Store the name of the auto-generated function to be called. 1435 output.assign(auto_generated_function_name); 1436 return true; 1437 } 1438 1439 bool 1440 ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, std::string &output) 1441 { 1442 static uint32_t num_created_functions = 0; 1443 user_input.RemoveBlankLines (); 1444 StreamString sstr; 1445 1446 // Check to see if we have any data; if not, just return. 1447 if (user_input.GetSize() == 0) 1448 return false; 1449 1450 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_cmd_alias_func", num_created_functions)); 1451 1452 sstr.Printf ("def %s (debugger, args, result, internal_dict):", auto_generated_function_name.c_str()); 1453 1454 if (!GenerateFunction(sstr.GetData(),user_input).Success()) 1455 return false; 1456 1457 // Store the name of the auto-generated function to be called. 1458 output.assign(auto_generated_function_name); 1459 return true; 1460 } 1461 1462 1463 bool 1464 ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, std::string &output, const void* name_token) 1465 { 1466 static uint32_t num_created_classes = 0; 1467 user_input.RemoveBlankLines (); 1468 int num_lines = user_input.GetSize (); 1469 StreamString sstr; 1470 1471 // Check to see if we have any data; if not, just return. 1472 if (user_input.GetSize() == 0) 1473 return false; 1474 1475 // Wrap all user input into a Python class 1476 1477 std::string auto_generated_class_name(GenerateUniqueName("lldb_autogen_python_type_synth_class",num_created_classes,name_token)); 1478 1479 StringList auto_generated_class; 1480 1481 // Create the function name & definition string. 1482 1483 sstr.Printf ("class %s:", auto_generated_class_name.c_str()); 1484 auto_generated_class.AppendString (sstr.GetData()); 1485 1486 // Wrap everything up inside the class, increasing the indentation. 1487 // we don't need to play any fancy indentation tricks here because there is no 1488 // surrounding code whose indentation we need to honor 1489 for (int i = 0; i < num_lines; ++i) 1490 { 1491 sstr.Clear (); 1492 sstr.Printf (" %s", user_input.GetStringAtIndex (i)); 1493 auto_generated_class.AppendString (sstr.GetData()); 1494 } 1495 1496 1497 // Verify that the results are valid Python. 1498 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported) 1499 // (TODO: rename that method to ExportDefinitionToInterpreter) 1500 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class).Success()) 1501 return false; 1502 1503 // Store the name of the auto-generated class 1504 1505 output.assign(auto_generated_class_name); 1506 return true; 1507 } 1508 1509 StructuredData::GenericSP 1510 ScriptInterpreterPython::OSPlugin_CreatePluginObject(const char *class_name, lldb::ProcessSP process_sp) 1511 { 1512 if (class_name == nullptr || class_name[0] == '\0') 1513 return StructuredData::GenericSP(); 1514 1515 if (!process_sp) 1516 return StructuredData::GenericSP(); 1517 1518 void* ret_val; 1519 1520 { 1521 Locker py_lock (this, 1522 Locker::AcquireLock | Locker::NoSTDIN, 1523 Locker::FreeLock); 1524 ret_val = g_swig_create_os_plugin (class_name, 1525 m_dictionary_name.c_str(), 1526 process_sp); 1527 } 1528 1529 return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 1530 } 1531 1532 StructuredData::DictionarySP 1533 ScriptInterpreterPython::OSPlugin_RegisterInfo(StructuredData::ObjectSP os_plugin_object_sp) 1534 { 1535 Locker py_lock(this, 1536 Locker::AcquireLock | Locker::NoSTDIN, 1537 Locker::FreeLock); 1538 1539 static char callee_name[] = "get_register_info"; 1540 1541 if (!os_plugin_object_sp) 1542 return StructuredData::DictionarySP(); 1543 1544 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 1545 if (!generic) 1546 return nullptr; 1547 1548 PythonObject implementor(PyRefType::Borrowed, (PyObject *)generic->GetValue()); 1549 1550 if (!implementor.IsAllocated()) 1551 return StructuredData::DictionarySP(); 1552 1553 PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name)); 1554 1555 if (PyErr_Occurred()) 1556 PyErr_Clear(); 1557 1558 if (!pmeth.IsAllocated()) 1559 return StructuredData::DictionarySP(); 1560 1561 if (PyCallable_Check(pmeth.get()) == 0) 1562 { 1563 if (PyErr_Occurred()) 1564 PyErr_Clear(); 1565 1566 return StructuredData::DictionarySP(); 1567 } 1568 1569 if (PyErr_Occurred()) 1570 PyErr_Clear(); 1571 1572 // right now we know this function exists and is callable.. 1573 PythonObject py_return(PyRefType::Owned, PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 1574 1575 // if it fails, print the error but otherwise go on 1576 if (PyErr_Occurred()) 1577 { 1578 PyErr_Print(); 1579 PyErr_Clear(); 1580 } 1581 assert(PythonDictionary::Check(py_return.get()) && "get_register_info returned unknown object type!"); 1582 1583 PythonDictionary result_dict(PyRefType::Borrowed, py_return.get()); 1584 return result_dict.CreateStructuredDictionary(); 1585 } 1586 1587 StructuredData::ArraySP 1588 ScriptInterpreterPython::OSPlugin_ThreadsInfo(StructuredData::ObjectSP os_plugin_object_sp) 1589 { 1590 Locker py_lock (this, 1591 Locker::AcquireLock | Locker::NoSTDIN, 1592 Locker::FreeLock); 1593 1594 static char callee_name[] = "get_thread_info"; 1595 1596 if (!os_plugin_object_sp) 1597 return StructuredData::ArraySP(); 1598 1599 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 1600 if (!generic) 1601 return nullptr; 1602 1603 PythonObject implementor(PyRefType::Borrowed, (PyObject *)generic->GetValue()); 1604 1605 if (!implementor.IsAllocated()) 1606 return StructuredData::ArraySP(); 1607 1608 PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name)); 1609 1610 if (PyErr_Occurred()) 1611 PyErr_Clear(); 1612 1613 if (!pmeth.IsAllocated()) 1614 return StructuredData::ArraySP(); 1615 1616 if (PyCallable_Check(pmeth.get()) == 0) 1617 { 1618 if (PyErr_Occurred()) 1619 PyErr_Clear(); 1620 1621 return StructuredData::ArraySP(); 1622 } 1623 1624 if (PyErr_Occurred()) 1625 PyErr_Clear(); 1626 1627 // right now we know this function exists and is callable.. 1628 PythonObject py_return(PyRefType::Owned, PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 1629 1630 // if it fails, print the error but otherwise go on 1631 if (PyErr_Occurred()) 1632 { 1633 PyErr_Print(); 1634 PyErr_Clear(); 1635 } 1636 1637 assert(PythonList::Check(py_return.get()) && "get_thread_info returned unknown object type!"); 1638 1639 PythonList result_list(PyRefType::Borrowed, py_return.get()); 1640 return result_list.CreateStructuredArray(); 1641 } 1642 1643 // GetPythonValueFormatString provides a system independent type safe way to 1644 // convert a variable's type into a python value format. Python value formats 1645 // are defined in terms of builtin C types and could change from system to 1646 // as the underlying typedef for uint* types, size_t, off_t and other values 1647 // change. 1648 1649 template <typename T> 1650 const char *GetPythonValueFormatString(T t) 1651 { 1652 assert(!"Unhandled type passed to GetPythonValueFormatString(T), make a specialization of GetPythonValueFormatString() to support this type."); 1653 return nullptr; 1654 } 1655 template <> const char *GetPythonValueFormatString (char *) { return "s"; } 1656 template <> const char *GetPythonValueFormatString (char) { return "b"; } 1657 template <> const char *GetPythonValueFormatString (unsigned char) { return "B"; } 1658 template <> const char *GetPythonValueFormatString (short) { return "h"; } 1659 template <> const char *GetPythonValueFormatString (unsigned short) { return "H"; } 1660 template <> const char *GetPythonValueFormatString (int) { return "i"; } 1661 template <> const char *GetPythonValueFormatString (unsigned int) { return "I"; } 1662 template <> const char *GetPythonValueFormatString (long) { return "l"; } 1663 template <> const char *GetPythonValueFormatString (unsigned long) { return "k"; } 1664 template <> const char *GetPythonValueFormatString (long long) { return "L"; } 1665 template <> const char *GetPythonValueFormatString (unsigned long long) { return "K"; } 1666 template <> const char *GetPythonValueFormatString (float t) { return "f"; } 1667 template <> const char *GetPythonValueFormatString (double t) { return "d"; } 1668 1669 StructuredData::StringSP 1670 ScriptInterpreterPython::OSPlugin_RegisterContextData(StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) 1671 { 1672 Locker py_lock (this, 1673 Locker::AcquireLock | Locker::NoSTDIN, 1674 Locker::FreeLock); 1675 1676 static char callee_name[] = "get_register_data"; 1677 static char *param_format = const_cast<char *>(GetPythonValueFormatString(tid)); 1678 1679 if (!os_plugin_object_sp) 1680 return StructuredData::StringSP(); 1681 1682 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 1683 if (!generic) 1684 return nullptr; 1685 PythonObject implementor(PyRefType::Borrowed, (PyObject *)generic->GetValue()); 1686 1687 if (!implementor.IsAllocated()) 1688 return StructuredData::StringSP(); 1689 1690 PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name)); 1691 1692 if (PyErr_Occurred()) 1693 PyErr_Clear(); 1694 1695 if (!pmeth.IsAllocated()) 1696 return StructuredData::StringSP(); 1697 1698 if (PyCallable_Check(pmeth.get()) == 0) 1699 { 1700 if (PyErr_Occurred()) 1701 PyErr_Clear(); 1702 return StructuredData::StringSP(); 1703 } 1704 1705 if (PyErr_Occurred()) 1706 PyErr_Clear(); 1707 1708 // right now we know this function exists and is callable.. 1709 PythonObject py_return(PyRefType::Owned, PyObject_CallMethod(implementor.get(), callee_name, param_format, tid)); 1710 1711 // if it fails, print the error but otherwise go on 1712 if (PyErr_Occurred()) 1713 { 1714 PyErr_Print(); 1715 PyErr_Clear(); 1716 } 1717 1718 assert(PythonString::Check(py_return.get()) && "get_register_data returned unknown object type!"); 1719 1720 PythonString result_string(PyRefType::Borrowed, py_return.get()); 1721 return result_string.CreateStructuredString(); 1722 } 1723 1724 StructuredData::DictionarySP 1725 ScriptInterpreterPython::OSPlugin_CreateThread(StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid, lldb::addr_t context) 1726 { 1727 Locker py_lock(this, 1728 Locker::AcquireLock | Locker::NoSTDIN, 1729 Locker::FreeLock); 1730 1731 static char callee_name[] = "create_thread"; 1732 std::string param_format; 1733 param_format += GetPythonValueFormatString(tid); 1734 param_format += GetPythonValueFormatString(context); 1735 1736 if (!os_plugin_object_sp) 1737 return StructuredData::DictionarySP(); 1738 1739 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); 1740 if (!generic) 1741 return nullptr; 1742 1743 PythonObject implementor(PyRefType::Borrowed, (PyObject *)generic->GetValue()); 1744 1745 if (!implementor.IsAllocated()) 1746 return StructuredData::DictionarySP(); 1747 1748 PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name)); 1749 1750 if (PyErr_Occurred()) 1751 PyErr_Clear(); 1752 1753 if (!pmeth.IsAllocated()) 1754 return StructuredData::DictionarySP(); 1755 1756 if (PyCallable_Check(pmeth.get()) == 0) 1757 { 1758 if (PyErr_Occurred()) 1759 PyErr_Clear(); 1760 return StructuredData::DictionarySP(); 1761 } 1762 1763 if (PyErr_Occurred()) 1764 PyErr_Clear(); 1765 1766 // right now we know this function exists and is callable.. 1767 PythonObject py_return(PyRefType::Owned, PyObject_CallMethod(implementor.get(), callee_name, ¶m_format[0], tid, context)); 1768 1769 // if it fails, print the error but otherwise go on 1770 if (PyErr_Occurred()) 1771 { 1772 PyErr_Print(); 1773 PyErr_Clear(); 1774 } 1775 1776 assert(PythonDictionary::Check(py_return.get()) && "create_thread returned unknown object type!"); 1777 1778 PythonDictionary result_dict(PyRefType::Borrowed, py_return.get()); 1779 return result_dict.CreateStructuredDictionary(); 1780 } 1781 1782 StructuredData::ObjectSP 1783 ScriptInterpreterPython::CreateScriptedThreadPlan(const char *class_name, lldb::ThreadPlanSP thread_plan_sp) 1784 { 1785 if (class_name == nullptr || class_name[0] == '\0') 1786 return StructuredData::ObjectSP(); 1787 1788 if (!thread_plan_sp.get()) 1789 return StructuredData::ObjectSP(); 1790 1791 Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger(); 1792 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter(); 1793 ScriptInterpreterPython *python_interpreter = static_cast<ScriptInterpreterPython *>(script_interpreter); 1794 1795 if (!script_interpreter) 1796 return StructuredData::ObjectSP(); 1797 1798 void* ret_val; 1799 1800 { 1801 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1802 1803 ret_val = g_swig_thread_plan_script (class_name, 1804 python_interpreter->m_dictionary_name.c_str(), 1805 thread_plan_sp); 1806 } 1807 1808 return StructuredData::ObjectSP(new StructuredPythonObject(ret_val)); 1809 } 1810 1811 bool 1812 ScriptInterpreterPython::ScriptedThreadPlanExplainsStop(StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) 1813 { 1814 bool explains_stop = true; 1815 StructuredData::Generic *generic = nullptr; 1816 if (implementor_sp) 1817 generic = implementor_sp->GetAsGeneric(); 1818 if (generic) 1819 { 1820 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1821 explains_stop = g_swig_call_thread_plan(generic->GetValue(), "explains_stop", event, script_error); 1822 if (script_error) 1823 return true; 1824 } 1825 return explains_stop; 1826 } 1827 1828 bool 1829 ScriptInterpreterPython::ScriptedThreadPlanShouldStop(StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) 1830 { 1831 bool should_stop = true; 1832 StructuredData::Generic *generic = nullptr; 1833 if (implementor_sp) 1834 generic = implementor_sp->GetAsGeneric(); 1835 if (generic) 1836 { 1837 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1838 should_stop = g_swig_call_thread_plan(generic->GetValue(), "should_stop", event, script_error); 1839 if (script_error) 1840 return true; 1841 } 1842 return should_stop; 1843 } 1844 1845 lldb::StateType 1846 ScriptInterpreterPython::ScriptedThreadPlanGetRunState(StructuredData::ObjectSP implementor_sp, bool &script_error) 1847 { 1848 bool should_step = false; 1849 StructuredData::Generic *generic = nullptr; 1850 if (implementor_sp) 1851 generic = implementor_sp->GetAsGeneric(); 1852 if (generic) 1853 { 1854 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1855 should_step = g_swig_call_thread_plan(generic->GetValue(), "should_step", NULL, script_error); 1856 if (script_error) 1857 should_step = true; 1858 } 1859 if (should_step) 1860 return lldb::eStateStepping; 1861 else 1862 return lldb::eStateRunning; 1863 } 1864 1865 StructuredData::ObjectSP 1866 ScriptInterpreterPython::LoadPluginModule(const FileSpec &file_spec, lldb_private::Error &error) 1867 { 1868 if (!file_spec.Exists()) 1869 { 1870 error.SetErrorString("no such file"); 1871 return StructuredData::ObjectSP(); 1872 } 1873 1874 StructuredData::ObjectSP module_sp; 1875 1876 if (LoadScriptingModule(file_spec.GetPath().c_str(),true,true,error,&module_sp)) 1877 return module_sp; 1878 1879 return StructuredData::ObjectSP(); 1880 } 1881 1882 StructuredData::DictionarySP 1883 ScriptInterpreterPython::GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target, const char *setting_name, 1884 lldb_private::Error &error) 1885 { 1886 if (!plugin_module_sp || !target || !setting_name || !setting_name[0] || !g_swig_plugin_get) 1887 return StructuredData::DictionarySP(); 1888 StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric(); 1889 if (!generic) 1890 return StructuredData::DictionarySP(); 1891 1892 PythonObject reply_pyobj; 1893 { 1894 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1895 TargetSP target_sp(target->shared_from_this()); 1896 reply_pyobj.Reset(PyRefType::Owned, 1897 (PyObject *)g_swig_plugin_get(generic->GetValue(), setting_name, target_sp)); 1898 } 1899 1900 PythonDictionary py_dict(PyRefType::Borrowed, reply_pyobj.get()); 1901 return py_dict.CreateStructuredDictionary(); 1902 } 1903 1904 StructuredData::ObjectSP 1905 ScriptInterpreterPython::CreateSyntheticScriptedProvider(const char *class_name, lldb::ValueObjectSP valobj) 1906 { 1907 if (class_name == nullptr || class_name[0] == '\0') 1908 return StructuredData::ObjectSP(); 1909 1910 if (!valobj.get()) 1911 return StructuredData::ObjectSP(); 1912 1913 ExecutionContext exe_ctx (valobj->GetExecutionContextRef()); 1914 Target *target = exe_ctx.GetTargetPtr(); 1915 1916 if (!target) 1917 return StructuredData::ObjectSP(); 1918 1919 Debugger &debugger = target->GetDebugger(); 1920 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter(); 1921 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter; 1922 1923 if (!script_interpreter) 1924 return StructuredData::ObjectSP(); 1925 1926 void *ret_val = nullptr; 1927 1928 { 1929 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1930 ret_val = g_swig_synthetic_script (class_name, 1931 python_interpreter->m_dictionary_name.c_str(), 1932 valobj); 1933 } 1934 1935 return StructuredData::ObjectSP(new StructuredPythonObject(ret_val)); 1936 } 1937 1938 StructuredData::GenericSP 1939 ScriptInterpreterPython::CreateScriptCommandObject (const char *class_name) 1940 { 1941 DebuggerSP debugger_sp(GetCommandInterpreter().GetDebugger().shared_from_this()); 1942 1943 if (class_name == nullptr || class_name[0] == '\0') 1944 return StructuredData::GenericSP(); 1945 1946 if (!debugger_sp.get()) 1947 return StructuredData::GenericSP(); 1948 1949 void* ret_val; 1950 1951 { 1952 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 1953 ret_val = g_swig_create_cmd (class_name, 1954 m_dictionary_name.c_str(), 1955 debugger_sp); 1956 } 1957 1958 return StructuredData::GenericSP(new StructuredPythonObject(ret_val)); 1959 } 1960 1961 bool 1962 ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, std::string& output, const void* name_token) 1963 { 1964 StringList input; 1965 input.SplitIntoLines(oneliner, strlen(oneliner)); 1966 return GenerateTypeScriptFunction(input, output, name_token); 1967 } 1968 1969 bool 1970 ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, std::string& output, const void* name_token) 1971 { 1972 StringList input; 1973 input.SplitIntoLines(oneliner, strlen(oneliner)); 1974 return GenerateTypeSynthClass(input, output, name_token); 1975 } 1976 1977 1978 Error 1979 ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, std::string& output) 1980 { 1981 static uint32_t num_created_functions = 0; 1982 user_input.RemoveBlankLines (); 1983 StreamString sstr; 1984 Error error; 1985 if (user_input.GetSize() == 0) 1986 { 1987 error.SetErrorString("No input data."); 1988 return error; 1989 } 1990 1991 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_bp_callback_func_",num_created_functions)); 1992 sstr.Printf ("def %s (frame, bp_loc, internal_dict):", auto_generated_function_name.c_str()); 1993 1994 error = GenerateFunction(sstr.GetData(), user_input); 1995 if (!error.Success()) 1996 return error; 1997 1998 // Store the name of the auto-generated function to be called. 1999 output.assign(auto_generated_function_name); 2000 return error; 2001 } 2002 2003 bool 2004 ScriptInterpreterPython::GenerateWatchpointCommandCallbackData (StringList &user_input, std::string& output) 2005 { 2006 static uint32_t num_created_functions = 0; 2007 user_input.RemoveBlankLines (); 2008 StreamString sstr; 2009 2010 if (user_input.GetSize() == 0) 2011 return false; 2012 2013 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_wp_callback_func_",num_created_functions)); 2014 sstr.Printf ("def %s (frame, wp, internal_dict):", auto_generated_function_name.c_str()); 2015 2016 if (!GenerateFunction(sstr.GetData(), user_input).Success()) 2017 return false; 2018 2019 // Store the name of the auto-generated function to be called. 2020 output.assign(auto_generated_function_name); 2021 return true; 2022 } 2023 2024 bool 2025 ScriptInterpreterPython::GetScriptedSummary(const char *python_function_name, lldb::ValueObjectSP valobj, 2026 StructuredData::ObjectSP &callee_wrapper_sp, const TypeSummaryOptions &options, 2027 std::string &retval) 2028 { 2029 2030 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); 2031 2032 if (!valobj.get()) 2033 { 2034 retval.assign("<no object>"); 2035 return false; 2036 } 2037 2038 void *old_callee = nullptr; 2039 StructuredData::Generic *generic = nullptr; 2040 if (callee_wrapper_sp) 2041 { 2042 generic = callee_wrapper_sp->GetAsGeneric(); 2043 if (generic) 2044 old_callee = generic->GetValue(); 2045 } 2046 void* new_callee = old_callee; 2047 2048 bool ret_val; 2049 if (python_function_name && *python_function_name) 2050 { 2051 { 2052 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2053 { 2054 TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options)); 2055 2056 Timer scoped_timer ("g_swig_typescript_callback","g_swig_typescript_callback"); 2057 ret_val = g_swig_typescript_callback (python_function_name, 2058 GetSessionDictionary().get(), 2059 valobj, 2060 &new_callee, 2061 options_sp, 2062 retval); 2063 } 2064 } 2065 } 2066 else 2067 { 2068 retval.assign("<no function name>"); 2069 return false; 2070 } 2071 2072 if (new_callee && old_callee != new_callee) 2073 callee_wrapper_sp.reset(new StructuredPythonObject(new_callee)); 2074 2075 return ret_val; 2076 } 2077 2078 void 2079 ScriptInterpreterPython::Clear () 2080 { 2081 // Release any global variables that might have strong references to 2082 // LLDB objects when clearing the python script interpreter. 2083 Locker locker(this, 2084 ScriptInterpreterPython::Locker::AcquireLock, 2085 ScriptInterpreterPython::Locker::FreeAcquiredLock); 2086 2087 // This may be called as part of Py_Finalize. In that case the modules are destroyed in random 2088 // order and we can't guarantee that we can access these. 2089 if (Py_IsInitialized()) 2090 PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process = None; lldb.thread = None; lldb.frame = None"); 2091 } 2092 2093 bool 2094 ScriptInterpreterPython::BreakpointCallbackFunction 2095 ( 2096 void *baton, 2097 StoppointCallbackContext *context, 2098 user_id_t break_id, 2099 user_id_t break_loc_id 2100 ) 2101 { 2102 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton; 2103 const char *python_function_name = bp_option_data->script_source.c_str(); 2104 2105 if (!context) 2106 return true; 2107 2108 ExecutionContext exe_ctx (context->exe_ctx_ref); 2109 Target *target = exe_ctx.GetTargetPtr(); 2110 2111 if (!target) 2112 return true; 2113 2114 Debugger &debugger = target->GetDebugger(); 2115 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter(); 2116 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter; 2117 2118 if (!script_interpreter) 2119 return true; 2120 2121 if (python_function_name && python_function_name[0]) 2122 { 2123 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP()); 2124 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id); 2125 if (breakpoint_sp) 2126 { 2127 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id)); 2128 2129 if (stop_frame_sp && bp_loc_sp) 2130 { 2131 bool ret_val = true; 2132 { 2133 Locker py_lock(python_interpreter, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2134 ret_val = g_swig_breakpoint_callback (python_function_name, 2135 python_interpreter->m_dictionary_name.c_str(), 2136 stop_frame_sp, 2137 bp_loc_sp); 2138 } 2139 return ret_val; 2140 } 2141 } 2142 } 2143 // We currently always true so we stop in case anything goes wrong when 2144 // trying to call the script function 2145 return true; 2146 } 2147 2148 bool 2149 ScriptInterpreterPython::WatchpointCallbackFunction 2150 ( 2151 void *baton, 2152 StoppointCallbackContext *context, 2153 user_id_t watch_id 2154 ) 2155 { 2156 WatchpointOptions::CommandData *wp_option_data = (WatchpointOptions::CommandData *) baton; 2157 const char *python_function_name = wp_option_data->script_source.c_str(); 2158 2159 if (!context) 2160 return true; 2161 2162 ExecutionContext exe_ctx (context->exe_ctx_ref); 2163 Target *target = exe_ctx.GetTargetPtr(); 2164 2165 if (!target) 2166 return true; 2167 2168 Debugger &debugger = target->GetDebugger(); 2169 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter(); 2170 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter; 2171 2172 if (!script_interpreter) 2173 return true; 2174 2175 if (python_function_name && python_function_name[0]) 2176 { 2177 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP()); 2178 WatchpointSP wp_sp = target->GetWatchpointList().FindByID (watch_id); 2179 if (wp_sp) 2180 { 2181 if (stop_frame_sp && wp_sp) 2182 { 2183 bool ret_val = true; 2184 { 2185 Locker py_lock(python_interpreter, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2186 ret_val = g_swig_watchpoint_callback (python_function_name, 2187 python_interpreter->m_dictionary_name.c_str(), 2188 stop_frame_sp, 2189 wp_sp); 2190 } 2191 return ret_val; 2192 } 2193 } 2194 } 2195 // We currently always true so we stop in case anything goes wrong when 2196 // trying to call the script function 2197 return true; 2198 } 2199 2200 size_t 2201 ScriptInterpreterPython::CalculateNumChildren(const StructuredData::ObjectSP &implementor_sp) 2202 { 2203 if (!implementor_sp) 2204 return 0; 2205 StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 2206 if (!generic) 2207 return 0; 2208 void *implementor = generic->GetValue(); 2209 if (!implementor) 2210 return 0; 2211 2212 if (!g_swig_calc_children) 2213 return 0; 2214 2215 size_t ret_val = 0; 2216 2217 { 2218 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2219 ret_val = g_swig_calc_children (implementor); 2220 } 2221 2222 return ret_val; 2223 } 2224 2225 lldb::ValueObjectSP 2226 ScriptInterpreterPython::GetChildAtIndex(const StructuredData::ObjectSP &implementor_sp, uint32_t idx) 2227 { 2228 if (!implementor_sp) 2229 return lldb::ValueObjectSP(); 2230 2231 StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 2232 if (!generic) 2233 return lldb::ValueObjectSP(); 2234 void *implementor = generic->GetValue(); 2235 if (!implementor) 2236 return lldb::ValueObjectSP(); 2237 2238 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue) 2239 return lldb::ValueObjectSP(); 2240 2241 lldb::ValueObjectSP ret_val; 2242 2243 { 2244 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2245 void* child_ptr = g_swig_get_child_index (implementor,idx); 2246 if (child_ptr != nullptr && child_ptr != Py_None) 2247 { 2248 lldb::SBValue* sb_value_ptr = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr); 2249 if (sb_value_ptr == nullptr) 2250 Py_XDECREF(child_ptr); 2251 else 2252 ret_val = g_swig_get_valobj_sp_from_sbvalue (sb_value_ptr); 2253 } 2254 else 2255 { 2256 Py_XDECREF(child_ptr); 2257 } 2258 } 2259 2260 return ret_val; 2261 } 2262 2263 int 2264 ScriptInterpreterPython::GetIndexOfChildWithName(const StructuredData::ObjectSP &implementor_sp, const char *child_name) 2265 { 2266 if (!implementor_sp) 2267 return UINT32_MAX; 2268 2269 StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 2270 if (!generic) 2271 return UINT32_MAX; 2272 void *implementor = generic->GetValue(); 2273 if (!implementor) 2274 return UINT32_MAX; 2275 2276 if (!g_swig_get_index_child) 2277 return UINT32_MAX; 2278 2279 int ret_val = UINT32_MAX; 2280 2281 { 2282 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2283 ret_val = g_swig_get_index_child (implementor, child_name); 2284 } 2285 2286 return ret_val; 2287 } 2288 2289 bool 2290 ScriptInterpreterPython::UpdateSynthProviderInstance(const StructuredData::ObjectSP &implementor_sp) 2291 { 2292 bool ret_val = false; 2293 2294 if (!implementor_sp) 2295 return ret_val; 2296 2297 StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 2298 if (!generic) 2299 return ret_val; 2300 void *implementor = generic->GetValue(); 2301 if (!implementor) 2302 return ret_val; 2303 2304 if (!g_swig_update_provider) 2305 return ret_val; 2306 2307 { 2308 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2309 ret_val = g_swig_update_provider (implementor); 2310 } 2311 2312 return ret_val; 2313 } 2314 2315 bool 2316 ScriptInterpreterPython::MightHaveChildrenSynthProviderInstance(const StructuredData::ObjectSP &implementor_sp) 2317 { 2318 bool ret_val = false; 2319 2320 if (!implementor_sp) 2321 return ret_val; 2322 2323 StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 2324 if (!generic) 2325 return ret_val; 2326 void *implementor = generic->GetValue(); 2327 if (!implementor) 2328 return ret_val; 2329 2330 if (!g_swig_mighthavechildren_provider) 2331 return ret_val; 2332 2333 { 2334 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2335 ret_val = g_swig_mighthavechildren_provider (implementor); 2336 } 2337 2338 return ret_val; 2339 } 2340 2341 lldb::ValueObjectSP 2342 ScriptInterpreterPython::GetSyntheticValue(const StructuredData::ObjectSP &implementor_sp) 2343 { 2344 lldb::ValueObjectSP ret_val(nullptr); 2345 2346 if (!implementor_sp) 2347 return ret_val; 2348 2349 StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); 2350 if (!generic) 2351 return ret_val; 2352 void *implementor = generic->GetValue(); 2353 if (!implementor) 2354 return ret_val; 2355 2356 if (!g_swig_getvalue_provider || !g_swig_cast_to_sbvalue || !g_swig_get_valobj_sp_from_sbvalue) 2357 return ret_val; 2358 2359 { 2360 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2361 void* child_ptr = g_swig_getvalue_provider (implementor); 2362 if (child_ptr != nullptr && child_ptr != Py_None) 2363 { 2364 lldb::SBValue* sb_value_ptr = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr); 2365 if (sb_value_ptr == nullptr) 2366 Py_XDECREF(child_ptr); 2367 else 2368 ret_val = g_swig_get_valobj_sp_from_sbvalue (sb_value_ptr); 2369 } 2370 else 2371 { 2372 Py_XDECREF(child_ptr); 2373 } 2374 } 2375 2376 return ret_val; 2377 } 2378 2379 static std::string 2380 ReadPythonBacktrace(PythonObject py_backtrace) 2381 { 2382 PythonObject traceback_module; 2383 PythonObject stringIO_module; 2384 PythonObject stringIO_builder; 2385 PythonObject stringIO_buffer; 2386 PythonObject printTB; 2387 PythonObject printTB_args; 2388 PythonObject printTB_result; 2389 PythonObject stringIO_getvalue; 2390 PythonObject printTB_string; 2391 2392 std::string retval("backtrace unavailable"); 2393 2394 if (!py_backtrace.IsAllocated()) 2395 return retval; 2396 2397 traceback_module.Reset(PyRefType::Owned, PyImport_ImportModule("traceback")); 2398 stringIO_module.Reset(PyRefType::Owned, PyImport_ImportModule("StringIO")); 2399 if (!traceback_module.IsAllocated() || !stringIO_module.IsAllocated()) 2400 return retval; 2401 2402 stringIO_builder.Reset(PyRefType::Owned, PyObject_GetAttrString(stringIO_module.get(), "StringIO")); 2403 if (!stringIO_builder.IsAllocated()) 2404 return retval; 2405 2406 stringIO_buffer.Reset(PyRefType::Owned, PyObject_CallObject(stringIO_builder.get(), nullptr)); 2407 if (!stringIO_buffer.IsAllocated()) 2408 return retval; 2409 2410 printTB.Reset(PyRefType::Owned, PyObject_GetAttrString(traceback_module.get(), "print_tb")); 2411 if (!printTB.IsAllocated()) 2412 return retval; 2413 2414 printTB_args.Reset(PyRefType::Owned, Py_BuildValue("OOO", py_backtrace.get(), Py_None, stringIO_buffer.get())); 2415 printTB_result.Reset(PyRefType::Owned, PyObject_CallObject(printTB.get(), printTB_args.get())); 2416 stringIO_getvalue.Reset(PyRefType::Owned, PyObject_GetAttrString(stringIO_buffer.get(), "getvalue")); 2417 if (!stringIO_getvalue.IsAllocated()) 2418 return retval; 2419 2420 printTB_string.Reset(PyRefType::Owned, PyObject_CallObject(stringIO_getvalue.get(), nullptr)); 2421 if (!printTB_string.IsAllocated()) 2422 return retval; 2423 2424 PythonString str(PyRefType::Borrowed, printTB_string.get()); 2425 llvm::StringRef string_data(str.GetString()); 2426 retval.assign(string_data.data(), string_data.size()); 2427 2428 return retval; 2429 } 2430 2431 bool 2432 ScriptInterpreterPython::RunScriptFormatKeyword (const char* impl_function, 2433 Process* process, 2434 std::string& output, 2435 Error& error) 2436 { 2437 bool ret_val; 2438 if (!process) 2439 { 2440 error.SetErrorString("no process"); 2441 return false; 2442 } 2443 if (!impl_function || !impl_function[0]) 2444 { 2445 error.SetErrorString("no function to execute"); 2446 return false; 2447 } 2448 if (!g_swig_run_script_keyword_process) 2449 { 2450 error.SetErrorString("internal helper function missing"); 2451 return false; 2452 } 2453 { 2454 ProcessSP process_sp(process->shared_from_this()); 2455 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2456 ret_val = g_swig_run_script_keyword_process (impl_function, m_dictionary_name.c_str(), process_sp, output); 2457 if (!ret_val) 2458 error.SetErrorString("python script evaluation failed"); 2459 } 2460 return ret_val; 2461 } 2462 2463 bool 2464 ScriptInterpreterPython::RunScriptFormatKeyword (const char* impl_function, 2465 Thread* thread, 2466 std::string& output, 2467 Error& error) 2468 { 2469 bool ret_val; 2470 if (!thread) 2471 { 2472 error.SetErrorString("no thread"); 2473 return false; 2474 } 2475 if (!impl_function || !impl_function[0]) 2476 { 2477 error.SetErrorString("no function to execute"); 2478 return false; 2479 } 2480 if (!g_swig_run_script_keyword_thread) 2481 { 2482 error.SetErrorString("internal helper function missing"); 2483 return false; 2484 } 2485 { 2486 ThreadSP thread_sp(thread->shared_from_this()); 2487 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2488 ret_val = g_swig_run_script_keyword_thread (impl_function, m_dictionary_name.c_str(), thread_sp, output); 2489 if (!ret_val) 2490 error.SetErrorString("python script evaluation failed"); 2491 } 2492 return ret_val; 2493 } 2494 2495 bool 2496 ScriptInterpreterPython::RunScriptFormatKeyword (const char* impl_function, 2497 Target* target, 2498 std::string& output, 2499 Error& error) 2500 { 2501 bool ret_val; 2502 if (!target) 2503 { 2504 error.SetErrorString("no thread"); 2505 return false; 2506 } 2507 if (!impl_function || !impl_function[0]) 2508 { 2509 error.SetErrorString("no function to execute"); 2510 return false; 2511 } 2512 if (!g_swig_run_script_keyword_target) 2513 { 2514 error.SetErrorString("internal helper function missing"); 2515 return false; 2516 } 2517 { 2518 TargetSP target_sp(target->shared_from_this()); 2519 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2520 ret_val = g_swig_run_script_keyword_target (impl_function, m_dictionary_name.c_str(), target_sp, output); 2521 if (!ret_val) 2522 error.SetErrorString("python script evaluation failed"); 2523 } 2524 return ret_val; 2525 } 2526 2527 bool 2528 ScriptInterpreterPython::RunScriptFormatKeyword (const char* impl_function, 2529 StackFrame* frame, 2530 std::string& output, 2531 Error& error) 2532 { 2533 bool ret_val; 2534 if (!frame) 2535 { 2536 error.SetErrorString("no frame"); 2537 return false; 2538 } 2539 if (!impl_function || !impl_function[0]) 2540 { 2541 error.SetErrorString("no function to execute"); 2542 return false; 2543 } 2544 if (!g_swig_run_script_keyword_frame) 2545 { 2546 error.SetErrorString("internal helper function missing"); 2547 return false; 2548 } 2549 { 2550 StackFrameSP frame_sp(frame->shared_from_this()); 2551 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2552 ret_val = g_swig_run_script_keyword_frame (impl_function, m_dictionary_name.c_str(), frame_sp, output); 2553 if (!ret_val) 2554 error.SetErrorString("python script evaluation failed"); 2555 } 2556 return ret_val; 2557 } 2558 2559 bool 2560 ScriptInterpreterPython::RunScriptFormatKeyword (const char* impl_function, 2561 ValueObject *value, 2562 std::string& output, 2563 Error& error) 2564 { 2565 bool ret_val; 2566 if (!value) 2567 { 2568 error.SetErrorString("no value"); 2569 return false; 2570 } 2571 if (!impl_function || !impl_function[0]) 2572 { 2573 error.SetErrorString("no function to execute"); 2574 return false; 2575 } 2576 if (!g_swig_run_script_keyword_value) 2577 { 2578 error.SetErrorString("internal helper function missing"); 2579 return false; 2580 } 2581 { 2582 ValueObjectSP value_sp(value->GetSP()); 2583 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); 2584 ret_val = g_swig_run_script_keyword_value (impl_function, m_dictionary_name.c_str(), value_sp, output); 2585 if (!ret_val) 2586 error.SetErrorString("python script evaluation failed"); 2587 } 2588 return ret_val; 2589 } 2590 2591 uint64_t replace_all(std::string& str, const std::string& oldStr, const std::string& newStr) 2592 { 2593 size_t pos = 0; 2594 uint64_t matches = 0; 2595 while((pos = str.find(oldStr, pos)) != std::string::npos) 2596 { 2597 matches++; 2598 str.replace(pos, oldStr.length(), newStr); 2599 pos += newStr.length(); 2600 } 2601 return matches; 2602 } 2603 2604 bool 2605 ScriptInterpreterPython::LoadScriptingModule(const char *pathname, bool can_reload, bool init_session, lldb_private::Error &error, 2606 StructuredData::ObjectSP *module_sp) 2607 { 2608 if (!pathname || !pathname[0]) 2609 { 2610 error.SetErrorString("invalid pathname"); 2611 return false; 2612 } 2613 2614 if (!g_swig_call_module_init) 2615 { 2616 error.SetErrorString("internal helper function missing"); 2617 return false; 2618 } 2619 2620 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this(); 2621 2622 { 2623 FileSpec target_file(pathname, true); 2624 std::string basename(target_file.GetFilename().GetCString()); 2625 2626 StreamString command_stream; 2627 2628 // Before executing Pyton code, lock the GIL. 2629 Locker py_lock (this, 2630 Locker::AcquireLock | (init_session ? Locker::InitSession : 0) | Locker::NoSTDIN, 2631 Locker::FreeAcquiredLock | (init_session ? Locker::TearDownSession : 0)); 2632 2633 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid || 2634 target_file.GetFileType() == FileSpec::eFileTypeUnknown) 2635 { 2636 // if not a valid file of any sort, check if it might be a filename still 2637 // dot can't be used but / and \ can, and if either is found, reject 2638 if (strchr(pathname,'\\') || strchr(pathname,'/')) 2639 { 2640 error.SetErrorString("invalid pathname"); 2641 return false; 2642 } 2643 basename = pathname; // not a filename, probably a package of some sort, let it go through 2644 } 2645 else if (target_file.GetFileType() == FileSpec::eFileTypeDirectory || 2646 target_file.GetFileType() == FileSpec::eFileTypeRegular || 2647 target_file.GetFileType() == FileSpec::eFileTypeSymbolicLink) 2648 { 2649 std::string directory(target_file.GetDirectory().GetCString()); 2650 replace_all(directory,"'","\\'"); 2651 2652 // now make sure that Python has "directory" in the search path 2653 StreamString command_stream; 2654 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.insert(1,'%s');\n\n", 2655 directory.c_str(), 2656 directory.c_str()); 2657 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false).SetSetLLDBGlobals(false)).Success(); 2658 if (!syspath_retval) 2659 { 2660 error.SetErrorString("Python sys.path handling failed"); 2661 return false; 2662 } 2663 2664 // strip .py or .pyc extension 2665 ConstString extension = target_file.GetFileNameExtension(); 2666 if (extension) 2667 { 2668 if (::strcmp(extension.GetCString(), "py") == 0) 2669 basename.resize(basename.length()-3); 2670 else if(::strcmp(extension.GetCString(), "pyc") == 0) 2671 basename.resize(basename.length()-4); 2672 } 2673 } 2674 else 2675 { 2676 error.SetErrorString("no known way to import this module specification"); 2677 return false; 2678 } 2679 2680 // check if the module is already import-ed 2681 command_stream.Clear(); 2682 command_stream.Printf("sys.modules.__contains__('%s')",basename.c_str()); 2683 bool does_contain = false; 2684 // this call will succeed if the module was ever imported in any Debugger in the lifetime of the process 2685 // in which this LLDB framework is living 2686 bool was_imported_globally = (ExecuteOneLineWithReturn(command_stream.GetData(), 2687 ScriptInterpreterPython::eScriptReturnTypeBool, 2688 &does_contain, 2689 ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false).SetSetLLDBGlobals(false)) && does_contain); 2690 // this call will fail if the module was not imported in this Debugger before 2691 command_stream.Clear(); 2692 command_stream.Printf("sys.getrefcount(%s)",basename.c_str()); 2693 bool was_imported_locally = GetSessionDictionary().GetItemForKey(PythonString(basename)).IsAllocated(); 2694 2695 bool was_imported = (was_imported_globally || was_imported_locally); 2696 2697 if (was_imported == true && can_reload == false) 2698 { 2699 error.SetErrorString("module already imported"); 2700 return false; 2701 } 2702 2703 // now actually do the import 2704 command_stream.Clear(); 2705 2706 if (was_imported) 2707 { 2708 if (!was_imported_locally) 2709 command_stream.Printf("import %s ; reload(%s)",basename.c_str(),basename.c_str()); 2710 else 2711 command_stream.Printf("reload(%s)",basename.c_str()); 2712 } 2713 else 2714 command_stream.Printf("import %s",basename.c_str()); 2715 2716 error = ExecuteMultipleLines(command_stream.GetData(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false).SetSetLLDBGlobals(false)); 2717 if (error.Fail()) 2718 return false; 2719 2720 // if we are here, everything worked 2721 // call __lldb_init_module(debugger,dict) 2722 if (!g_swig_call_module_init (basename.c_str(), 2723 m_dictionary_name.c_str(), 2724 debugger_sp)) 2725 { 2726 error.SetErrorString("calling __lldb_init_module failed"); 2727 return false; 2728 } 2729 2730 if (module_sp) 2731 { 2732 // everything went just great, now set the module object 2733 command_stream.Clear(); 2734 command_stream.Printf("%s",basename.c_str()); 2735 void* module_pyobj = nullptr; 2736 if (ExecuteOneLineWithReturn(command_stream.GetData(),ScriptInterpreter::eScriptReturnTypeOpaqueObject,&module_pyobj) && module_pyobj) 2737 module_sp->reset(new StructuredPythonObject(module_pyobj)); 2738 } 2739 2740 return true; 2741 } 2742 } 2743 2744 bool 2745 ScriptInterpreterPython::IsReservedWord (const char* word) 2746 { 2747 if (!word || !word[0]) 2748 return false; 2749 2750 llvm::StringRef word_sr(word); 2751 2752 // filter out a few characters that would just confuse us 2753 // and that are clearly not keyword material anyway 2754 if (word_sr.find_first_of("'\"") != llvm::StringRef::npos) 2755 return false; 2756 2757 StreamString command_stream; 2758 command_stream.Printf("keyword.iskeyword('%s')", word); 2759 bool result; 2760 ExecuteScriptOptions options; 2761 options.SetEnableIO(false); 2762 options.SetMaskoutErrors(true); 2763 options.SetSetLLDBGlobals(false); 2764 if (ExecuteOneLineWithReturn(command_stream.GetData(), ScriptInterpreter::eScriptReturnTypeBool, &result, options)) 2765 return result; 2766 return false; 2767 } 2768 2769 ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp, 2770 ScriptedCommandSynchronicity synchro) : 2771 m_debugger_sp(debugger_sp), 2772 m_synch_wanted(synchro), 2773 m_old_asynch(debugger_sp->GetAsyncExecution()) 2774 { 2775 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous) 2776 m_debugger_sp->SetAsyncExecution(false); 2777 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous) 2778 m_debugger_sp->SetAsyncExecution(true); 2779 } 2780 2781 ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler() 2782 { 2783 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue) 2784 m_debugger_sp->SetAsyncExecution(m_old_asynch); 2785 } 2786 2787 bool 2788 ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function, 2789 const char* args, 2790 ScriptedCommandSynchronicity synchronicity, 2791 lldb_private::CommandReturnObject& cmd_retobj, 2792 Error& error, 2793 const lldb_private::ExecutionContext& exe_ctx) 2794 { 2795 if (!impl_function) 2796 { 2797 error.SetErrorString("no function to execute"); 2798 return false; 2799 } 2800 2801 if (!g_swig_call_command) 2802 { 2803 error.SetErrorString("no helper function to run scripted commands"); 2804 return false; 2805 } 2806 2807 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this(); 2808 lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); 2809 2810 if (!debugger_sp.get()) 2811 { 2812 error.SetErrorString("invalid Debugger pointer"); 2813 return false; 2814 } 2815 2816 bool ret_val = false; 2817 2818 std::string err_msg; 2819 2820 { 2821 Locker py_lock(this, 2822 Locker::AcquireLock | Locker::InitSession | (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN), 2823 Locker::FreeLock | Locker::TearDownSession); 2824 2825 SynchronicityHandler synch_handler(debugger_sp, 2826 synchronicity); 2827 2828 ret_val = g_swig_call_command (impl_function, 2829 m_dictionary_name.c_str(), 2830 debugger_sp, 2831 args, 2832 cmd_retobj, 2833 exe_ctx_ref_sp); 2834 } 2835 2836 if (!ret_val) 2837 error.SetErrorString("unable to execute script function"); 2838 else 2839 error.Clear(); 2840 2841 return ret_val; 2842 } 2843 2844 bool 2845 ScriptInterpreterPython::RunScriptBasedCommand (StructuredData::GenericSP impl_obj_sp, 2846 const char* args, 2847 ScriptedCommandSynchronicity synchronicity, 2848 lldb_private::CommandReturnObject& cmd_retobj, 2849 Error& error, 2850 const lldb_private::ExecutionContext& exe_ctx) 2851 { 2852 if (!impl_obj_sp || !impl_obj_sp->IsValid()) 2853 { 2854 error.SetErrorString("no function to execute"); 2855 return false; 2856 } 2857 2858 if (!g_swig_call_command_object) 2859 { 2860 error.SetErrorString("no helper function to run scripted commands"); 2861 return false; 2862 } 2863 2864 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this(); 2865 lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); 2866 2867 if (!debugger_sp.get()) 2868 { 2869 error.SetErrorString("invalid Debugger pointer"); 2870 return false; 2871 } 2872 2873 bool ret_val = false; 2874 2875 std::string err_msg; 2876 2877 { 2878 Locker py_lock(this, 2879 Locker::AcquireLock | Locker::InitSession | (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN), 2880 Locker::FreeLock | Locker::TearDownSession); 2881 2882 SynchronicityHandler synch_handler(debugger_sp, 2883 synchronicity); 2884 2885 ret_val = g_swig_call_command_object (impl_obj_sp->GetValue(), 2886 debugger_sp, 2887 args, 2888 cmd_retobj, 2889 exe_ctx_ref_sp); 2890 } 2891 2892 if (!ret_val) 2893 error.SetErrorString("unable to execute script function"); 2894 else 2895 error.Clear(); 2896 2897 return ret_val; 2898 } 2899 2900 // in Python, a special attribute __doc__ contains the docstring 2901 // for an object (function, method, class, ...) if any is defined 2902 // Otherwise, the attribute's value is None 2903 bool 2904 ScriptInterpreterPython::GetDocumentationForItem(const char* item, std::string& dest) 2905 { 2906 dest.clear(); 2907 if (!item || !*item) 2908 return false; 2909 std::string command(item); 2910 command += ".__doc__"; 2911 2912 char* result_ptr = nullptr; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully 2913 2914 if (ExecuteOneLineWithReturn (command.c_str(), 2915 ScriptInterpreter::eScriptReturnTypeCharStrOrNone, 2916 &result_ptr, 2917 ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false))) 2918 { 2919 if (result_ptr) 2920 dest.assign(result_ptr); 2921 return true; 2922 } 2923 else 2924 { 2925 StreamString str_stream; 2926 str_stream.Printf("Function %s was not found. Containing module might be missing.",item); 2927 dest.assign(str_stream.GetData()); 2928 return false; 2929 } 2930 } 2931 2932 bool 2933 ScriptInterpreterPython::GetShortHelpForCommandObject (StructuredData::GenericSP cmd_obj_sp, 2934 std::string& dest) 2935 { 2936 bool got_string = false; 2937 dest.clear(); 2938 2939 Locker py_lock (this, 2940 Locker::AcquireLock | Locker::NoSTDIN, 2941 Locker::FreeLock); 2942 2943 static char callee_name[] = "get_short_help"; 2944 2945 if (!cmd_obj_sp) 2946 return false; 2947 2948 PythonObject implementor(PyRefType::Borrowed, (PyObject *)cmd_obj_sp->GetValue()); 2949 2950 if (!implementor.IsAllocated()) 2951 return false; 2952 2953 PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name)); 2954 2955 if (PyErr_Occurred()) 2956 PyErr_Clear(); 2957 2958 if (!pmeth.IsAllocated()) 2959 return false; 2960 2961 if (PyCallable_Check(pmeth.get()) == 0) 2962 { 2963 if (PyErr_Occurred()) 2964 PyErr_Clear(); 2965 return false; 2966 } 2967 2968 if (PyErr_Occurred()) 2969 PyErr_Clear(); 2970 2971 // right now we know this function exists and is callable.. 2972 PythonObject py_return(PyRefType::Owned, PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 2973 2974 // if it fails, print the error but otherwise go on 2975 if (PyErr_Occurred()) 2976 { 2977 PyErr_Print(); 2978 PyErr_Clear(); 2979 } 2980 2981 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) 2982 { 2983 PythonString py_string(PyRefType::Borrowed, py_return.get()); 2984 llvm::StringRef return_data(py_string.GetString()); 2985 dest.assign(return_data.data(), return_data.size()); 2986 got_string = true; 2987 } 2988 return got_string; 2989 } 2990 2991 uint32_t 2992 ScriptInterpreterPython::GetFlagsForCommandObject (StructuredData::GenericSP cmd_obj_sp) 2993 { 2994 uint32_t result = 0; 2995 2996 Locker py_lock (this, 2997 Locker::AcquireLock | Locker::NoSTDIN, 2998 Locker::FreeLock); 2999 3000 static char callee_name[] = "get_flags"; 3001 3002 if (!cmd_obj_sp) 3003 return result; 3004 3005 PythonObject implementor(PyRefType::Borrowed, (PyObject *)cmd_obj_sp->GetValue()); 3006 3007 if (!implementor.IsAllocated()) 3008 return result; 3009 3010 PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name)); 3011 3012 if (PyErr_Occurred()) 3013 PyErr_Clear(); 3014 3015 if (!pmeth.IsAllocated()) 3016 return result; 3017 3018 if (PyCallable_Check(pmeth.get()) == 0) 3019 { 3020 if (PyErr_Occurred()) 3021 PyErr_Clear(); 3022 return result; 3023 } 3024 3025 if (PyErr_Occurred()) 3026 PyErr_Clear(); 3027 3028 // right now we know this function exists and is callable.. 3029 PythonObject py_return(PyRefType::Owned, PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 3030 3031 // if it fails, print the error but otherwise go on 3032 if (PyErr_Occurred()) 3033 { 3034 PyErr_Print(); 3035 PyErr_Clear(); 3036 } 3037 3038 if (py_return.IsAllocated() && PythonInteger::Check(py_return.get())) 3039 { 3040 PythonInteger int_value(PyRefType::Borrowed, py_return.get()); 3041 result = int_value.GetInteger(); 3042 } 3043 3044 return result; 3045 } 3046 3047 bool 3048 ScriptInterpreterPython::GetLongHelpForCommandObject (StructuredData::GenericSP cmd_obj_sp, 3049 std::string& dest) 3050 { 3051 bool got_string = false; 3052 dest.clear(); 3053 3054 Locker py_lock (this, 3055 Locker::AcquireLock | Locker::NoSTDIN, 3056 Locker::FreeLock); 3057 3058 static char callee_name[] = "get_long_help"; 3059 3060 if (!cmd_obj_sp) 3061 return false; 3062 3063 PythonObject implementor(PyRefType::Borrowed, (PyObject *)cmd_obj_sp->GetValue()); 3064 3065 if (!implementor.IsAllocated()) 3066 return false; 3067 3068 PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name)); 3069 3070 if (PyErr_Occurred()) 3071 PyErr_Clear(); 3072 3073 if (!pmeth.IsAllocated()) 3074 return false; 3075 3076 if (PyCallable_Check(pmeth.get()) == 0) 3077 { 3078 if (PyErr_Occurred()) 3079 PyErr_Clear(); 3080 3081 return false; 3082 } 3083 3084 if (PyErr_Occurred()) 3085 PyErr_Clear(); 3086 3087 // right now we know this function exists and is callable.. 3088 PythonObject py_return(PyRefType::Owned, PyObject_CallMethod(implementor.get(), callee_name, nullptr)); 3089 3090 // if it fails, print the error but otherwise go on 3091 if (PyErr_Occurred()) 3092 { 3093 PyErr_Print(); 3094 PyErr_Clear(); 3095 } 3096 3097 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) 3098 { 3099 PythonString str(PyRefType::Borrowed, py_return.get()); 3100 llvm::StringRef str_data(str.GetString()); 3101 dest.assign(str_data.data(), str_data.size()); 3102 got_string = true; 3103 } 3104 3105 return got_string; 3106 } 3107 3108 std::unique_ptr<ScriptInterpreterLocker> 3109 ScriptInterpreterPython::AcquireInterpreterLock () 3110 { 3111 std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(this, 3112 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN, 3113 Locker::FreeLock | Locker::TearDownSession)); 3114 return py_lock; 3115 } 3116 3117 void 3118 ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback swig_init_callback, 3119 SWIGBreakpointCallbackFunction swig_breakpoint_callback, 3120 SWIGWatchpointCallbackFunction swig_watchpoint_callback, 3121 SWIGPythonTypeScriptCallbackFunction swig_typescript_callback, 3122 SWIGPythonCreateSyntheticProvider swig_synthetic_script, 3123 SWIGPythonCreateCommandObject swig_create_cmd, 3124 SWIGPythonCalculateNumChildren swig_calc_children, 3125 SWIGPythonGetChildAtIndex swig_get_child_index, 3126 SWIGPythonGetIndexOfChildWithName swig_get_index_child, 3127 SWIGPythonCastPyObjectToSBValue swig_cast_to_sbvalue , 3128 SWIGPythonGetValueObjectSPFromSBValue swig_get_valobj_sp_from_sbvalue, 3129 SWIGPythonUpdateSynthProviderInstance swig_update_provider, 3130 SWIGPythonMightHaveChildrenSynthProviderInstance swig_mighthavechildren_provider, 3131 SWIGPythonGetValueSynthProviderInstance swig_getvalue_provider, 3132 SWIGPythonCallCommand swig_call_command, 3133 SWIGPythonCallCommandObject swig_call_command_object, 3134 SWIGPythonCallModuleInit swig_call_module_init, 3135 SWIGPythonCreateOSPlugin swig_create_os_plugin, 3136 SWIGPythonScriptKeyword_Process swig_run_script_keyword_process, 3137 SWIGPythonScriptKeyword_Thread swig_run_script_keyword_thread, 3138 SWIGPythonScriptKeyword_Target swig_run_script_keyword_target, 3139 SWIGPythonScriptKeyword_Frame swig_run_script_keyword_frame, 3140 SWIGPythonScriptKeyword_Value swig_run_script_keyword_value, 3141 SWIGPython_GetDynamicSetting swig_plugin_get, 3142 SWIGPythonCreateScriptedThreadPlan swig_thread_plan_script, 3143 SWIGPythonCallThreadPlan swig_call_thread_plan) 3144 { 3145 g_swig_init_callback = swig_init_callback; 3146 g_swig_breakpoint_callback = swig_breakpoint_callback; 3147 g_swig_watchpoint_callback = swig_watchpoint_callback; 3148 g_swig_typescript_callback = swig_typescript_callback; 3149 g_swig_synthetic_script = swig_synthetic_script; 3150 g_swig_create_cmd = swig_create_cmd; 3151 g_swig_calc_children = swig_calc_children; 3152 g_swig_get_child_index = swig_get_child_index; 3153 g_swig_get_index_child = swig_get_index_child; 3154 g_swig_cast_to_sbvalue = swig_cast_to_sbvalue; 3155 g_swig_get_valobj_sp_from_sbvalue = swig_get_valobj_sp_from_sbvalue; 3156 g_swig_update_provider = swig_update_provider; 3157 g_swig_mighthavechildren_provider = swig_mighthavechildren_provider; 3158 g_swig_getvalue_provider = swig_getvalue_provider; 3159 g_swig_call_command = swig_call_command; 3160 g_swig_call_command_object = swig_call_command_object; 3161 g_swig_call_module_init = swig_call_module_init; 3162 g_swig_create_os_plugin = swig_create_os_plugin; 3163 g_swig_run_script_keyword_process = swig_run_script_keyword_process; 3164 g_swig_run_script_keyword_thread = swig_run_script_keyword_thread; 3165 g_swig_run_script_keyword_target = swig_run_script_keyword_target; 3166 g_swig_run_script_keyword_frame = swig_run_script_keyword_frame; 3167 g_swig_run_script_keyword_value = swig_run_script_keyword_value; 3168 g_swig_plugin_get = swig_plugin_get; 3169 g_swig_thread_plan_script = swig_thread_plan_script; 3170 g_swig_call_thread_plan = swig_call_thread_plan; 3171 } 3172 3173 void 3174 ScriptInterpreterPython::InitializePrivate () 3175 { 3176 assert(!g_initialized && "ScriptInterpreterPython::InitializePrivate() called more than once!"); 3177 g_initialized = true; 3178 3179 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); 3180 3181 // RAII-based initialization which correctly handles multiple-initialization, version- 3182 // specific differences among Python 2 and Python 3, and saving and restoring various 3183 // other pieces of state that can get mucked with during initialization. 3184 InitializePythonRAII initialize_guard; 3185 3186 if (g_swig_init_callback) 3187 g_swig_init_callback (); 3188 3189 // Update the path python uses to search for modules to include the current directory. 3190 3191 PyRun_SimpleString ("import sys"); 3192 AddToSysPath(AddLocation::End, "."); 3193 3194 FileSpec file_spec; 3195 // Don't denormalize paths when calling file_spec.GetPath(). On platforms that use 3196 // a backslash as the path separator, this will result in executing python code containing 3197 // paths with unescaped backslashes. But Python also accepts forward slashes, so to make 3198 // life easier we just use that. 3199 if (HostInfo::GetLLDBPath(ePathTypePythonDir, file_spec)) 3200 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false)); 3201 if (HostInfo::GetLLDBPath(ePathTypeLLDBShlibDir, file_spec)) 3202 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false)); 3203 3204 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"); 3205 } 3206 3207 void 3208 ScriptInterpreterPython::AddToSysPath(AddLocation location, std::string path) 3209 { 3210 std::string path_copy; 3211 3212 std::string statement; 3213 if (location == AddLocation::Beginning) 3214 { 3215 statement.assign("sys.path.insert(0,\""); 3216 statement.append (path); 3217 statement.append ("\")"); 3218 } 3219 else 3220 { 3221 statement.assign("sys.path.append(\""); 3222 statement.append(path); 3223 statement.append("\")"); 3224 } 3225 PyRun_SimpleString (statement.c_str()); 3226 } 3227 3228 3229 //void 3230 //ScriptInterpreterPython::Terminate () 3231 //{ 3232 // // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling 3233 // // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers 3234 // // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls 3235 // // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate, 3236 // // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls 3237 // // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from 3238 // // within Py_Finalize, which results in a seg fault. 3239 // // 3240 // // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't 3241 // // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the 3242 // // process exits). 3243 // // 3244 //// Py_Finalize (); 3245 //} 3246 3247 #endif // #ifdef LLDB_DISABLE_PYTHON 3248