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