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