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