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