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