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