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