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