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