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