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