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