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