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