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