1 //===-- ScriptInterpreterPython.cpp -----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifdef LLDB_DISABLE_PYTHON
12 // Python is disabled in this build
16 // LLDB Python header must be included first
17 #include "lldb-python.h"
19 #include "PythonDataObjects.h"
20 #include "PythonExceptionState.h"
21 #include "ScriptInterpreterPython.h"
29 #include "lldb/API/SBValue.h"
30 #include "lldb/Breakpoint/BreakpointLocation.h"
31 #include "lldb/Breakpoint/StoppointCallbackContext.h"
32 #include "lldb/Breakpoint/WatchpointOptions.h"
33 #include "lldb/Core/Communication.h"
34 #include "lldb/Core/Debugger.h"
35 #include "lldb/Core/PluginManager.h"
36 #include "lldb/Core/ValueObject.h"
37 #include "lldb/DataFormatters/TypeSummary.h"
38 #include "lldb/Host/ConnectionFileDescriptor.h"
39 #include "lldb/Host/FileSystem.h"
40 #include "lldb/Host/HostInfo.h"
41 #include "lldb/Host/Pipe.h"
42 #include "lldb/Interpreter/CommandInterpreter.h"
43 #include "lldb/Interpreter/CommandReturnObject.h"
44 #include "lldb/Target/Thread.h"
45 #include "lldb/Target/ThreadPlan.h"
46 #include "lldb/Utility/Timer.h"
49 #include "lldb/Host/windows/ConnectionGenericFileWindows.h"
52 #include "llvm/ADT/STLExtras.h"
53 #include "llvm/ADT/StringRef.h"
54 #include "llvm/Support/FileSystem.h"
57 using namespace lldb_private;
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 =
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 =
106 static ScriptInterpreterPython::SWIGPythonCreateScriptedThreadPlan
107 g_swig_thread_plan_script = nullptr;
108 static ScriptInterpreterPython::SWIGPythonCallThreadPlan
109 g_swig_call_thread_plan = nullptr;
111 static bool g_initialized = false;
115 // Initializing Python is not a straightforward process. We cannot control
116 // what external code may have done before getting to this point in LLDB,
117 // including potentially having already initialized Python, so we need to do a
118 // lot of work to ensure that the existing state of the system is maintained
119 // across our initialization. We do this by using an RAII pattern where we
120 // save off initial state at the beginning, and restore it at the end
121 struct InitializePythonRAII {
123 InitializePythonRAII()
124 : m_gil_state(PyGILState_UNLOCKED), m_was_already_initialized(false) {
125 // Python will muck with STDIN terminal state, so save off any current TTY
126 // settings so we can restore them.
127 m_stdin_tty_state.Save(STDIN_FILENO, false);
129 InitializePythonHome();
131 // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
132 // calling `Py_Initialize` and `PyEval_InitThreads`. < 3.2 requires that you
133 // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
134 #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
136 InitializeThreadsPrivate();
138 InitializeThreadsPrivate();
143 ~InitializePythonRAII() {
144 if (m_was_already_initialized) {
145 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
146 LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
147 m_was_already_initialized == PyGILState_UNLOCKED ? "un" : "");
148 PyGILState_Release(m_gil_state);
150 // We initialized the threads in this function, just unlock the GIL.
154 m_stdin_tty_state.Restore();
158 void InitializePythonHome() {
159 #if defined(LLDB_PYTHON_HOME)
160 #if PY_MAJOR_VERSION >= 3
162 static wchar_t *g_python_home = Py_DecodeLocale(LLDB_PYTHON_HOME, &size);
164 static char g_python_home[] = LLDB_PYTHON_HOME;
166 Py_SetPythonHome(g_python_home);
170 void InitializeThreadsPrivate() {
171 if (PyEval_ThreadsInitialized()) {
172 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
174 m_was_already_initialized = true;
175 m_gil_state = PyGILState_Ensure();
176 LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n",
177 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
181 // InitThreads acquires the GIL if it hasn't been called before.
182 PyEval_InitThreads();
185 TerminalState m_stdin_tty_state;
186 PyGILState_STATE m_gil_state;
187 bool m_was_already_initialized;
191 ScriptInterpreterPython::Locker::Locker(ScriptInterpreterPython *py_interpreter,
192 uint16_t on_entry, uint16_t on_leave,
193 FILE *in, FILE *out, FILE *err)
194 : ScriptInterpreterLocker(),
195 m_teardown_session((on_leave & TearDownSession) == TearDownSession),
196 m_python_interpreter(py_interpreter) {
198 if ((on_entry & InitSession) == InitSession) {
199 if (DoInitSession(on_entry, in, out, err) == false) {
200 // Don't teardown the session if we didn't init it.
201 m_teardown_session = false;
206 bool ScriptInterpreterPython::Locker::DoAcquireLock() {
207 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
208 m_GILState = PyGILState_Ensure();
209 LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked",
210 m_GILState == PyGILState_UNLOCKED ? "un" : "");
212 // we need to save the thread state when we first start the command because
213 // we might decide to interrupt it while some action is taking place outside
214 // of Python (e.g. printing to screen, waiting for the network, ...) in that
215 // case, _PyThreadState_Current will be NULL - and we would be unable to set
216 // the asynchronous exception - not a desirable situation
217 m_python_interpreter->SetThreadState(PyThreadState_Get());
218 m_python_interpreter->IncrementLockCount();
222 bool ScriptInterpreterPython::Locker::DoInitSession(uint16_t on_entry_flags,
225 if (!m_python_interpreter)
227 return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
230 bool ScriptInterpreterPython::Locker::DoFreeLock() {
231 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
232 LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
233 m_GILState == PyGILState_UNLOCKED ? "un" : "");
234 PyGILState_Release(m_GILState);
235 m_python_interpreter->DecrementLockCount();
239 bool ScriptInterpreterPython::Locker::DoTearDownSession() {
240 if (!m_python_interpreter)
242 m_python_interpreter->LeaveSession();
246 ScriptInterpreterPython::Locker::~Locker() {
247 if (m_teardown_session)
252 ScriptInterpreterPython::ScriptInterpreterPython(
253 CommandInterpreter &interpreter)
254 : ScriptInterpreter(interpreter, eScriptLanguagePython),
255 IOHandlerDelegateMultiline("DONE"), m_saved_stdin(), m_saved_stdout(),
256 m_saved_stderr(), m_main_module(), m_lldb_module(),
257 m_session_dict(PyInitialValue::Invalid),
258 m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(),
259 m_run_one_line_str_global(),
261 interpreter.GetDebugger().GetInstanceName().AsCString()),
262 m_terminal_state(), m_active_io_handler(eIOHandlerNone),
263 m_session_is_active(false), m_pty_slave_is_open(false),
264 m_valid_session(true), m_lock_count(0), m_command_thread_state(nullptr) {
267 m_dictionary_name.append("_dict");
268 StreamString run_string;
269 run_string.Printf("%s = dict()", m_dictionary_name.c_str());
271 Locker locker(this, ScriptInterpreterPython::Locker::AcquireLock,
272 ScriptInterpreterPython::Locker::FreeAcquiredLock);
273 PyRun_SimpleString(run_string.GetData());
277 "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
278 m_dictionary_name.c_str());
279 PyRun_SimpleString(run_string.GetData());
281 // Reloading modules requires a different syntax in Python 2 and Python 3.
282 // This provides a consistent syntax no matter what version of Python.
284 run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')",
285 m_dictionary_name.c_str());
286 PyRun_SimpleString(run_string.GetData());
288 // WARNING: temporary code that loads Cocoa formatters - this should be done
289 // on a per-platform basis rather than loading the whole set and letting the
290 // individual formatter classes exploit APIs to check whether they can/cannot
294 "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')",
295 m_dictionary_name.c_str());
296 PyRun_SimpleString(run_string.GetData());
299 run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
300 "lldb.embedded_interpreter import run_python_interpreter; "
301 "from lldb.embedded_interpreter import run_one_line')",
302 m_dictionary_name.c_str());
303 PyRun_SimpleString(run_string.GetData());
306 run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
307 "; pydoc.pager = pydoc.plainpager')",
308 m_dictionary_name.c_str(),
309 interpreter.GetDebugger().GetID());
310 PyRun_SimpleString(run_string.GetData());
313 ScriptInterpreterPython::~ScriptInterpreterPython() {
314 // the session dictionary may hold objects with complex state which means
315 // that they may need to be torn down with some level of smarts and that, in
316 // turn, requires a valid thread state force Python to procure itself such a
317 // thread state, nuke the session dictionary and then release it for others
318 // to use and proceed with the rest of the shutdown
319 auto gil_state = PyGILState_Ensure();
320 m_session_dict.Reset();
321 PyGILState_Release(gil_state);
324 void ScriptInterpreterPython::Initialize() {
325 static llvm::once_flag g_once_flag;
327 llvm::call_once(g_once_flag, []() {
328 PluginManager::RegisterPlugin(GetPluginNameStatic(),
329 GetPluginDescriptionStatic(),
330 lldb::eScriptLanguagePython, CreateInstance);
334 void ScriptInterpreterPython::Terminate() {}
336 lldb::ScriptInterpreterSP
337 ScriptInterpreterPython::CreateInstance(CommandInterpreter &interpreter) {
338 return std::make_shared<ScriptInterpreterPython>(interpreter);
341 lldb_private::ConstString ScriptInterpreterPython::GetPluginNameStatic() {
342 static ConstString g_name("script-python");
346 const char *ScriptInterpreterPython::GetPluginDescriptionStatic() {
347 return "Embedded Python interpreter";
350 void ScriptInterpreterPython::ComputePythonDirForApple(
351 llvm::SmallVectorImpl<char> &path) {
352 auto style = llvm::sys::path::Style::posix;
354 llvm::StringRef path_ref(path.begin(), path.size());
355 auto rbegin = llvm::sys::path::rbegin(path_ref, style);
356 auto rend = llvm::sys::path::rend(path_ref);
357 auto framework = std::find(rbegin, rend, "LLDB.framework");
358 if (framework == rend) {
359 ComputePythonDirForPosix(path);
362 path.resize(framework - rend);
363 llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
366 void ScriptInterpreterPython::ComputePythonDirForPosix(
367 llvm::SmallVectorImpl<char> &path) {
368 auto style = llvm::sys::path::Style::posix;
369 #if defined(LLDB_PYTHON_RELATIVE_LIBDIR)
370 // Build the path by backing out of the lib dir, then building with whatever
371 // the real python interpreter uses. (e.g. lib for most, lib64 on RHEL
373 llvm::sys::path::remove_filename(path, style);
374 llvm::sys::path::append(path, style, LLDB_PYTHON_RELATIVE_LIBDIR);
376 llvm::sys::path::append(path, style,
377 "python" + llvm::Twine(PY_MAJOR_VERSION) + "." +
378 llvm::Twine(PY_MINOR_VERSION),
383 void ScriptInterpreterPython::ComputePythonDirForWindows(
384 llvm::SmallVectorImpl<char> &path) {
385 auto style = llvm::sys::path::Style::windows;
386 llvm::sys::path::remove_filename(path, style);
387 llvm::sys::path::append(path, style, "lib", "site-packages");
389 // This will be injected directly through FileSpec.GetDirectory().SetString(),
390 // so we need to normalize manually.
391 std::replace(path.begin(), path.end(), '\\', '/');
394 FileSpec ScriptInterpreterPython::GetPythonDir() {
395 static FileSpec g_spec = []() {
396 FileSpec spec = HostInfo::GetShlibDir();
399 llvm::SmallString<64> path;
402 #if defined(__APPLE__)
403 ComputePythonDirForApple(path);
404 #elif defined(_WIN32)
405 ComputePythonDirForWindows(path);
407 ComputePythonDirForPosix(path);
409 spec.GetDirectory().SetString(path);
415 lldb_private::ConstString ScriptInterpreterPython::GetPluginName() {
416 return GetPluginNameStatic();
419 uint32_t ScriptInterpreterPython::GetPluginVersion() { return 1; }
421 void ScriptInterpreterPython::IOHandlerActivated(IOHandler &io_handler) {
422 const char *instructions = nullptr;
424 switch (m_active_io_handler) {
427 case eIOHandlerBreakpoint:
428 instructions = R"(Enter your Python command(s). Type 'DONE' to end.
429 def function (frame, bp_loc, internal_dict):
430 """frame: the lldb.SBFrame for the location at which you stopped
431 bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
432 internal_dict: an LLDB support object not to be used"""
435 case eIOHandlerWatchpoint:
436 instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
441 StreamFileSP output_sp(io_handler.GetOutputStreamFile());
443 output_sp->PutCString(instructions);
449 void ScriptInterpreterPython::IOHandlerInputComplete(IOHandler &io_handler,
451 io_handler.SetIsDone(true);
452 bool batch_mode = m_interpreter.GetBatchCommandMode();
454 switch (m_active_io_handler) {
457 case eIOHandlerBreakpoint: {
458 std::vector<BreakpointOptions *> *bp_options_vec =
459 (std::vector<BreakpointOptions *> *)io_handler.GetUserData();
460 for (auto bp_options : *bp_options_vec) {
464 auto data_ap = llvm::make_unique<CommandDataPython>();
467 data_ap->user_source.SplitIntoLines(data);
469 if (GenerateBreakpointCommandCallbackData(data_ap->user_source,
470 data_ap->script_source)
472 auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
474 bp_options->SetCallback(
475 ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
476 } else if (!batch_mode) {
477 StreamFileSP error_sp = io_handler.GetErrorStreamFile();
479 error_sp->Printf("Warning: No command attached to breakpoint.\n");
484 m_active_io_handler = eIOHandlerNone;
486 case eIOHandlerWatchpoint: {
487 WatchpointOptions *wp_options =
488 (WatchpointOptions *)io_handler.GetUserData();
489 auto data_ap = llvm::make_unique<WatchpointOptions::CommandData>();
490 data_ap->user_source.SplitIntoLines(data);
492 if (GenerateWatchpointCommandCallbackData(data_ap->user_source,
493 data_ap->script_source)) {
495 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_ap));
496 wp_options->SetCallback(
497 ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp);
498 } else if (!batch_mode) {
499 StreamFileSP error_sp = io_handler.GetErrorStreamFile();
501 error_sp->Printf("Warning: No command attached to breakpoint.\n");
505 m_active_io_handler = eIOHandlerNone;
510 void ScriptInterpreterPython::ResetOutputFileHandle(FILE *fh) {}
512 void ScriptInterpreterPython::SaveTerminalState(int fd) {
513 // Python mucks with the terminal state of STDIN. If we can possibly avoid
514 // this by setting the file handles up correctly prior to entering the
515 // interpreter we should. For now we save and restore the terminal state on
516 // the input file handle.
517 m_terminal_state.Save(fd, false);
520 void ScriptInterpreterPython::RestoreTerminalState() {
521 // Python mucks with the terminal state of STDIN. If we can possibly avoid
522 // this by setting the file handles up correctly prior to entering the
523 // interpreter we should. For now we save and restore the terminal state on
524 // the input file handle.
525 m_terminal_state.Restore();
528 void ScriptInterpreterPython::LeaveSession() {
529 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
531 log->PutCString("ScriptInterpreterPython::LeaveSession()");
533 // checking that we have a valid thread state - since we use our own
534 // threading and locking in some (rare) cases during cleanup Python may end
535 // up believing we have no thread state and PyImport_AddModule will crash if
536 // that is the case - since that seems to only happen when destroying the
537 // SBDebugger, we can make do without clearing up stdout and stderr
539 // rdar://problem/11292882
540 // When the current thread state is NULL, PyThreadState_Get() issues a fatal
542 if (PyThreadState_GetDict()) {
543 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
544 if (sys_module_dict.IsValid()) {
545 if (m_saved_stdin.IsValid()) {
546 sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
547 m_saved_stdin.Reset();
549 if (m_saved_stdout.IsValid()) {
550 sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
551 m_saved_stdout.Reset();
553 if (m_saved_stderr.IsValid()) {
554 sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
555 m_saved_stderr.Reset();
560 m_session_is_active = false;
563 bool ScriptInterpreterPython::SetStdHandle(File &file, const char *py_name,
564 PythonFile &save_file,
566 if (file.IsValid()) {
567 // Flush the file before giving it to python to avoid interleaved output.
570 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
572 save_file = sys_module_dict.GetItemForKey(PythonString(py_name))
573 .AsType<PythonFile>();
575 PythonFile new_file(file, mode);
576 sys_module_dict.SetItemForKey(PythonString(py_name), new_file);
583 bool ScriptInterpreterPython::EnterSession(uint16_t on_entry_flags, FILE *in,
584 FILE *out, FILE *err) {
585 // If we have already entered the session, without having officially 'left'
586 // it, then there is no need to 'enter' it again.
587 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
588 if (m_session_is_active) {
591 "ScriptInterpreterPython::EnterSession(on_entry_flags=0x%" PRIx16
592 ") session is already active, returning without doing anything",
599 "ScriptInterpreterPython::EnterSession(on_entry_flags=0x%" PRIx16 ")",
602 m_session_is_active = true;
604 StreamString run_string;
606 if (on_entry_flags & Locker::InitGlobals) {
607 run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
608 m_dictionary_name.c_str(),
609 GetCommandInterpreter().GetDebugger().GetID());
611 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
612 GetCommandInterpreter().GetDebugger().GetID());
613 run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
614 run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
615 run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
616 run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
617 run_string.PutCString("')");
619 // If we aren't initing the globals, we should still always set the
620 // debugger (since that is always unique.)
621 run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
622 m_dictionary_name.c_str(),
623 GetCommandInterpreter().GetDebugger().GetID());
625 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
626 GetCommandInterpreter().GetDebugger().GetID());
627 run_string.PutCString("')");
630 PyRun_SimpleString(run_string.GetData());
633 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
634 if (sys_module_dict.IsValid()) {
635 File in_file(in, false);
636 File out_file(out, false);
637 File err_file(err, false);
639 lldb::StreamFileSP in_sp;
640 lldb::StreamFileSP out_sp;
641 lldb::StreamFileSP err_sp;
642 if (!in_file.IsValid() || !out_file.IsValid() || !err_file.IsValid())
643 m_interpreter.GetDebugger().AdoptTopIOHandlerFilesIfInvalid(in_sp, out_sp,
646 if (on_entry_flags & Locker::NoSTDIN) {
647 m_saved_stdin.Reset();
649 if (!SetStdHandle(in_file, "stdin", m_saved_stdin, "r")) {
651 SetStdHandle(in_sp->GetFile(), "stdin", m_saved_stdin, "r");
655 if (!SetStdHandle(out_file, "stdout", m_saved_stdout, "w")) {
657 SetStdHandle(out_sp->GetFile(), "stdout", m_saved_stdout, "w");
660 if (!SetStdHandle(err_file, "stderr", m_saved_stderr, "w")) {
662 SetStdHandle(err_sp->GetFile(), "stderr", m_saved_stderr, "w");
666 if (PyErr_Occurred())
672 PythonObject &ScriptInterpreterPython::GetMainModule() {
673 if (!m_main_module.IsValid())
674 m_main_module.Reset(PyRefType::Borrowed, PyImport_AddModule("__main__"));
675 return m_main_module;
678 PythonDictionary &ScriptInterpreterPython::GetSessionDictionary() {
679 if (m_session_dict.IsValid())
680 return m_session_dict;
682 PythonObject &main_module = GetMainModule();
683 if (!main_module.IsValid())
684 return m_session_dict;
686 PythonDictionary main_dict(PyRefType::Borrowed,
687 PyModule_GetDict(main_module.get()));
688 if (!main_dict.IsValid())
689 return m_session_dict;
691 PythonObject item = main_dict.GetItemForKey(PythonString(m_dictionary_name));
692 m_session_dict.Reset(PyRefType::Borrowed, item.get());
693 return m_session_dict;
696 PythonDictionary &ScriptInterpreterPython::GetSysModuleDictionary() {
697 if (m_sys_module_dict.IsValid())
698 return m_sys_module_dict;
700 PythonObject sys_module(PyRefType::Borrowed, PyImport_AddModule("sys"));
701 if (sys_module.IsValid())
702 m_sys_module_dict.Reset(PyRefType::Borrowed,
703 PyModule_GetDict(sys_module.get()));
704 return m_sys_module_dict;
707 static std::string GenerateUniqueName(const char *base_name_wanted,
708 uint32_t &functions_counter,
709 const void *name_token = nullptr) {
712 if (!base_name_wanted)
713 return std::string();
716 sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
718 sstr.Printf("%s_%p", base_name_wanted, name_token);
720 return sstr.GetString();
723 bool ScriptInterpreterPython::GetEmbeddedInterpreterModuleObjects() {
724 if (m_run_one_line_function.IsValid())
727 PythonObject module(PyRefType::Borrowed,
728 PyImport_AddModule("lldb.embedded_interpreter"));
729 if (!module.IsValid())
732 PythonDictionary module_dict(PyRefType::Borrowed,
733 PyModule_GetDict(module.get()));
734 if (!module_dict.IsValid())
737 m_run_one_line_function =
738 module_dict.GetItemForKey(PythonString("run_one_line"));
739 m_run_one_line_str_global =
740 module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
741 return m_run_one_line_function.IsValid();
744 static void ReadThreadBytesReceived(void *baton, const void *src,
746 if (src && src_len) {
747 Stream *strm = (Stream *)baton;
748 strm->Write(src, src_len);
753 bool ScriptInterpreterPython::ExecuteOneLine(
754 llvm::StringRef command, CommandReturnObject *result,
755 const ExecuteScriptOptions &options) {
756 std::string command_str = command.str();
758 if (!m_valid_session)
761 if (!command.empty()) {
762 // We want to call run_one_line, passing in the dictionary and the command
763 // string. We cannot do this through PyRun_SimpleString here because the
764 // command string may contain escaped characters, and putting it inside
765 // another string to pass to PyRun_SimpleString messes up the escaping. So
766 // we use the following more complicated method to pass the command string
767 // directly down to Python.
768 Debugger &debugger = m_interpreter.GetDebugger();
770 StreamFileSP input_file_sp;
771 StreamFileSP output_file_sp;
772 StreamFileSP error_file_sp;
773 Communication output_comm(
774 "lldb.ScriptInterpreterPython.ExecuteOneLine.comm");
775 bool join_read_thread = false;
776 if (options.GetEnableIO()) {
778 input_file_sp = debugger.GetInputFile();
779 // Set output to a temporary file so we can forward the results on to
783 Status pipe_result = pipe.CreateNew(false);
784 if (pipe_result.Success()) {
786 lldb::file_t read_file = pipe.GetReadNativeHandle();
787 pipe.ReleaseReadFileDescriptor();
788 std::unique_ptr<ConnectionGenericFile> conn_ap(
789 new ConnectionGenericFile(read_file, true));
791 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
792 new ConnectionFileDescriptor(pipe.ReleaseReadFileDescriptor(),
795 if (conn_ap->IsConnected()) {
796 output_comm.SetConnection(conn_ap.release());
797 output_comm.SetReadThreadBytesReceivedCallback(
798 ReadThreadBytesReceived, &result->GetOutputStream());
799 output_comm.StartReadThread();
800 join_read_thread = true;
801 FILE *outfile_handle =
802 fdopen(pipe.ReleaseWriteFileDescriptor(), "w");
803 output_file_sp.reset(new StreamFile(outfile_handle, true));
804 error_file_sp = output_file_sp;
806 ::setbuf(outfile_handle, nullptr);
808 result->SetImmediateOutputFile(
809 debugger.GetOutputFile()->GetFile().GetStream());
810 result->SetImmediateErrorFile(
811 debugger.GetErrorFile()->GetFile().GetStream());
815 if (!input_file_sp || !output_file_sp || !error_file_sp)
816 debugger.AdoptTopIOHandlerFilesIfInvalid(input_file_sp, output_file_sp,
819 input_file_sp.reset(new StreamFile());
820 input_file_sp->GetFile().Open(FileSystem::DEV_NULL,
821 File::eOpenOptionRead);
822 output_file_sp.reset(new StreamFile());
823 output_file_sp->GetFile().Open(FileSystem::DEV_NULL,
824 File::eOpenOptionWrite);
825 error_file_sp = output_file_sp;
828 FILE *in_file = input_file_sp->GetFile().GetStream();
829 FILE *out_file = output_file_sp->GetFile().GetStream();
830 FILE *err_file = error_file_sp->GetFile().GetStream();
831 bool success = false;
833 // WARNING! It's imperative that this RAII scope be as tight as
834 // possible. In particular, the scope must end *before* we try to join
835 // the read thread. The reason for this is that a pre-requisite for
836 // joining the read thread is that we close the write handle (to break
837 // the pipe and cause it to wake up and exit). But acquiring the GIL as
838 // below will redirect Python's stdio to use this same handle. If we
839 // close the handle while Python is still using it, bad things will
843 ScriptInterpreterPython::Locker::AcquireLock |
844 ScriptInterpreterPython::Locker::InitSession |
845 (options.GetSetLLDBGlobals()
846 ? ScriptInterpreterPython::Locker::InitGlobals
848 ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
849 ScriptInterpreterPython::Locker::FreeAcquiredLock |
850 ScriptInterpreterPython::Locker::TearDownSession,
851 in_file, out_file, err_file);
853 // Find the correct script interpreter dictionary in the main module.
854 PythonDictionary &session_dict = GetSessionDictionary();
855 if (session_dict.IsValid()) {
856 if (GetEmbeddedInterpreterModuleObjects()) {
857 if (PyCallable_Check(m_run_one_line_function.get())) {
860 Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
861 if (pargs.IsValid()) {
862 PythonObject return_value(
864 PyObject_CallObject(m_run_one_line_function.get(),
866 if (return_value.IsValid())
868 else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
877 // Flush our output and error file handles
879 if (out_file != err_file)
883 if (join_read_thread) {
884 // Close the write end of the pipe since we are done with our one line
885 // script. This should cause the read thread that output_comm is using to
887 output_file_sp->GetFile().Close();
888 // The close above should cause this thread to exit when it gets to the
889 // end of file, so let it get all its data
890 output_comm.JoinReadThread();
891 // Now we can close the read end of the pipe
892 output_comm.Disconnect();
898 // The one-liner failed. Append the error message.
900 result->AppendErrorWithFormat(
901 "python failed attempting to evaluate '%s'\n", command_str.c_str());
907 result->AppendError("empty command passed to python\n");
911 class IOHandlerPythonInterpreter : public IOHandler {
913 IOHandlerPythonInterpreter(Debugger &debugger,
914 ScriptInterpreterPython *python)
915 : IOHandler(debugger, IOHandler::Type::PythonInterpreter),
918 ~IOHandlerPythonInterpreter() override {}
920 ConstString GetControlSequence(char ch) override {
922 return ConstString("quit()\n");
923 return ConstString();
926 void Run() override {
928 int stdin_fd = GetInputFD();
930 Terminal terminal(stdin_fd);
931 TerminalState terminal_state;
932 const bool is_a_tty = terminal.IsATerminal();
935 terminal_state.Save(stdin_fd, false);
936 terminal.SetCanonical(false);
937 terminal.SetEcho(true);
940 ScriptInterpreterPython::Locker locker(
941 m_python, ScriptInterpreterPython::Locker::AcquireLock |
942 ScriptInterpreterPython::Locker::InitSession |
943 ScriptInterpreterPython::Locker::InitGlobals,
944 ScriptInterpreterPython::Locker::FreeAcquiredLock |
945 ScriptInterpreterPython::Locker::TearDownSession);
947 // The following call drops into the embedded interpreter loop and
948 // stays there until the user chooses to exit from the Python
949 // interpreter. This embedded interpreter will, as any Python code that
950 // performs I/O, unlock the GIL before a system call that can hang, and
951 // lock it when the syscall has returned.
953 // We need to surround the call to the embedded interpreter with calls
954 // to PyGILState_Ensure and PyGILState_Release (using the Locker
955 // above). This is because Python has a global lock which must be held
956 // whenever we want to touch any Python objects. Otherwise, if the user
957 // calls Python code, the interpreter state will be off, and things
958 // could hang (it's happened before).
960 StreamString run_string;
961 run_string.Printf("run_python_interpreter (%s)",
962 m_python->GetDictionaryName());
963 PyRun_SimpleString(run_string.GetData());
966 terminal_state.Restore();
972 void Cancel() override {}
974 bool Interrupt() override { return m_python->Interrupt(); }
976 void GotEOF() override {}
979 ScriptInterpreterPython *m_python;
982 void ScriptInterpreterPython::ExecuteInterpreterLoop() {
983 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
984 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
986 Debugger &debugger = GetCommandInterpreter().GetDebugger();
988 // At the moment, the only time the debugger does not have an input file
989 // handle is when this is called directly from Python, in which case it is
990 // both dangerous and unnecessary (not to mention confusing) to try to embed
991 // a running interpreter loop inside the already running Python interpreter
992 // loop, so we won't do it.
994 if (!debugger.GetInputFile()->GetFile().IsValid())
997 IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
999 debugger.PushIOHandler(io_handler_sp);
1003 bool ScriptInterpreterPython::Interrupt() {
1004 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
1006 if (IsExecutingPython()) {
1007 PyThreadState *state = PyThreadState_GET();
1009 state = GetThreadState();
1011 long tid = state->thread_id;
1012 PyThreadState_Swap(state);
1013 int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
1015 log->Printf("ScriptInterpreterPython::Interrupt() sending "
1016 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
1022 log->Printf("ScriptInterpreterPython::Interrupt() python code not running, "
1026 bool ScriptInterpreterPython::ExecuteOneLineWithReturn(
1027 llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
1028 void *ret_value, const ExecuteScriptOptions &options) {
1030 Locker locker(this, ScriptInterpreterPython::Locker::AcquireLock |
1031 ScriptInterpreterPython::Locker::InitSession |
1032 (options.GetSetLLDBGlobals()
1033 ? ScriptInterpreterPython::Locker::InitGlobals
1036 ScriptInterpreterPython::Locker::FreeAcquiredLock |
1037 ScriptInterpreterPython::Locker::TearDownSession);
1039 PythonObject py_return;
1040 PythonObject &main_module = GetMainModule();
1041 PythonDictionary globals(PyRefType::Borrowed,
1042 PyModule_GetDict(main_module.get()));
1043 PythonObject py_error;
1044 bool ret_success = false;
1047 PythonDictionary locals = GetSessionDictionary();
1049 if (!locals.IsValid()) {
1052 PyObject_GetAttrString(globals.get(), m_dictionary_name.c_str()));
1055 if (!locals.IsValid())
1058 py_error.Reset(PyRefType::Borrowed, PyErr_Occurred());
1059 if (py_error.IsValid())
1062 std::string as_string = in_string.str();
1063 { // scope for PythonInputReaderManager
1064 // PythonInputReaderManager py_input(options.GetEnableIO() ? this : NULL);
1065 py_return.Reset(PyRefType::Owned,
1066 PyRun_String(as_string.c_str(), Py_eval_input,
1067 globals.get(), locals.get()));
1068 if (!py_return.IsValid()) {
1069 py_error.Reset(PyRefType::Borrowed, PyErr_Occurred());
1070 if (py_error.IsValid())
1073 py_return.Reset(PyRefType::Owned,
1074 PyRun_String(as_string.c_str(), Py_single_input,
1075 globals.get(), locals.get()));
1079 if (py_return.IsValid()) {
1080 switch (return_type) {
1081 case eScriptReturnTypeCharPtr: // "char *"
1083 const char format[3] = "s#";
1084 success = PyArg_Parse(py_return.get(), format, (char **)ret_value);
1087 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
1090 const char format[3] = "z";
1091 success = PyArg_Parse(py_return.get(), format, (char **)ret_value);
1094 case eScriptReturnTypeBool: {
1095 const char format[2] = "b";
1096 success = PyArg_Parse(py_return.get(), format, (bool *)ret_value);
1099 case eScriptReturnTypeShortInt: {
1100 const char format[2] = "h";
1101 success = PyArg_Parse(py_return.get(), format, (short *)ret_value);
1104 case eScriptReturnTypeShortIntUnsigned: {
1105 const char format[2] = "H";
1107 PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
1110 case eScriptReturnTypeInt: {
1111 const char format[2] = "i";
1112 success = PyArg_Parse(py_return.get(), format, (int *)ret_value);
1115 case eScriptReturnTypeIntUnsigned: {
1116 const char format[2] = "I";
1117 success = PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
1120 case eScriptReturnTypeLongInt: {
1121 const char format[2] = "l";
1122 success = PyArg_Parse(py_return.get(), format, (long *)ret_value);
1125 case eScriptReturnTypeLongIntUnsigned: {
1126 const char format[2] = "k";
1128 PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
1131 case eScriptReturnTypeLongLong: {
1132 const char format[2] = "L";
1133 success = PyArg_Parse(py_return.get(), format, (long long *)ret_value);
1136 case eScriptReturnTypeLongLongUnsigned: {
1137 const char format[2] = "K";
1139 PyArg_Parse(py_return.get(), format, (unsigned long long *)ret_value);
1142 case eScriptReturnTypeFloat: {
1143 const char format[2] = "f";
1144 success = PyArg_Parse(py_return.get(), format, (float *)ret_value);
1147 case eScriptReturnTypeDouble: {
1148 const char format[2] = "d";
1149 success = PyArg_Parse(py_return.get(), format, (double *)ret_value);
1152 case eScriptReturnTypeChar: {
1153 const char format[2] = "c";
1154 success = PyArg_Parse(py_return.get(), format, (char *)ret_value);
1157 case eScriptReturnTypeOpaqueObject: {
1159 PyObject *saved_value = py_return.get();
1160 Py_XINCREF(saved_value);
1161 *((PyObject **)ret_value) = saved_value;
1166 ret_success = success;
1169 py_error.Reset(PyRefType::Borrowed, PyErr_Occurred());
1170 if (py_error.IsValid()) {
1171 ret_success = false;
1172 if (options.GetMaskoutErrors()) {
1173 if (PyErr_GivenExceptionMatches(py_error.get(), PyExc_SyntaxError))
1182 Status ScriptInterpreterPython::ExecuteMultipleLines(
1183 const char *in_string, const ExecuteScriptOptions &options) {
1186 Locker locker(this, ScriptInterpreterPython::Locker::AcquireLock |
1187 ScriptInterpreterPython::Locker::InitSession |
1188 (options.GetSetLLDBGlobals()
1189 ? ScriptInterpreterPython::Locker::InitGlobals
1192 ScriptInterpreterPython::Locker::FreeAcquiredLock |
1193 ScriptInterpreterPython::Locker::TearDownSession);
1195 PythonObject return_value;
1196 PythonObject &main_module = GetMainModule();
1197 PythonDictionary globals(PyRefType::Borrowed,
1198 PyModule_GetDict(main_module.get()));
1199 PythonObject py_error;
1201 PythonDictionary locals = GetSessionDictionary();
1203 if (!locals.IsValid())
1206 PyObject_GetAttrString(globals.get(), m_dictionary_name.c_str()));
1208 if (!locals.IsValid())
1211 py_error.Reset(PyRefType::Borrowed, PyErr_Occurred());
1212 if (py_error.IsValid())
1215 if (in_string != nullptr) {
1216 PythonObject code_object;
1217 code_object.Reset(PyRefType::Owned,
1218 Py_CompileString(in_string, "temp.py", Py_file_input));
1220 if (code_object.IsValid()) {
1221 // In Python 2.x, PyEval_EvalCode takes a PyCodeObject, but in Python 3.x, it
1222 // takes a PyObject. They are convertible (hence the function
1223 // PyCode_Check(PyObject*), so we have to do the cast for Python 2.x
1224 #if PY_MAJOR_VERSION >= 3
1225 PyObject *py_code_obj = code_object.get();
1227 PyCodeObject *py_code_obj =
1228 reinterpret_cast<PyCodeObject *>(code_object.get());
1232 PyEval_EvalCode(py_code_obj, globals.get(), locals.get()));
1236 PythonExceptionState exception_state(!options.GetMaskoutErrors());
1237 if (exception_state.IsError())
1238 error.SetErrorString(exception_state.Format().c_str());
1243 void ScriptInterpreterPython::CollectDataForBreakpointCommandCallback(
1244 std::vector<BreakpointOptions *> &bp_options_vec,
1245 CommandReturnObject &result) {
1246 m_active_io_handler = eIOHandlerBreakpoint;
1247 m_interpreter.GetPythonCommandsFromIOHandler(" ", *this, true,
1251 void ScriptInterpreterPython::CollectDataForWatchpointCommandCallback(
1252 WatchpointOptions *wp_options, CommandReturnObject &result) {
1253 m_active_io_handler = eIOHandlerWatchpoint;
1254 m_interpreter.GetPythonCommandsFromIOHandler(" ", *this, true, wp_options);
1257 void ScriptInterpreterPython::SetBreakpointCommandCallbackFunction(
1258 BreakpointOptions *bp_options, const char *function_name) {
1259 // For now just cons up a oneliner that calls the provided function.
1260 std::string oneliner("return ");
1261 oneliner += function_name;
1262 oneliner += "(frame, bp_loc, internal_dict)";
1263 m_interpreter.GetScriptInterpreter()->SetBreakpointCommandCallback(
1264 bp_options, oneliner.c_str());
1267 Status ScriptInterpreterPython::SetBreakpointCommandCallback(
1268 BreakpointOptions *bp_options,
1269 std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
1271 error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1272 cmd_data_up->script_source);
1277 std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1278 bp_options->SetCallback(ScriptInterpreterPython::BreakpointCallbackFunction,
1283 // Set a Python one-liner as the callback for the breakpoint.
1284 Status ScriptInterpreterPython::SetBreakpointCommandCallback(
1285 BreakpointOptions *bp_options, const char *command_body_text) {
1286 auto data_ap = llvm::make_unique<CommandDataPython>();
1288 // Split the command_body_text into lines, and pass that to
1289 // GenerateBreakpointCommandCallbackData. That will wrap the body in an
1290 // auto-generated function, and return the function name in script_source.
1291 // That is what the callback will actually invoke.
1293 data_ap->user_source.SplitIntoLines(command_body_text);
1294 Status error = GenerateBreakpointCommandCallbackData(data_ap->user_source,
1295 data_ap->script_source);
1296 if (error.Success()) {
1298 std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_ap));
1299 bp_options->SetCallback(ScriptInterpreterPython::BreakpointCallbackFunction,
1306 // Set a Python one-liner as the callback for the watchpoint.
1307 void ScriptInterpreterPython::SetWatchpointCommandCallback(
1308 WatchpointOptions *wp_options, const char *oneliner) {
1309 auto data_ap = llvm::make_unique<WatchpointOptions::CommandData>();
1311 // It's necessary to set both user_source and script_source to the oneliner.
1312 // The former is used to generate callback description (as in watchpoint
1313 // command list) while the latter is used for Python to interpret during the
1316 data_ap->user_source.AppendString(oneliner);
1317 data_ap->script_source.assign(oneliner);
1319 if (GenerateWatchpointCommandCallbackData(data_ap->user_source,
1320 data_ap->script_source)) {
1322 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_ap));
1323 wp_options->SetCallback(ScriptInterpreterPython::WatchpointCallbackFunction,
1330 Status ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter(
1331 StringList &function_def) {
1332 // Convert StringList to one long, newline delimited, const char *.
1333 std::string function_def_string(function_def.CopyList());
1335 Status error = ExecuteMultipleLines(
1336 function_def_string.c_str(),
1337 ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false));
1341 Status ScriptInterpreterPython::GenerateFunction(const char *signature,
1342 const StringList &input) {
1344 int num_lines = input.GetSize();
1345 if (num_lines == 0) {
1346 error.SetErrorString("No input data.");
1350 if (!signature || *signature == 0) {
1351 error.SetErrorString("No output function name.");
1356 StringList auto_generated_function;
1357 auto_generated_function.AppendString(signature);
1358 auto_generated_function.AppendString(
1359 " global_dict = globals()"); // Grab the global dictionary
1360 auto_generated_function.AppendString(
1361 " new_keys = internal_dict.keys()"); // Make a list of keys in the
1363 auto_generated_function.AppendString(
1364 " old_keys = global_dict.keys()"); // Save list of keys in global dict
1365 auto_generated_function.AppendString(
1366 " global_dict.update (internal_dict)"); // Add the session dictionary
1368 // global dictionary.
1370 // Wrap everything up inside the function, increasing the indentation.
1372 auto_generated_function.AppendString(" if True:");
1373 for (int i = 0; i < num_lines; ++i) {
1375 sstr.Printf(" %s", input.GetStringAtIndex(i));
1376 auto_generated_function.AppendString(sstr.GetData());
1378 auto_generated_function.AppendString(
1379 " for key in new_keys:"); // Iterate over all the keys from session
1381 auto_generated_function.AppendString(
1382 " internal_dict[key] = global_dict[key]"); // Update session dict
1384 auto_generated_function.AppendString(
1385 " if key not in old_keys:"); // If key was not originally in
1387 auto_generated_function.AppendString(
1388 " del global_dict[key]"); // ...then remove key/value from
1391 // Verify that the results are valid Python.
1393 error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
1398 bool ScriptInterpreterPython::GenerateTypeScriptFunction(
1399 StringList &user_input, std::string &output, const void *name_token) {
1400 static uint32_t num_created_functions = 0;
1401 user_input.RemoveBlankLines();
1404 // Check to see if we have any data; if not, just return.
1405 if (user_input.GetSize() == 0)
1408 // Take what the user wrote, wrap it all up inside one big auto-generated
1409 // Python function, passing in the ValueObject as parameter to the function.
1411 std::string auto_generated_function_name(
1412 GenerateUniqueName("lldb_autogen_python_type_print_func",
1413 num_created_functions, name_token));
1414 sstr.Printf("def %s (valobj, internal_dict):",
1415 auto_generated_function_name.c_str());
1417 if (!GenerateFunction(sstr.GetData(), user_input).Success())
1420 // Store the name of the auto-generated function to be called.
1421 output.assign(auto_generated_function_name);
1425 bool ScriptInterpreterPython::GenerateScriptAliasFunction(
1426 StringList &user_input, std::string &output) {
1427 static uint32_t num_created_functions = 0;
1428 user_input.RemoveBlankLines();
1431 // Check to see if we have any data; if not, just return.
1432 if (user_input.GetSize() == 0)
1435 std::string auto_generated_function_name(GenerateUniqueName(
1436 "lldb_autogen_python_cmd_alias_func", num_created_functions));
1438 sstr.Printf("def %s (debugger, args, result, internal_dict):",
1439 auto_generated_function_name.c_str());
1441 if (!GenerateFunction(sstr.GetData(), user_input).Success())
1444 // Store the name of the auto-generated function to be called.
1445 output.assign(auto_generated_function_name);
1449 bool ScriptInterpreterPython::GenerateTypeSynthClass(StringList &user_input,
1450 std::string &output,
1451 const void *name_token) {
1452 static uint32_t num_created_classes = 0;
1453 user_input.RemoveBlankLines();
1454 int num_lines = user_input.GetSize();
1457 // Check to see if we have any data; if not, just return.
1458 if (user_input.GetSize() == 0)
1461 // Wrap all user input into a Python class
1463 std::string auto_generated_class_name(GenerateUniqueName(
1464 "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1466 StringList auto_generated_class;
1468 // Create the function name & definition string.
1470 sstr.Printf("class %s:", auto_generated_class_name.c_str());
1471 auto_generated_class.AppendString(sstr.GetString());
1473 // Wrap everything up inside the class, increasing the indentation. we don't
1474 // need to play any fancy indentation tricks here because there is no
1475 // surrounding code whose indentation we need to honor
1476 for (int i = 0; i < num_lines; ++i) {
1478 sstr.Printf(" %s", user_input.GetStringAtIndex(i));
1479 auto_generated_class.AppendString(sstr.GetString());
1482 // Verify that the results are valid Python. (even though the method is
1483 // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1484 // (TODO: rename that method to ExportDefinitionToInterpreter)
1485 if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
1488 // Store the name of the auto-generated class
1490 output.assign(auto_generated_class_name);
1494 StructuredData::GenericSP ScriptInterpreterPython::OSPlugin_CreatePluginObject(
1495 const char *class_name, lldb::ProcessSP process_sp) {
1496 if (class_name == nullptr || class_name[0] == '\0')
1497 return StructuredData::GenericSP();
1500 return StructuredData::GenericSP();
1505 Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
1507 ret_val = g_swig_create_os_plugin(class_name, m_dictionary_name.c_str(),
1511 return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
1514 StructuredData::DictionarySP ScriptInterpreterPython::OSPlugin_RegisterInfo(
1515 StructuredData::ObjectSP os_plugin_object_sp) {
1516 Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1518 static char callee_name[] = "get_register_info";
1520 if (!os_plugin_object_sp)
1521 return StructuredData::DictionarySP();
1523 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1527 PythonObject implementor(PyRefType::Borrowed,
1528 (PyObject *)generic->GetValue());
1530 if (!implementor.IsAllocated())
1531 return StructuredData::DictionarySP();
1533 PythonObject pmeth(PyRefType::Owned,
1534 PyObject_GetAttrString(implementor.get(), callee_name));
1536 if (PyErr_Occurred())
1539 if (!pmeth.IsAllocated())
1540 return StructuredData::DictionarySP();
1542 if (PyCallable_Check(pmeth.get()) == 0) {
1543 if (PyErr_Occurred())
1546 return StructuredData::DictionarySP();
1549 if (PyErr_Occurred())
1552 // right now we know this function exists and is callable..
1553 PythonObject py_return(
1555 PyObject_CallMethod(implementor.get(), callee_name, nullptr));
1557 // if it fails, print the error but otherwise go on
1558 if (PyErr_Occurred()) {
1562 if (py_return.get()) {
1563 PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1564 return result_dict.CreateStructuredDictionary();
1566 return StructuredData::DictionarySP();
1569 StructuredData::ArraySP ScriptInterpreterPython::OSPlugin_ThreadsInfo(
1570 StructuredData::ObjectSP os_plugin_object_sp) {
1571 Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1573 static char callee_name[] = "get_thread_info";
1575 if (!os_plugin_object_sp)
1576 return StructuredData::ArraySP();
1578 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1582 PythonObject implementor(PyRefType::Borrowed,
1583 (PyObject *)generic->GetValue());
1585 if (!implementor.IsAllocated())
1586 return StructuredData::ArraySP();
1588 PythonObject pmeth(PyRefType::Owned,
1589 PyObject_GetAttrString(implementor.get(), callee_name));
1591 if (PyErr_Occurred())
1594 if (!pmeth.IsAllocated())
1595 return StructuredData::ArraySP();
1597 if (PyCallable_Check(pmeth.get()) == 0) {
1598 if (PyErr_Occurred())
1601 return StructuredData::ArraySP();
1604 if (PyErr_Occurred())
1607 // right now we know this function exists and is callable..
1608 PythonObject py_return(
1610 PyObject_CallMethod(implementor.get(), callee_name, nullptr));
1612 // if it fails, print the error but otherwise go on
1613 if (PyErr_Occurred()) {
1618 if (py_return.get()) {
1619 PythonList result_list(PyRefType::Borrowed, py_return.get());
1620 return result_list.CreateStructuredArray();
1622 return StructuredData::ArraySP();
1625 // GetPythonValueFormatString provides a system independent type safe way to
1626 // convert a variable's type into a python value format. Python value formats
1627 // are defined in terms of builtin C types and could change from system to as
1628 // the underlying typedef for uint* types, size_t, off_t and other values
1631 template <typename T> const char *GetPythonValueFormatString(T t);
1632 template <> const char *GetPythonValueFormatString(char *) { return "s"; }
1633 template <> const char *GetPythonValueFormatString(char) { return "b"; }
1634 template <> const char *GetPythonValueFormatString(unsigned char) {
1637 template <> const char *GetPythonValueFormatString(short) { return "h"; }
1638 template <> const char *GetPythonValueFormatString(unsigned short) {
1641 template <> const char *GetPythonValueFormatString(int) { return "i"; }
1642 template <> const char *GetPythonValueFormatString(unsigned int) { return "I"; }
1643 template <> const char *GetPythonValueFormatString(long) { return "l"; }
1644 template <> const char *GetPythonValueFormatString(unsigned long) {
1647 template <> const char *GetPythonValueFormatString(long long) { return "L"; }
1648 template <> const char *GetPythonValueFormatString(unsigned long long) {
1651 template <> const char *GetPythonValueFormatString(float t) { return "f"; }
1652 template <> const char *GetPythonValueFormatString(double t) { return "d"; }
1654 StructuredData::StringSP ScriptInterpreterPython::OSPlugin_RegisterContextData(
1655 StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
1656 Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1658 static char callee_name[] = "get_register_data";
1659 static char *param_format =
1660 const_cast<char *>(GetPythonValueFormatString(tid));
1662 if (!os_plugin_object_sp)
1663 return StructuredData::StringSP();
1665 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1668 PythonObject implementor(PyRefType::Borrowed,
1669 (PyObject *)generic->GetValue());
1671 if (!implementor.IsAllocated())
1672 return StructuredData::StringSP();
1674 PythonObject pmeth(PyRefType::Owned,
1675 PyObject_GetAttrString(implementor.get(), callee_name));
1677 if (PyErr_Occurred())
1680 if (!pmeth.IsAllocated())
1681 return StructuredData::StringSP();
1683 if (PyCallable_Check(pmeth.get()) == 0) {
1684 if (PyErr_Occurred())
1686 return StructuredData::StringSP();
1689 if (PyErr_Occurred())
1692 // right now we know this function exists and is callable..
1693 PythonObject py_return(
1695 PyObject_CallMethod(implementor.get(), callee_name, param_format, tid));
1697 // if it fails, print the error but otherwise go on
1698 if (PyErr_Occurred()) {
1703 if (py_return.get()) {
1704 PythonBytes result(PyRefType::Borrowed, py_return.get());
1705 return result.CreateStructuredString();
1707 return StructuredData::StringSP();
1710 StructuredData::DictionarySP ScriptInterpreterPython::OSPlugin_CreateThread(
1711 StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
1712 lldb::addr_t context) {
1713 Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1715 static char callee_name[] = "create_thread";
1716 std::string param_format;
1717 param_format += GetPythonValueFormatString(tid);
1718 param_format += GetPythonValueFormatString(context);
1720 if (!os_plugin_object_sp)
1721 return StructuredData::DictionarySP();
1723 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1727 PythonObject implementor(PyRefType::Borrowed,
1728 (PyObject *)generic->GetValue());
1730 if (!implementor.IsAllocated())
1731 return StructuredData::DictionarySP();
1733 PythonObject pmeth(PyRefType::Owned,
1734 PyObject_GetAttrString(implementor.get(), callee_name));
1736 if (PyErr_Occurred())
1739 if (!pmeth.IsAllocated())
1740 return StructuredData::DictionarySP();
1742 if (PyCallable_Check(pmeth.get()) == 0) {
1743 if (PyErr_Occurred())
1745 return StructuredData::DictionarySP();
1748 if (PyErr_Occurred())
1751 // right now we know this function exists and is callable..
1752 PythonObject py_return(PyRefType::Owned,
1753 PyObject_CallMethod(implementor.get(), callee_name,
1754 ¶m_format[0], tid, context));
1756 // if it fails, print the error but otherwise go on
1757 if (PyErr_Occurred()) {
1762 if (py_return.get()) {
1763 PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1764 return result_dict.CreateStructuredDictionary();
1766 return StructuredData::DictionarySP();
1769 StructuredData::ObjectSP ScriptInterpreterPython::CreateScriptedThreadPlan(
1770 const char *class_name, lldb::ThreadPlanSP thread_plan_sp) {
1771 if (class_name == nullptr || class_name[0] == '\0')
1772 return StructuredData::ObjectSP();
1774 if (!thread_plan_sp.get())
1775 return StructuredData::ObjectSP();
1777 Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
1778 ScriptInterpreter *script_interpreter =
1779 debugger.GetCommandInterpreter().GetScriptInterpreter();
1780 ScriptInterpreterPython *python_interpreter =
1781 static_cast<ScriptInterpreterPython *>(script_interpreter);
1783 if (!script_interpreter)
1784 return StructuredData::ObjectSP();
1789 Locker py_lock(this,
1790 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1792 ret_val = g_swig_thread_plan_script(
1793 class_name, python_interpreter->m_dictionary_name.c_str(),
1797 return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
1800 bool ScriptInterpreterPython::ScriptedThreadPlanExplainsStop(
1801 StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1802 bool explains_stop = true;
1803 StructuredData::Generic *generic = nullptr;
1805 generic = implementor_sp->GetAsGeneric();
1807 Locker py_lock(this,
1808 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1809 explains_stop = g_swig_call_thread_plan(
1810 generic->GetValue(), "explains_stop", event, script_error);
1814 return explains_stop;
1817 bool ScriptInterpreterPython::ScriptedThreadPlanShouldStop(
1818 StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1819 bool should_stop = true;
1820 StructuredData::Generic *generic = nullptr;
1822 generic = implementor_sp->GetAsGeneric();
1824 Locker py_lock(this,
1825 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1826 should_stop = g_swig_call_thread_plan(generic->GetValue(), "should_stop",
1827 event, script_error);
1834 bool ScriptInterpreterPython::ScriptedThreadPlanIsStale(
1835 StructuredData::ObjectSP implementor_sp, bool &script_error) {
1836 bool is_stale = true;
1837 StructuredData::Generic *generic = nullptr;
1839 generic = implementor_sp->GetAsGeneric();
1841 Locker py_lock(this,
1842 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1843 is_stale = g_swig_call_thread_plan(generic->GetValue(), "is_stale", nullptr,
1851 lldb::StateType ScriptInterpreterPython::ScriptedThreadPlanGetRunState(
1852 StructuredData::ObjectSP implementor_sp, bool &script_error) {
1853 bool should_step = false;
1854 StructuredData::Generic *generic = nullptr;
1856 generic = implementor_sp->GetAsGeneric();
1858 Locker py_lock(this,
1859 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1860 should_step = g_swig_call_thread_plan(generic->GetValue(), "should_step",
1861 NULL, script_error);
1866 return lldb::eStateStepping;
1868 return lldb::eStateRunning;
1871 StructuredData::ObjectSP
1872 ScriptInterpreterPython::LoadPluginModule(const FileSpec &file_spec,
1873 lldb_private::Status &error) {
1874 if (!file_spec.Exists()) {
1875 error.SetErrorString("no such file");
1876 return StructuredData::ObjectSP();
1879 StructuredData::ObjectSP module_sp;
1881 if (LoadScriptingModule(file_spec.GetPath().c_str(), true, true, error,
1885 return StructuredData::ObjectSP();
1888 StructuredData::DictionarySP ScriptInterpreterPython::GetDynamicSettings(
1889 StructuredData::ObjectSP plugin_module_sp, Target *target,
1890 const char *setting_name, lldb_private::Status &error) {
1891 if (!plugin_module_sp || !target || !setting_name || !setting_name[0] ||
1893 return StructuredData::DictionarySP();
1894 StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
1896 return StructuredData::DictionarySP();
1898 PythonObject reply_pyobj;
1899 Locker py_lock(this,
1900 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1901 TargetSP target_sp(target->shared_from_this());
1902 reply_pyobj.Reset(PyRefType::Owned,
1903 (PyObject *)g_swig_plugin_get(generic->GetValue(),
1904 setting_name, target_sp));
1906 PythonDictionary py_dict(PyRefType::Borrowed, reply_pyobj.get());
1907 return py_dict.CreateStructuredDictionary();
1910 StructuredData::ObjectSP
1911 ScriptInterpreterPython::CreateSyntheticScriptedProvider(
1912 const char *class_name, lldb::ValueObjectSP valobj) {
1913 if (class_name == nullptr || class_name[0] == '\0')
1914 return StructuredData::ObjectSP();
1917 return StructuredData::ObjectSP();
1919 ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
1920 Target *target = exe_ctx.GetTargetPtr();
1923 return StructuredData::ObjectSP();
1925 Debugger &debugger = target->GetDebugger();
1926 ScriptInterpreter *script_interpreter =
1927 debugger.GetCommandInterpreter().GetScriptInterpreter();
1928 ScriptInterpreterPython *python_interpreter =
1929 (ScriptInterpreterPython *)script_interpreter;
1931 if (!script_interpreter)
1932 return StructuredData::ObjectSP();
1934 void *ret_val = nullptr;
1937 Locker py_lock(this,
1938 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1939 ret_val = g_swig_synthetic_script(
1940 class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
1943 return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
1946 StructuredData::GenericSP
1947 ScriptInterpreterPython::CreateScriptCommandObject(const char *class_name) {
1948 DebuggerSP debugger_sp(
1949 GetCommandInterpreter().GetDebugger().shared_from_this());
1951 if (class_name == nullptr || class_name[0] == '\0')
1952 return StructuredData::GenericSP();
1954 if (!debugger_sp.get())
1955 return StructuredData::GenericSP();
1960 Locker py_lock(this,
1961 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1963 g_swig_create_cmd(class_name, m_dictionary_name.c_str(), debugger_sp);
1966 return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
1969 bool ScriptInterpreterPython::GenerateTypeScriptFunction(
1970 const char *oneliner, std::string &output, const void *name_token) {
1972 input.SplitIntoLines(oneliner, strlen(oneliner));
1973 return GenerateTypeScriptFunction(input, output, name_token);
1976 bool ScriptInterpreterPython::GenerateTypeSynthClass(const char *oneliner,
1977 std::string &output,
1978 const void *name_token) {
1980 input.SplitIntoLines(oneliner, strlen(oneliner));
1981 return GenerateTypeSynthClass(input, output, name_token);
1984 Status ScriptInterpreterPython::GenerateBreakpointCommandCallbackData(
1985 StringList &user_input, std::string &output) {
1986 static uint32_t num_created_functions = 0;
1987 user_input.RemoveBlankLines();
1990 if (user_input.GetSize() == 0) {
1991 error.SetErrorString("No input data.");
1995 std::string auto_generated_function_name(GenerateUniqueName(
1996 "lldb_autogen_python_bp_callback_func_", num_created_functions));
1997 sstr.Printf("def %s (frame, bp_loc, internal_dict):",
1998 auto_generated_function_name.c_str());
2000 error = GenerateFunction(sstr.GetData(), user_input);
2001 if (!error.Success())
2004 // Store the name of the auto-generated function to be called.
2005 output.assign(auto_generated_function_name);
2009 bool ScriptInterpreterPython::GenerateWatchpointCommandCallbackData(
2010 StringList &user_input, std::string &output) {
2011 static uint32_t num_created_functions = 0;
2012 user_input.RemoveBlankLines();
2015 if (user_input.GetSize() == 0)
2018 std::string auto_generated_function_name(GenerateUniqueName(
2019 "lldb_autogen_python_wp_callback_func_", num_created_functions));
2020 sstr.Printf("def %s (frame, wp, internal_dict):",
2021 auto_generated_function_name.c_str());
2023 if (!GenerateFunction(sstr.GetData(), user_input).Success())
2026 // Store the name of the auto-generated function to be called.
2027 output.assign(auto_generated_function_name);
2031 bool ScriptInterpreterPython::GetScriptedSummary(
2032 const char *python_function_name, lldb::ValueObjectSP valobj,
2033 StructuredData::ObjectSP &callee_wrapper_sp,
2034 const TypeSummaryOptions &options, std::string &retval) {
2036 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2037 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
2039 if (!valobj.get()) {
2040 retval.assign("<no object>");
2044 void *old_callee = nullptr;
2045 StructuredData::Generic *generic = nullptr;
2046 if (callee_wrapper_sp) {
2047 generic = callee_wrapper_sp->GetAsGeneric();
2049 old_callee = generic->GetValue();
2051 void *new_callee = old_callee;
2054 if (python_function_name && *python_function_name) {
2056 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
2059 TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
2061 static Timer::Category func_cat("g_swig_typescript_callback");
2062 Timer scoped_timer(func_cat, "g_swig_typescript_callback");
2063 ret_val = g_swig_typescript_callback(
2064 python_function_name, GetSessionDictionary().get(), valobj,
2065 &new_callee, options_sp, retval);
2069 retval.assign("<no function name>");
2073 if (new_callee && old_callee != new_callee)
2074 callee_wrapper_sp.reset(new StructuredPythonObject(new_callee));
2079 void ScriptInterpreterPython::Clear() {
2080 // Release any global variables that might have strong references to
2081 // LLDB objects when clearing the python script interpreter.
2082 Locker locker(this, ScriptInterpreterPython::Locker::AcquireLock,
2083 ScriptInterpreterPython::Locker::FreeAcquiredLock);
2085 // This may be called as part of Py_Finalize. In that case the modules are
2086 // destroyed in random order and we can't guarantee that we can access these.
2087 if (Py_IsInitialized())
2088 PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
2089 "= None; lldb.thread = None; lldb.frame = None");
2092 bool ScriptInterpreterPython::BreakpointCallbackFunction(
2093 void *baton, StoppointCallbackContext *context, user_id_t break_id,
2094 user_id_t break_loc_id) {
2095 CommandDataPython *bp_option_data = (CommandDataPython *)baton;
2096 const char *python_function_name = bp_option_data->script_source.c_str();
2101 ExecutionContext exe_ctx(context->exe_ctx_ref);
2102 Target *target = exe_ctx.GetTargetPtr();
2107 Debugger &debugger = target->GetDebugger();
2108 ScriptInterpreter *script_interpreter =
2109 debugger.GetCommandInterpreter().GetScriptInterpreter();
2110 ScriptInterpreterPython *python_interpreter =
2111 (ScriptInterpreterPython *)script_interpreter;
2113 if (!script_interpreter)
2116 if (python_function_name && python_function_name[0]) {
2117 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2118 BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2119 if (breakpoint_sp) {
2120 const BreakpointLocationSP bp_loc_sp(
2121 breakpoint_sp->FindLocationByID(break_loc_id));
2123 if (stop_frame_sp && bp_loc_sp) {
2124 bool ret_val = true;
2126 Locker py_lock(python_interpreter, Locker::AcquireLock |
2127 Locker::InitSession |
2129 ret_val = g_swig_breakpoint_callback(
2130 python_function_name,
2131 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2138 // We currently always true so we stop in case anything goes wrong when
2139 // trying to call the script function
2143 bool ScriptInterpreterPython::WatchpointCallbackFunction(
2144 void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2145 WatchpointOptions::CommandData *wp_option_data =
2146 (WatchpointOptions::CommandData *)baton;
2147 const char *python_function_name = wp_option_data->script_source.c_str();
2152 ExecutionContext exe_ctx(context->exe_ctx_ref);
2153 Target *target = exe_ctx.GetTargetPtr();
2158 Debugger &debugger = target->GetDebugger();
2159 ScriptInterpreter *script_interpreter =
2160 debugger.GetCommandInterpreter().GetScriptInterpreter();
2161 ScriptInterpreterPython *python_interpreter =
2162 (ScriptInterpreterPython *)script_interpreter;
2164 if (!script_interpreter)
2167 if (python_function_name && python_function_name[0]) {
2168 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2169 WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2171 if (stop_frame_sp && wp_sp) {
2172 bool ret_val = true;
2174 Locker py_lock(python_interpreter, Locker::AcquireLock |
2175 Locker::InitSession |
2177 ret_val = g_swig_watchpoint_callback(
2178 python_function_name,
2179 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2186 // We currently always true so we stop in case anything goes wrong when
2187 // trying to call the script function
2191 size_t ScriptInterpreterPython::CalculateNumChildren(
2192 const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
2193 if (!implementor_sp)
2195 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2198 void *implementor = generic->GetValue();
2202 if (!g_swig_calc_children)
2208 Locker py_lock(this,
2209 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2210 ret_val = g_swig_calc_children(implementor, max);
2216 lldb::ValueObjectSP ScriptInterpreterPython::GetChildAtIndex(
2217 const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
2218 if (!implementor_sp)
2219 return lldb::ValueObjectSP();
2221 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2223 return lldb::ValueObjectSP();
2224 void *implementor = generic->GetValue();
2226 return lldb::ValueObjectSP();
2228 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
2229 return lldb::ValueObjectSP();
2231 lldb::ValueObjectSP ret_val;
2234 Locker py_lock(this,
2235 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2236 void *child_ptr = g_swig_get_child_index(implementor, idx);
2237 if (child_ptr != nullptr && child_ptr != Py_None) {
2238 lldb::SBValue *sb_value_ptr =
2239 (lldb::SBValue *)g_swig_cast_to_sbvalue(child_ptr);
2240 if (sb_value_ptr == nullptr)
2241 Py_XDECREF(child_ptr);
2243 ret_val = g_swig_get_valobj_sp_from_sbvalue(sb_value_ptr);
2245 Py_XDECREF(child_ptr);
2252 int ScriptInterpreterPython::GetIndexOfChildWithName(
2253 const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
2254 if (!implementor_sp)
2257 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2260 void *implementor = generic->GetValue();
2264 if (!g_swig_get_index_child)
2267 int ret_val = UINT32_MAX;
2270 Locker py_lock(this,
2271 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2272 ret_val = g_swig_get_index_child(implementor, child_name);
2278 bool ScriptInterpreterPython::UpdateSynthProviderInstance(
2279 const StructuredData::ObjectSP &implementor_sp) {
2280 bool ret_val = false;
2282 if (!implementor_sp)
2285 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2288 void *implementor = generic->GetValue();
2292 if (!g_swig_update_provider)
2296 Locker py_lock(this,
2297 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2298 ret_val = g_swig_update_provider(implementor);
2304 bool ScriptInterpreterPython::MightHaveChildrenSynthProviderInstance(
2305 const StructuredData::ObjectSP &implementor_sp) {
2306 bool ret_val = false;
2308 if (!implementor_sp)
2311 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2314 void *implementor = generic->GetValue();
2318 if (!g_swig_mighthavechildren_provider)
2322 Locker py_lock(this,
2323 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2324 ret_val = g_swig_mighthavechildren_provider(implementor);
2330 lldb::ValueObjectSP ScriptInterpreterPython::GetSyntheticValue(
2331 const StructuredData::ObjectSP &implementor_sp) {
2332 lldb::ValueObjectSP ret_val(nullptr);
2334 if (!implementor_sp)
2337 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2340 void *implementor = generic->GetValue();
2344 if (!g_swig_getvalue_provider || !g_swig_cast_to_sbvalue ||
2345 !g_swig_get_valobj_sp_from_sbvalue)
2349 Locker py_lock(this,
2350 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2351 void *child_ptr = g_swig_getvalue_provider(implementor);
2352 if (child_ptr != nullptr && child_ptr != Py_None) {
2353 lldb::SBValue *sb_value_ptr =
2354 (lldb::SBValue *)g_swig_cast_to_sbvalue(child_ptr);
2355 if (sb_value_ptr == nullptr)
2356 Py_XDECREF(child_ptr);
2358 ret_val = g_swig_get_valobj_sp_from_sbvalue(sb_value_ptr);
2360 Py_XDECREF(child_ptr);
2367 ConstString ScriptInterpreterPython::GetSyntheticTypeName(
2368 const StructuredData::ObjectSP &implementor_sp) {
2369 Locker py_lock(this,
2370 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2372 static char callee_name[] = "get_type_name";
2374 ConstString ret_val;
2375 bool got_string = false;
2378 if (!implementor_sp)
2381 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2384 PythonObject implementor(PyRefType::Borrowed,
2385 (PyObject *)generic->GetValue());
2386 if (!implementor.IsAllocated())
2389 PythonObject pmeth(PyRefType::Owned,
2390 PyObject_GetAttrString(implementor.get(), callee_name));
2392 if (PyErr_Occurred())
2395 if (!pmeth.IsAllocated())
2398 if (PyCallable_Check(pmeth.get()) == 0) {
2399 if (PyErr_Occurred())
2404 if (PyErr_Occurred())
2407 // right now we know this function exists and is callable..
2408 PythonObject py_return(
2410 PyObject_CallMethod(implementor.get(), callee_name, nullptr));
2412 // if it fails, print the error but otherwise go on
2413 if (PyErr_Occurred()) {
2418 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2419 PythonString py_string(PyRefType::Borrowed, py_return.get());
2420 llvm::StringRef return_data(py_string.GetString());
2421 if (!return_data.empty()) {
2422 buffer.assign(return_data.data(), return_data.size());
2428 ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
2433 bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function,
2435 std::string &output,
2439 error.SetErrorString("no process");
2442 if (!impl_function || !impl_function[0]) {
2443 error.SetErrorString("no function to execute");
2446 if (!g_swig_run_script_keyword_process) {
2447 error.SetErrorString("internal helper function missing");
2451 ProcessSP process_sp(process->shared_from_this());
2452 Locker py_lock(this,
2453 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2454 ret_val = g_swig_run_script_keyword_process(
2455 impl_function, m_dictionary_name.c_str(), process_sp, output);
2457 error.SetErrorString("python script evaluation failed");
2462 bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function,
2464 std::string &output,
2468 error.SetErrorString("no thread");
2471 if (!impl_function || !impl_function[0]) {
2472 error.SetErrorString("no function to execute");
2475 if (!g_swig_run_script_keyword_thread) {
2476 error.SetErrorString("internal helper function missing");
2480 ThreadSP thread_sp(thread->shared_from_this());
2481 Locker py_lock(this,
2482 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2483 ret_val = g_swig_run_script_keyword_thread(
2484 impl_function, m_dictionary_name.c_str(), thread_sp, output);
2486 error.SetErrorString("python script evaluation failed");
2491 bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function,
2493 std::string &output,
2497 error.SetErrorString("no thread");
2500 if (!impl_function || !impl_function[0]) {
2501 error.SetErrorString("no function to execute");
2504 if (!g_swig_run_script_keyword_target) {
2505 error.SetErrorString("internal helper function missing");
2509 TargetSP target_sp(target->shared_from_this());
2510 Locker py_lock(this,
2511 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2512 ret_val = g_swig_run_script_keyword_target(
2513 impl_function, m_dictionary_name.c_str(), target_sp, output);
2515 error.SetErrorString("python script evaluation failed");
2520 bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function,
2522 std::string &output,
2526 error.SetErrorString("no frame");
2529 if (!impl_function || !impl_function[0]) {
2530 error.SetErrorString("no function to execute");
2533 if (!g_swig_run_script_keyword_frame) {
2534 error.SetErrorString("internal helper function missing");
2538 StackFrameSP frame_sp(frame->shared_from_this());
2539 Locker py_lock(this,
2540 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2541 ret_val = g_swig_run_script_keyword_frame(
2542 impl_function, m_dictionary_name.c_str(), frame_sp, output);
2544 error.SetErrorString("python script evaluation failed");
2549 bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function,
2551 std::string &output,
2555 error.SetErrorString("no value");
2558 if (!impl_function || !impl_function[0]) {
2559 error.SetErrorString("no function to execute");
2562 if (!g_swig_run_script_keyword_value) {
2563 error.SetErrorString("internal helper function missing");
2567 ValueObjectSP value_sp(value->GetSP());
2568 Locker py_lock(this,
2569 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2570 ret_val = g_swig_run_script_keyword_value(
2571 impl_function, m_dictionary_name.c_str(), value_sp, output);
2573 error.SetErrorString("python script evaluation failed");
2578 uint64_t replace_all(std::string &str, const std::string &oldStr,
2579 const std::string &newStr) {
2581 uint64_t matches = 0;
2582 while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2584 str.replace(pos, oldStr.length(), newStr);
2585 pos += newStr.length();
2590 bool ScriptInterpreterPython::LoadScriptingModule(
2591 const char *pathname, bool can_reload, bool init_session,
2592 lldb_private::Status &error, StructuredData::ObjectSP *module_sp) {
2593 if (!pathname || !pathname[0]) {
2594 error.SetErrorString("invalid pathname");
2598 if (!g_swig_call_module_init) {
2599 error.SetErrorString("internal helper function missing");
2603 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
2606 FileSpec target_file(pathname, true);
2607 std::string basename(target_file.GetFilename().GetCString());
2609 StreamString command_stream;
2611 // Before executing Python code, lock the GIL.
2612 Locker py_lock(this, Locker::AcquireLock |
2613 (init_session ? Locker::InitSession : 0) |
2615 Locker::FreeAcquiredLock |
2616 (init_session ? Locker::TearDownSession : 0));
2617 namespace fs = llvm::sys::fs;
2619 std::error_code ec = status(target_file.GetPath(), st);
2621 if (ec || st.type() == fs::file_type::status_error ||
2622 st.type() == fs::file_type::type_unknown ||
2623 st.type() == fs::file_type::file_not_found) {
2624 // if not a valid file of any sort, check if it might be a filename still
2625 // dot can't be used but / and \ can, and if either is found, reject
2626 if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2627 error.SetErrorString("invalid pathname");
2630 basename = pathname; // not a filename, probably a package of some sort,
2631 // let it go through
2632 } else if (is_directory(st) || is_regular_file(st)) {
2633 std::string directory = target_file.GetDirectory().GetCString();
2634 replace_all(directory, "\\", "\\\\");
2635 replace_all(directory, "'", "\\'");
2637 // now make sure that Python has "directory" in the search path
2638 StreamString command_stream;
2639 command_stream.Printf("if not (sys.path.__contains__('%s')):\n "
2640 "sys.path.insert(1,'%s');\n\n",
2641 directory.c_str(), directory.c_str());
2642 bool syspath_retval =
2643 ExecuteMultipleLines(command_stream.GetData(),
2644 ScriptInterpreter::ExecuteScriptOptions()
2646 .SetSetLLDBGlobals(false))
2648 if (!syspath_retval) {
2649 error.SetErrorString("Python sys.path handling failed");
2653 // strip .py or .pyc extension
2654 ConstString extension = target_file.GetFileNameExtension();
2656 if (llvm::StringRef(extension.GetCString()) == ".py")
2657 basename.resize(basename.length() - 3);
2658 else if (llvm::StringRef(extension.GetCString()) == ".pyc")
2659 basename.resize(basename.length() - 4);
2662 error.SetErrorString("no known way to import this module specification");
2666 // check if the module is already import-ed
2667 command_stream.Clear();
2668 command_stream.Printf("sys.modules.__contains__('%s')", basename.c_str());
2669 bool does_contain = false;
2670 // this call will succeed if the module was ever imported in any Debugger
2671 // in the lifetime of the process in which this LLDB framework is living
2672 bool was_imported_globally =
2673 (ExecuteOneLineWithReturn(
2674 command_stream.GetData(),
2675 ScriptInterpreterPython::eScriptReturnTypeBool, &does_contain,
2676 ScriptInterpreter::ExecuteScriptOptions()
2678 .SetSetLLDBGlobals(false)) &&
2680 // this call will fail if the module was not imported in this Debugger
2682 command_stream.Clear();
2683 command_stream.Printf("sys.getrefcount(%s)", basename.c_str());
2684 bool was_imported_locally = GetSessionDictionary()
2685 .GetItemForKey(PythonString(basename))
2688 bool was_imported = (was_imported_globally || was_imported_locally);
2690 if (was_imported == true && can_reload == false) {
2691 error.SetErrorString("module already imported");
2695 // now actually do the import
2696 command_stream.Clear();
2699 if (!was_imported_locally)
2700 command_stream.Printf("import %s ; reload_module(%s)", basename.c_str(),
2703 command_stream.Printf("reload_module(%s)", basename.c_str());
2705 command_stream.Printf("import %s", basename.c_str());
2707 error = ExecuteMultipleLines(command_stream.GetData(),
2708 ScriptInterpreter::ExecuteScriptOptions()
2710 .SetSetLLDBGlobals(false));
2714 // if we are here, everything worked
2715 // call __lldb_init_module(debugger,dict)
2716 if (!g_swig_call_module_init(basename.c_str(), m_dictionary_name.c_str(),
2718 error.SetErrorString("calling __lldb_init_module failed");
2723 // everything went just great, now set the module object
2724 command_stream.Clear();
2725 command_stream.Printf("%s", basename.c_str());
2726 void *module_pyobj = nullptr;
2727 if (ExecuteOneLineWithReturn(
2728 command_stream.GetData(),
2729 ScriptInterpreter::eScriptReturnTypeOpaqueObject,
2732 module_sp->reset(new StructuredPythonObject(module_pyobj));
2739 bool ScriptInterpreterPython::IsReservedWord(const char *word) {
2740 if (!word || !word[0])
2743 llvm::StringRef word_sr(word);
2745 // filter out a few characters that would just confuse us and that are
2746 // clearly not keyword material anyway
2747 if (word_sr.find_first_of("'\"") != llvm::StringRef::npos)
2750 StreamString command_stream;
2751 command_stream.Printf("keyword.iskeyword('%s')", word);
2753 ExecuteScriptOptions options;
2754 options.SetEnableIO(false);
2755 options.SetMaskoutErrors(true);
2756 options.SetSetLLDBGlobals(false);
2757 if (ExecuteOneLineWithReturn(command_stream.GetData(),
2758 ScriptInterpreter::eScriptReturnTypeBool,
2764 ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler(
2765 lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2766 : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2767 m_old_asynch(debugger_sp->GetAsyncExecution()) {
2768 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2769 m_debugger_sp->SetAsyncExecution(false);
2770 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2771 m_debugger_sp->SetAsyncExecution(true);
2774 ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler() {
2775 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2776 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2779 bool ScriptInterpreterPython::RunScriptBasedCommand(
2780 const char *impl_function, llvm::StringRef args,
2781 ScriptedCommandSynchronicity synchronicity,
2782 lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2783 const lldb_private::ExecutionContext &exe_ctx) {
2784 if (!impl_function) {
2785 error.SetErrorString("no function to execute");
2789 if (!g_swig_call_command) {
2790 error.SetErrorString("no helper function to run scripted commands");
2794 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
2795 lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2797 if (!debugger_sp.get()) {
2798 error.SetErrorString("invalid Debugger pointer");
2802 bool ret_val = false;
2804 std::string err_msg;
2807 Locker py_lock(this,
2808 Locker::AcquireLock | Locker::InitSession |
2809 (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2810 Locker::FreeLock | Locker::TearDownSession);
2812 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2814 std::string args_str = args.str();
2815 ret_val = g_swig_call_command(impl_function, m_dictionary_name.c_str(),
2816 debugger_sp, args_str.c_str(), cmd_retobj,
2821 error.SetErrorString("unable to execute script function");
2828 bool ScriptInterpreterPython::RunScriptBasedCommand(
2829 StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
2830 ScriptedCommandSynchronicity synchronicity,
2831 lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2832 const lldb_private::ExecutionContext &exe_ctx) {
2833 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2834 error.SetErrorString("no function to execute");
2838 if (!g_swig_call_command_object) {
2839 error.SetErrorString("no helper function to run scripted commands");
2843 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
2844 lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2846 if (!debugger_sp.get()) {
2847 error.SetErrorString("invalid Debugger pointer");
2851 bool ret_val = false;
2853 std::string err_msg;
2856 Locker py_lock(this,
2857 Locker::AcquireLock | Locker::InitSession |
2858 (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2859 Locker::FreeLock | Locker::TearDownSession);
2861 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2863 std::string args_str = args.str();
2864 ret_val = g_swig_call_command_object(impl_obj_sp->GetValue(), debugger_sp,
2865 args_str.c_str(), cmd_retobj,
2870 error.SetErrorString("unable to execute script function");
2877 // in Python, a special attribute __doc__ contains the docstring for an object
2878 // (function, method, class, ...) if any is defined Otherwise, the attribute's
2880 bool ScriptInterpreterPython::GetDocumentationForItem(const char *item,
2881 std::string &dest) {
2883 if (!item || !*item)
2885 std::string command(item);
2886 command += ".__doc__";
2888 char *result_ptr = nullptr; // Python is going to point this to valid data if
2889 // ExecuteOneLineWithReturn returns successfully
2891 if (ExecuteOneLineWithReturn(
2892 command.c_str(), ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
2894 ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false))) {
2896 dest.assign(result_ptr);
2899 StreamString str_stream;
2901 "Function %s was not found. Containing module might be missing.", item);
2902 dest = str_stream.GetString();
2907 bool ScriptInterpreterPython::GetShortHelpForCommandObject(
2908 StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2909 bool got_string = false;
2912 Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2914 static char callee_name[] = "get_short_help";
2919 PythonObject implementor(PyRefType::Borrowed,
2920 (PyObject *)cmd_obj_sp->GetValue());
2922 if (!implementor.IsAllocated())
2925 PythonObject pmeth(PyRefType::Owned,
2926 PyObject_GetAttrString(implementor.get(), callee_name));
2928 if (PyErr_Occurred())
2931 if (!pmeth.IsAllocated())
2934 if (PyCallable_Check(pmeth.get()) == 0) {
2935 if (PyErr_Occurred())
2940 if (PyErr_Occurred())
2943 // right now we know this function exists and is callable..
2944 PythonObject py_return(
2946 PyObject_CallMethod(implementor.get(), callee_name, nullptr));
2948 // if it fails, print the error but otherwise go on
2949 if (PyErr_Occurred()) {
2954 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2955 PythonString py_string(PyRefType::Borrowed, py_return.get());
2956 llvm::StringRef return_data(py_string.GetString());
2957 dest.assign(return_data.data(), return_data.size());
2963 uint32_t ScriptInterpreterPython::GetFlagsForCommandObject(
2964 StructuredData::GenericSP cmd_obj_sp) {
2965 uint32_t result = 0;
2967 Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2969 static char callee_name[] = "get_flags";
2974 PythonObject implementor(PyRefType::Borrowed,
2975 (PyObject *)cmd_obj_sp->GetValue());
2977 if (!implementor.IsAllocated())
2980 PythonObject pmeth(PyRefType::Owned,
2981 PyObject_GetAttrString(implementor.get(), callee_name));
2983 if (PyErr_Occurred())
2986 if (!pmeth.IsAllocated())
2989 if (PyCallable_Check(pmeth.get()) == 0) {
2990 if (PyErr_Occurred())
2995 if (PyErr_Occurred())
2998 // right now we know this function exists and is callable..
2999 PythonObject py_return(
3001 PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3003 // if it fails, print the error but otherwise go on
3004 if (PyErr_Occurred()) {
3009 if (py_return.IsAllocated() && PythonInteger::Check(py_return.get())) {
3010 PythonInteger int_value(PyRefType::Borrowed, py_return.get());
3011 result = int_value.GetInteger();
3017 bool ScriptInterpreterPython::GetLongHelpForCommandObject(
3018 StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
3019 bool got_string = false;
3022 Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3024 static char callee_name[] = "get_long_help";
3029 PythonObject implementor(PyRefType::Borrowed,
3030 (PyObject *)cmd_obj_sp->GetValue());
3032 if (!implementor.IsAllocated())
3035 PythonObject pmeth(PyRefType::Owned,
3036 PyObject_GetAttrString(implementor.get(), callee_name));
3038 if (PyErr_Occurred())
3041 if (!pmeth.IsAllocated())
3044 if (PyCallable_Check(pmeth.get()) == 0) {
3045 if (PyErr_Occurred())
3051 if (PyErr_Occurred())
3054 // right now we know this function exists and is callable..
3055 PythonObject py_return(
3057 PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3059 // if it fails, print the error but otherwise go on
3060 if (PyErr_Occurred()) {
3065 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3066 PythonString str(PyRefType::Borrowed, py_return.get());
3067 llvm::StringRef str_data(str.GetString());
3068 dest.assign(str_data.data(), str_data.size());
3075 std::unique_ptr<ScriptInterpreterLocker>
3076 ScriptInterpreterPython::AcquireInterpreterLock() {
3077 std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3078 this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3079 Locker::FreeLock | Locker::TearDownSession));
3083 void ScriptInterpreterPython::InitializeInterpreter(
3084 SWIGInitCallback swig_init_callback,
3085 SWIGBreakpointCallbackFunction swig_breakpoint_callback,
3086 SWIGWatchpointCallbackFunction swig_watchpoint_callback,
3087 SWIGPythonTypeScriptCallbackFunction swig_typescript_callback,
3088 SWIGPythonCreateSyntheticProvider swig_synthetic_script,
3089 SWIGPythonCreateCommandObject swig_create_cmd,
3090 SWIGPythonCalculateNumChildren swig_calc_children,
3091 SWIGPythonGetChildAtIndex swig_get_child_index,
3092 SWIGPythonGetIndexOfChildWithName swig_get_index_child,
3093 SWIGPythonCastPyObjectToSBValue swig_cast_to_sbvalue,
3094 SWIGPythonGetValueObjectSPFromSBValue swig_get_valobj_sp_from_sbvalue,
3095 SWIGPythonUpdateSynthProviderInstance swig_update_provider,
3096 SWIGPythonMightHaveChildrenSynthProviderInstance
3097 swig_mighthavechildren_provider,
3098 SWIGPythonGetValueSynthProviderInstance swig_getvalue_provider,
3099 SWIGPythonCallCommand swig_call_command,
3100 SWIGPythonCallCommandObject swig_call_command_object,
3101 SWIGPythonCallModuleInit swig_call_module_init,
3102 SWIGPythonCreateOSPlugin swig_create_os_plugin,
3103 SWIGPythonScriptKeyword_Process swig_run_script_keyword_process,
3104 SWIGPythonScriptKeyword_Thread swig_run_script_keyword_thread,
3105 SWIGPythonScriptKeyword_Target swig_run_script_keyword_target,
3106 SWIGPythonScriptKeyword_Frame swig_run_script_keyword_frame,
3107 SWIGPythonScriptKeyword_Value swig_run_script_keyword_value,
3108 SWIGPython_GetDynamicSetting swig_plugin_get,
3109 SWIGPythonCreateScriptedThreadPlan swig_thread_plan_script,
3110 SWIGPythonCallThreadPlan swig_call_thread_plan) {
3111 g_swig_init_callback = swig_init_callback;
3112 g_swig_breakpoint_callback = swig_breakpoint_callback;
3113 g_swig_watchpoint_callback = swig_watchpoint_callback;
3114 g_swig_typescript_callback = swig_typescript_callback;
3115 g_swig_synthetic_script = swig_synthetic_script;
3116 g_swig_create_cmd = swig_create_cmd;
3117 g_swig_calc_children = swig_calc_children;
3118 g_swig_get_child_index = swig_get_child_index;
3119 g_swig_get_index_child = swig_get_index_child;
3120 g_swig_cast_to_sbvalue = swig_cast_to_sbvalue;
3121 g_swig_get_valobj_sp_from_sbvalue = swig_get_valobj_sp_from_sbvalue;
3122 g_swig_update_provider = swig_update_provider;
3123 g_swig_mighthavechildren_provider = swig_mighthavechildren_provider;
3124 g_swig_getvalue_provider = swig_getvalue_provider;
3125 g_swig_call_command = swig_call_command;
3126 g_swig_call_command_object = swig_call_command_object;
3127 g_swig_call_module_init = swig_call_module_init;
3128 g_swig_create_os_plugin = swig_create_os_plugin;
3129 g_swig_run_script_keyword_process = swig_run_script_keyword_process;
3130 g_swig_run_script_keyword_thread = swig_run_script_keyword_thread;
3131 g_swig_run_script_keyword_target = swig_run_script_keyword_target;
3132 g_swig_run_script_keyword_frame = swig_run_script_keyword_frame;
3133 g_swig_run_script_keyword_value = swig_run_script_keyword_value;
3134 g_swig_plugin_get = swig_plugin_get;
3135 g_swig_thread_plan_script = swig_thread_plan_script;
3136 g_swig_call_thread_plan = swig_call_thread_plan;
3139 void ScriptInterpreterPython::InitializePrivate() {
3143 g_initialized = true;
3145 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
3146 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
3148 // RAII-based initialization which correctly handles multiple-initialization,
3149 // version- specific differences among Python 2 and Python 3, and saving and
3150 // restoring various other pieces of state that can get mucked with during
3152 InitializePythonRAII initialize_guard;
3154 if (g_swig_init_callback)
3155 g_swig_init_callback();
3157 // Update the path python uses to search for modules to include the current
3160 PyRun_SimpleString("import sys");
3161 AddToSysPath(AddLocation::End, ".");
3163 // Don't denormalize paths when calling file_spec.GetPath(). On platforms
3164 // that use a backslash as the path separator, this will result in executing
3165 // python code containing paths with unescaped backslashes. But Python also
3166 // accepts forward slashes, so to make life easier we just use that.
3167 if (FileSpec file_spec = GetPythonDir())
3168 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3169 if (FileSpec file_spec = HostInfo::GetShlibDir())
3170 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3172 PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3173 "lldb.embedded_interpreter; from "
3174 "lldb.embedded_interpreter import run_python_interpreter; "
3175 "from lldb.embedded_interpreter import run_one_line");
3178 void ScriptInterpreterPython::AddToSysPath(AddLocation location,
3180 std::string path_copy;
3182 std::string statement;
3183 if (location == AddLocation::Beginning) {
3184 statement.assign("sys.path.insert(0,\"");
3185 statement.append(path);
3186 statement.append("\")");
3188 statement.assign("sys.path.append(\"");
3189 statement.append(path);
3190 statement.append("\")");
3192 PyRun_SimpleString(statement.c_str());
3195 // We are intentionally NOT calling Py_Finalize here (this would be the logical
3196 // place to call it). Calling Py_Finalize here causes test suite runs to seg
3197 // fault: The test suite runs in Python. It registers SBDebugger::Terminate to
3198 // be called 'at_exit'. When the test suite Python harness finishes up, it
3199 // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3200 // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3201 // which calls ScriptInterpreter::Terminate, which calls
3202 // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end
3203 // up with Py_Finalize being called from within Py_Finalize, which results in a
3204 // seg fault. Since this function only gets called when lldb is shutting down
3205 // and going away anyway, the fact that we don't actually call Py_Finalize
3206 // should not cause any problems (everything should shut down/go away anyway
3207 // when the process exits).
3209 // void ScriptInterpreterPython::Terminate() { Py_Finalize (); }
3211 #endif // LLDB_DISABLE_PYTHON