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