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