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