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