9#include "lldb/Host/Config.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/StringRef.h"
46#include "llvm/Support/Error.h"
47#include "llvm/Support/FileSystem.h"
48#include "llvm/Support/FormatAdapters.h"
65extern "C" PyObject *PyInit__lldb(
void);
67#define LLDBSwigPyInit PyInit__lldb
71#define LLDB_USE_PYTHON_SET_INTERRUPT 0
74#define LLDB_USE_PYTHON_SET_INTERRUPT \
75 (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
78static ScriptInterpreterPythonImpl *GetPythonInterpreter(
Debugger &debugger) {
81 return static_cast<ScriptInterpreterPythonImpl *
>(script_interpreter);
92struct InitializePythonRAII {
94 InitializePythonRAII() {
95 InitializePythonHome();
99 if (!Py_IsInitialized()) {
100#ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
103 bool ReadlinePatched =
false;
104 for (
auto *p = PyImport_Inittab; p->name !=
nullptr; p++) {
105 if (strcmp(p->name,
"readline") == 0) {
106 p->initfunc = initlldb_readline;
110 if (!ReadlinePatched) {
111 PyImport_AppendInittab(
"readline", initlldb_readline);
112 ReadlinePatched =
true;
117 PyImport_AppendInittab(
"_lldb", LLDBSwigPyInit);
123#if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
125 InitializeThreadsPrivate();
127 InitializeThreadsPrivate();
132 ~InitializePythonRAII() {
133 if (m_was_already_initialized) {
135 LLDB_LOGV(log,
"Releasing PyGILState. Returning to state = {0}locked",
136 m_gil_state == PyGILState_UNLOCKED ?
"un" :
"");
137 PyGILState_Release(m_gil_state);
145 void InitializePythonHome() {
146#if LLDB_EMBED_PYTHON_HOME
147 typedef wchar_t *str_type;
148 static str_type g_python_home = []() -> str_type {
149 const char *lldb_python_home = LLDB_PYTHON_HOME;
150 const char *absolute_python_home =
nullptr;
151 llvm::SmallString<64> path;
152 if (llvm::sys::path::is_absolute(lldb_python_home)) {
153 absolute_python_home = lldb_python_home;
155 FileSpec spec = HostInfo::GetShlibDir();
159 llvm::sys::path::append(path, lldb_python_home);
160 absolute_python_home = path.c_str();
163 return Py_DecodeLocale(absolute_python_home, &size);
165 if (g_python_home !=
nullptr) {
166 Py_SetPythonHome(g_python_home);
171 void InitializeThreadsPrivate() {
178#if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3)
180 if (PyGILState_Check())
186#if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 9) || (PY_MAJOR_VERSION < 3)
187 if (PyEval_ThreadsInitialized()) {
193 m_was_already_initialized =
true;
194 m_gil_state = PyGILState_Ensure();
195 LLDB_LOGV(log,
"Ensured PyGILState. Previous state = {0}locked\n",
196 m_gil_state == PyGILState_UNLOCKED ?
"un" :
"");
200#if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 9) || (PY_MAJOR_VERSION < 3)
205 PyEval_InitThreads();
211 PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
212 bool m_was_already_initialized =
false;
215#if LLDB_USE_PYTHON_SET_INTERRUPT
218struct RestoreSignalHandlerScope {
220 struct sigaction m_prev_handler;
222 RestoreSignalHandlerScope(
int signal_code) : m_signal_code(signal_code) {
224 std::memset(&m_prev_handler, 0,
sizeof(m_prev_handler));
226 struct sigaction *new_handler =
nullptr;
227 int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler);
228 lldbassert(signal_err == 0 &&
"sigaction failed to read handler");
230 ~RestoreSignalHandlerScope() {
231 int signal_err = ::sigaction(m_signal_code, &m_prev_handler,
nullptr);
232 lldbassert(signal_err == 0 &&
"sigaction failed to restore old handler");
238void ScriptInterpreterPython::ComputePythonDirForApple(
240 auto style = llvm::sys::path::Style::posix;
242 llvm::StringRef path_ref(path.begin(), path.size());
243 auto rbegin = llvm::sys::path::rbegin(path_ref, style);
244 auto rend = llvm::sys::path::rend(path_ref);
245 auto framework = std::find(rbegin, rend,
"LLDB.framework");
246 if (framework == rend) {
247 ComputePythonDir(path);
250 path.resize(framework - rend);
251 llvm::sys::path::append(path, style,
"LLDB.framework",
"Resources",
"Python");
254void ScriptInterpreterPython::ComputePythonDir(
259 llvm::sys::path::remove_filename(path);
260 llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
265 std::replace(path.begin(), path.end(),
'\\',
'/');
269FileSpec ScriptInterpreterPython::GetPythonDir() {
271 FileSpec spec = HostInfo::GetShlibDir();
274 llvm::SmallString<64> path;
277#if defined(__APPLE__)
278 ComputePythonDirForApple(path);
280 ComputePythonDir(path);
288static const char GetInterpreterInfoScript[] = R
"(
292def main(lldb_python_dir, python_exe_relative_path):
294 "lldb-pythonpath": lldb_python_dir,
295 "language": "python",
296 "prefix": sys.prefix,
297 "executable": os.path.join(sys.prefix, python_exe_relative_path)
302static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH;
306 FileSpec python_dir_spec = GetPythonDir();
307 if (!python_dir_spec)
309 PythonScript get_info(GetInterpreterInfoScript);
310 auto info_json = unwrapIgnoringErrors(
311 As<PythonDictionary>(get_info(PythonString(python_dir_spec.
GetPath()),
312 PythonString(python_exe_relative_path))));
315 return info_json.CreateStructuredDictionary();
318void ScriptInterpreterPython::SharedLibraryDirectoryHelper(
329 llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
330 for (
auto it = llvm::sys::path::begin(libdir),
331 end = llvm::sys::path::end(libdir);
340 FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
344llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() {
345 return "Embedded Python interpreter";
348void ScriptInterpreterPython::Initialize() {
349 static llvm::once_flag g_once_flag;
350 llvm::call_once(g_once_flag, []() {
351 PluginManager::RegisterPlugin(GetPluginNameStatic(),
352 GetPluginDescriptionStatic(),
354 ScriptInterpreterPythonImpl::CreateInstance);
355 ScriptInterpreterPythonImpl::Initialize();
359void ScriptInterpreterPython::Terminate() {}
361ScriptInterpreterPythonImpl::Locker::Locker(
362 ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
365 m_teardown_session((on_leave & TearDownSession) == TearDownSession),
366 m_python_interpreter(py_interpreter) {
368 if ((on_entry & InitSession) == InitSession) {
369 if (!DoInitSession(on_entry, in, out, err)) {
371 m_teardown_session =
false;
376bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
378 m_GILState = PyGILState_Ensure();
379 LLDB_LOGV(log,
"Ensured PyGILState. Previous state = {0}locked",
380 m_GILState == PyGILState_UNLOCKED ?
"un" :
"");
387 m_python_interpreter->SetThreadState(PyThreadState_Get());
388 m_python_interpreter->IncrementLockCount();
392bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
395 if (!m_python_interpreter)
397 return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
400bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
402 LLDB_LOGV(log,
"Releasing PyGILState. Returning to state = {0}locked",
403 m_GILState == PyGILState_UNLOCKED ?
"un" :
"");
404 PyGILState_Release(m_GILState);
405 m_python_interpreter->DecrementLockCount();
409bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
410 if (!m_python_interpreter)
412 m_python_interpreter->LeaveSession();
416ScriptInterpreterPythonImpl::Locker::~Locker() {
417 if (m_teardown_session)
422ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(
Debugger &debugger)
423 : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
424 m_saved_stderr(), m_main_module(),
425 m_session_dict(PyInitialValue::
Invalid),
426 m_sys_module_dict(PyInitialValue::
Invalid), m_run_one_line_function(),
427 m_run_one_line_str_global(),
428 m_dictionary_name(m_debugger.GetInstanceName()),
430 m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
431 m_command_thread_state(nullptr) {
433 m_dictionary_name.append(
"_dict");
435 run_string.
Printf(
"%s = dict()", m_dictionary_name.c_str());
437 Locker locker(
this, Locker::AcquireLock, Locker::FreeAcquiredLock);
438 PyRun_SimpleString(run_string.
GetData());
442 "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
443 m_dictionary_name.c_str());
444 PyRun_SimpleString(run_string.
GetData());
449 run_string.
Printf(
"run_one_line (%s, 'from importlib import reload as reload_module')",
450 m_dictionary_name.c_str());
451 PyRun_SimpleString(run_string.
GetData());
459 "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp')",
460 m_dictionary_name.c_str());
461 PyRun_SimpleString(run_string.
GetData());
464 run_string.
Printf(
"run_one_line (%s, 'import lldb.embedded_interpreter; from "
465 "lldb.embedded_interpreter import run_python_interpreter; "
466 "from lldb.embedded_interpreter import run_one_line')",
467 m_dictionary_name.c_str());
468 PyRun_SimpleString(run_string.
GetData());
471 run_string.
Printf(
"run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
473 m_dictionary_name.c_str(), m_debugger.GetID());
474 PyRun_SimpleString(run_string.
GetData());
477ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
483 auto gil_state = PyGILState_Ensure();
484 m_session_dict.Reset();
485 PyGILState_Release(gil_state);
488void ScriptInterpreterPythonImpl::IOHandlerActivated(
IOHandler &io_handler,
490 const char *instructions =
nullptr;
492 switch (m_active_io_handler) {
496 instructions = R
"(Enter your Python command(s). Type 'DONE' to end.
497def function (frame, bp_loc, internal_dict):
498 """frame: the lldb.SBFrame for the location at which you stopped
499 bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
500 internal_dict: an LLDB support object not to be used"""
504 instructions =
"Enter your Python command(s). Type 'DONE' to end.\n";
510 if (output_sp && interactive) {
511 output_sp->PutCString(instructions);
517void ScriptInterpreterPythonImpl::IOHandlerInputComplete(
IOHandler &io_handler,
520 bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
522 switch (m_active_io_handler) {
526 std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
527 (std::vector<std::reference_wrapper<BreakpointOptions>> *)
531 auto data_up = std::make_unique<CommandDataPython>();
534 data_up->user_source.SplitIntoLines(data);
536 if (GenerateBreakpointCommandCallbackData(data_up->user_source,
537 data_up->script_source,
541 auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
543 bp_options.SetCallback(
544 ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
545 }
else if (!batch_mode) {
548 error_sp->Printf(
"Warning: No command attached to breakpoint.\n");
558 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
559 data_up->user_source.SplitIntoLines(data);
561 if (GenerateWatchpointCommandCallbackData(data_up->user_source,
562 data_up->script_source,
565 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
567 ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
568 }
else if (!batch_mode) {
571 error_sp->Printf(
"Warning: No command attached to breakpoint.\n");
581ScriptInterpreterPythonImpl::CreateInstance(
Debugger &debugger) {
582 return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
585void ScriptInterpreterPythonImpl::LeaveSession() {
588 log->
PutCString(
"ScriptInterpreterPythonImpl::LeaveSession()");
591 PyRun_SimpleString(
"lldb.debugger = None; lldb.target = None; lldb.process "
592 "= None; lldb.thread = None; lldb.frame = None");
599 if (PyThreadState_GetDict()) {
600 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
601 if (sys_module_dict.IsValid()) {
602 if (m_saved_stdin.IsValid()) {
603 sys_module_dict.SetItemForKey(PythonString(
"stdin"), m_saved_stdin);
604 m_saved_stdin.Reset();
606 if (m_saved_stdout.IsValid()) {
607 sys_module_dict.SetItemForKey(PythonString(
"stdout"), m_saved_stdout);
608 m_saved_stdout.Reset();
610 if (m_saved_stderr.IsValid()) {
611 sys_module_dict.SetItemForKey(PythonString(
"stderr"), m_saved_stderr);
612 m_saved_stderr.Reset();
617 m_session_is_active =
false;
620bool ScriptInterpreterPythonImpl::SetStdHandle(
FileSP file_sp,
622 PythonObject &save_file,
624 if (!file_sp || !*file_sp) {
628 File &file = *file_sp;
633 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
635 auto new_file = PythonFile::FromFile(file, mode);
637 llvm::consumeError(new_file.takeError());
641 save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
643 sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
647bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
653 if (m_session_is_active) {
656 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
657 ") session is already active, returning without doing anything",
664 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
")",
667 m_session_is_active =
true;
671 if (on_entry_flags & Locker::InitGlobals) {
672 run_string.
Printf(
"run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
673 m_dictionary_name.c_str(), m_debugger.GetID());
675 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64
")",
677 run_string.
PutCString(
"; lldb.target = lldb.debugger.GetSelectedTarget()");
678 run_string.
PutCString(
"; lldb.process = lldb.target.GetProcess()");
679 run_string.
PutCString(
"; lldb.thread = lldb.process.GetSelectedThread ()");
680 run_string.
PutCString(
"; lldb.frame = lldb.thread.GetSelectedFrame ()");
685 run_string.
Printf(
"run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
686 m_dictionary_name.c_str(), m_debugger.GetID());
688 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64
")",
693 PyRun_SimpleString(run_string.
GetData());
696 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
697 if (sys_module_dict.IsValid()) {
700 if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
701 m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
704 if (on_entry_flags & Locker::NoSTDIN) {
705 m_saved_stdin.Reset();
707 if (!SetStdHandle(in_sp,
"stdin", m_saved_stdin,
"r")) {
709 SetStdHandle(top_in_sp,
"stdin", m_saved_stdin,
"r");
713 if (!SetStdHandle(out_sp,
"stdout", m_saved_stdout,
"w")) {
715 SetStdHandle(top_out_sp->GetFileSP(),
"stdout", m_saved_stdout,
"w");
718 if (!SetStdHandle(err_sp,
"stderr", m_saved_stderr,
"w")) {
720 SetStdHandle(top_err_sp->GetFileSP(),
"stderr", m_saved_stderr,
"w");
724 if (PyErr_Occurred())
730PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
731 if (!m_main_module.IsValid())
732 m_main_module = unwrapIgnoringErrors(PythonModule::Import(
"__main__"));
733 return m_main_module;
736PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
737 if (m_session_dict.IsValid())
738 return m_session_dict;
740 PythonObject &main_module = GetMainModule();
741 if (!main_module.IsValid())
742 return m_session_dict;
744 PythonDictionary main_dict(PyRefType::Borrowed,
745 PyModule_GetDict(main_module.get()));
746 if (!main_dict.IsValid())
747 return m_session_dict;
749 m_session_dict = unwrapIgnoringErrors(
750 As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
751 return m_session_dict;
754PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
755 if (m_sys_module_dict.IsValid())
756 return m_sys_module_dict;
757 PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import(
"sys"));
758 m_sys_module_dict = sys_module.GetDictionary();
759 return m_sys_module_dict;
762llvm::Expected<unsigned>
763ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
764 const llvm::StringRef &callable_name) {
765 if (callable_name.empty()) {
766 return llvm::createStringError(
767 llvm::inconvertibleErrorCode(),
768 "called with empty callable name.");
770 Locker py_lock(
this, Locker::AcquireLock |
771 Locker::InitSession |
773 auto dict = PythonModule::MainModule()
774 .ResolveName<PythonDictionary>(m_dictionary_name);
775 auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
776 callable_name, dict);
777 if (!pfunc.IsAllocated()) {
778 return llvm::createStringError(
779 llvm::inconvertibleErrorCode(),
780 "can't find callable: %s", callable_name.str().c_str());
782 llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
784 return arg_info.takeError();
785 return arg_info.get().max_positional_args;
788static std::string GenerateUniqueName(
const char *base_name_wanted,
789 uint32_t &functions_counter,
790 const void *name_token =
nullptr) {
793 if (!base_name_wanted)
794 return std::string();
797 sstr.
Printf(
"%s_%d", base_name_wanted, functions_counter++);
799 sstr.
Printf(
"%s_%p", base_name_wanted, name_token);
804bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
805 if (m_run_one_line_function.IsValid())
808 PythonObject module(PyRefType::Borrowed,
809 PyImport_AddModule(
"lldb.embedded_interpreter"));
810 if (!module.IsValid())
813 PythonDictionary module_dict(PyRefType::Borrowed,
814 PyModule_GetDict(module.get()));
815 if (!module_dict.IsValid())
818 m_run_one_line_function =
819 module_dict.GetItemForKey(PythonString(
"run_one_line"));
820 m_run_one_line_str_global =
821 module_dict.GetItemForKey(PythonString(
"g_run_one_line_str"));
822 return m_run_one_line_function.IsValid();
825bool ScriptInterpreterPythonImpl::ExecuteOneLine(
828 std::string command_str = command.str();
830 if (!m_valid_session)
833 if (!command.empty()) {
840 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
841 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
843 if (!io_redirect_or_error) {
846 "failed to redirect I/O: {0}\n",
847 llvm::fmt_consume(io_redirect_or_error.takeError()));
849 llvm::consumeError(io_redirect_or_error.takeError());
855 bool success =
false;
867 Locker::AcquireLock | Locker::InitSession |
870 Locker::FreeAcquiredLock | Locker::TearDownSession,
875 PythonDictionary &session_dict = GetSessionDictionary();
876 if (session_dict.IsValid()) {
877 if (GetEmbeddedInterpreterModuleObjects()) {
878 if (PyCallable_Check(m_run_one_line_function.get())) {
881 Py_BuildValue(
"(Os)", session_dict.get(), command_str.c_str()));
882 if (pargs.IsValid()) {
883 PythonObject return_value(
885 PyObject_CallObject(m_run_one_line_function.get(),
887 if (return_value.IsValid())
907 "python failed attempting to evaluate '%s'\n", command_str.c_str());
913 result->
AppendError(
"empty command passed to python\n");
917void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
931 IOHandlerSP io_handler_sp(
new IOHandlerPythonInterpreter(debugger,
this));
937bool ScriptInterpreterPythonImpl::Interrupt() {
938#if LLDB_USE_PYTHON_SET_INTERRUPT
942 if (!IsExecutingPython())
946 PyErr_SetInterrupt();
956 if (IsExecutingPython()) {
957 PyThreadState *state = PyThreadState_GET();
959 state = GetThreadState();
961 long tid = state->thread_id;
962 PyThreadState_Swap(state);
963 int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
965 "ScriptInterpreterPythonImpl::Interrupt() sending "
966 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
972 "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
978bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
982 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
983 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
986 if (!io_redirect_or_error) {
987 llvm::consumeError(io_redirect_or_error.takeError());
994 Locker::AcquireLock | Locker::InitSession |
997 Locker::FreeAcquiredLock | Locker::TearDownSession,
1001 PythonModule &main_module = GetMainModule();
1002 PythonDictionary globals = main_module.GetDictionary();
1004 PythonDictionary locals = GetSessionDictionary();
1005 if (!locals.IsValid())
1006 locals = unwrapIgnoringErrors(
1007 As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1008 if (!locals.IsValid())
1011 Expected<PythonObject> maybe_py_return =
1012 runStringOneLine(in_string, globals, locals);
1014 if (!maybe_py_return) {
1015 llvm::handleAllErrors(
1016 maybe_py_return.takeError(),
1017 [&](PythonException &E) {
1019 if (options.GetMaskoutErrors()) {
1020 if (E.Matches(PyExc_SyntaxError)) {
1026 [](
const llvm::ErrorInfoBase &E) {});
1030 PythonObject py_return = std::move(maybe_py_return.get());
1031 assert(py_return.IsValid());
1033 switch (return_type) {
1034 case eScriptReturnTypeCharPtr:
1036 const char format[3] =
"s#";
1037 return PyArg_Parse(py_return.get(), format, (
char **)ret_value);
1039 case eScriptReturnTypeCharStrOrNone:
1042 const char format[3] =
"z";
1043 return PyArg_Parse(py_return.get(), format, (
char **)ret_value);
1045 case eScriptReturnTypeBool: {
1046 const char format[2] =
"b";
1047 return PyArg_Parse(py_return.get(), format, (
bool *)ret_value);
1049 case eScriptReturnTypeShortInt: {
1050 const char format[2] =
"h";
1051 return PyArg_Parse(py_return.get(), format, (
short *)ret_value);
1053 case eScriptReturnTypeShortIntUnsigned: {
1054 const char format[2] =
"H";
1055 return PyArg_Parse(py_return.get(), format, (
unsigned short *)ret_value);
1057 case eScriptReturnTypeInt: {
1058 const char format[2] =
"i";
1059 return PyArg_Parse(py_return.get(), format, (
int *)ret_value);
1061 case eScriptReturnTypeIntUnsigned: {
1062 const char format[2] =
"I";
1063 return PyArg_Parse(py_return.get(), format, (
unsigned int *)ret_value);
1065 case eScriptReturnTypeLongInt: {
1066 const char format[2] =
"l";
1067 return PyArg_Parse(py_return.get(), format, (
long *)ret_value);
1069 case eScriptReturnTypeLongIntUnsigned: {
1070 const char format[2] =
"k";
1071 return PyArg_Parse(py_return.get(), format, (
unsigned long *)ret_value);
1073 case eScriptReturnTypeLongLong: {
1074 const char format[2] =
"L";
1075 return PyArg_Parse(py_return.get(), format, (
long long *)ret_value);
1077 case eScriptReturnTypeLongLongUnsigned: {
1078 const char format[2] =
"K";
1079 return PyArg_Parse(py_return.get(), format,
1080 (
unsigned long long *)ret_value);
1082 case eScriptReturnTypeFloat: {
1083 const char format[2] =
"f";
1084 return PyArg_Parse(py_return.get(), format, (
float *)ret_value);
1086 case eScriptReturnTypeDouble: {
1087 const char format[2] =
"d";
1088 return PyArg_Parse(py_return.get(), format, (
double *)ret_value);
1090 case eScriptReturnTypeChar: {
1091 const char format[2] =
"c";
1092 return PyArg_Parse(py_return.get(), format, (
char *)ret_value);
1094 case eScriptReturnTypeOpaqueObject: {
1095 *((PyObject **)ret_value) = py_return.release();
1099 llvm_unreachable(
"Fully covered switch!");
1102Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1105 if (in_string ==
nullptr)
1108 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1109 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1112 if (!io_redirect_or_error)
1113 return Status(io_redirect_or_error.takeError());
1118 Locker::AcquireLock | Locker::InitSession |
1121 Locker::FreeAcquiredLock | Locker::TearDownSession,
1125 PythonModule &main_module = GetMainModule();
1126 PythonDictionary globals = main_module.GetDictionary();
1128 PythonDictionary locals = GetSessionDictionary();
1129 if (!locals.IsValid())
1130 locals = unwrapIgnoringErrors(
1131 As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1132 if (!locals.IsValid())
1135 Expected<PythonObject> return_value =
1136 runStringMultiLine(in_string, globals, locals);
1138 if (!return_value) {
1140 llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
1141 llvm::Error error = llvm::createStringError(
1142 llvm::inconvertibleErrorCode(), E.ReadBacktrace());
1143 if (!options.GetMaskoutErrors())
1153void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1154 std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1157 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1158 " ", *
this, &bp_options_vec);
1161void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1164 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1165 " ", *
this, wp_options);
1168Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1173 std::string function_signature = function_name;
1175 llvm::Expected<unsigned> maybe_args =
1176 GetMaxPositionalArgumentsForCallable(function_name);
1178 error.SetErrorStringWithFormat(
1179 "could not get num args: %s",
1180 llvm::toString(maybe_args.takeError()).c_str());
1183 size_t max_args = *maybe_args;
1185 bool uses_extra_args =
false;
1186 if (max_args >= 4) {
1187 uses_extra_args =
true;
1188 function_signature +=
"(frame, bp_loc, extra_args, internal_dict)";
1189 }
else if (max_args >= 3) {
1190 if (extra_args_sp) {
1191 error.SetErrorString(
"cannot pass extra_args to a three argument callback"
1195 uses_extra_args =
false;
1196 function_signature +=
"(frame, bp_loc, internal_dict)";
1198 error.SetErrorStringWithFormat(
"expected 3 or 4 argument "
1199 "function, %s can only take %zu",
1200 function_name, max_args);
1204 SetBreakpointCommandCallback(bp_options, function_signature.c_str(),
1205 extra_args_sp, uses_extra_args,
1210Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1212 std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
1214 error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1215 cmd_data_up->script_source,
1222 std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1224 ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1228Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1231 return SetBreakpointCommandCallback(bp_options, command_body_text, {},
1232 false, is_callback);
1236Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1240 auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1246 data_up->user_source.SplitIntoLines(command_body_text);
1247 Status error = GenerateBreakpointCommandCallbackData(
1248 data_up->user_source, data_up->script_source, uses_extra_args,
1250 if (
error.Success()) {
1252 std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1254 ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1261void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1264 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
1271 data_up->user_source.AppendString(user_input);
1272 data_up->script_source.assign(user_input);
1274 if (GenerateWatchpointCommandCallbackData(
1275 data_up->user_source, data_up->script_source, is_callback)) {
1277 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
1279 ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
1283Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1286 std::string function_def_string(function_def.
CopyList());
1289 function_def_string.c_str(),
1294Status ScriptInterpreterPythonImpl::GenerateFunction(
const char *signature,
1298 int num_lines = input.
GetSize();
1299 if (num_lines == 0) {
1300 error.SetErrorString(
"No input data.");
1304 if (!signature || *signature == 0) {
1305 error.SetErrorString(
"No output function name.");
1313 " global_dict = globals()");
1315 " new_keys = internal_dict.keys()");
1318 " old_keys = global_dict.keys()");
1320 " global_dict.update(internal_dict)");
1327 if (num_lines == 1) {
1332 return Status(
"ScriptInterpreterPythonImpl::GenerateFunction(is_callback="
1333 "true) = ERROR: python function is multiline.");
1337 " __return_val = None");
1339 " def __user_code():");
1343 for (
int i = 0; i < num_lines; ++i) {
1349 " __return_val = __user_code()");
1353 " for key in new_keys:");
1356 " internal_dict[key] = global_dict[key]");
1359 " if key not in old_keys:");
1362 " del global_dict[key]");
1365 " return __return_val");
1368 error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
1373bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1374 StringList &user_input, std::string &output,
const void *name_token) {
1375 static uint32_t num_created_functions = 0;
1380 if (user_input.
GetSize() == 0)
1386 std::string auto_generated_function_name(
1387 GenerateUniqueName(
"lldb_autogen_python_type_print_func",
1388 num_created_functions, name_token));
1389 sstr.
Printf(
"def %s (valobj, internal_dict):",
1390 auto_generated_function_name.c_str());
1392 if (!GenerateFunction(sstr.
GetData(), user_input,
false)
1397 output.assign(auto_generated_function_name);
1401bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1402 StringList &user_input, std::string &output) {
1403 static uint32_t num_created_functions = 0;
1408 if (user_input.
GetSize() == 0)
1411 std::string auto_generated_function_name(GenerateUniqueName(
1412 "lldb_autogen_python_cmd_alias_func", num_created_functions));
1414 sstr.
Printf(
"def %s (debugger, args, exe_ctx, result, internal_dict):",
1415 auto_generated_function_name.c_str());
1417 if (!GenerateFunction(sstr.
GetData(), user_input,
false)
1422 output.assign(auto_generated_function_name);
1426bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1427 StringList &user_input, std::string &output,
const void *name_token) {
1428 static uint32_t num_created_classes = 0;
1430 int num_lines = user_input.
GetSize();
1434 if (user_input.
GetSize() == 0)
1439 std::string auto_generated_class_name(GenerateUniqueName(
1440 "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1446 sstr.
Printf(
"class %s:", auto_generated_class_name.c_str());
1452 for (
int i = 0; i < num_lines; ++i) {
1461 if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).
Success())
1466 output.assign(auto_generated_class_name);
1471ScriptInterpreterPythonImpl::CreateFrameRecognizer(
const char *class_name) {
1472 if (class_name ==
nullptr || class_name[0] ==
'\0')
1475 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1476 PythonObject ret_val = SWIGBridge::LLDBSWIGPython_CreateFrameRecognizer(
1477 class_name, m_dictionary_name.c_str());
1480 new StructuredPythonObject(std::move(ret_val)));
1486 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1488 if (!os_plugin_object_sp)
1495 PythonObject implementor(PyRefType::Borrowed,
1496 (PyObject *)generic->GetValue());
1498 if (!implementor.IsAllocated())
1501 PythonObject py_return(PyRefType::Owned,
1502 SWIGBridge::LLDBSwigPython_GetRecognizedArguments(
1503 implementor.get(), frame_sp));
1506 if (PyErr_Occurred()) {
1510 if (py_return.get()) {
1511 PythonList result_list(PyRefType::Borrowed, py_return.get());
1513 for (
size_t i = 0; i < result_list.GetSize(); i++) {
1514 PyObject *item = result_list.GetItemAtIndex(i).get();
1516 (
lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
1518 SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
1520 result->Append(valobj_sp);
1527bool ScriptInterpreterPythonImpl::ShouldHide(
1530 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1532 if (!os_plugin_object_sp)
1539 PythonObject implementor(PyRefType::Borrowed,
1540 (PyObject *)generic->GetValue());
1542 if (!implementor.IsAllocated())
1546 SWIGBridge::LLDBSwigPython_ShouldHide(implementor.get(), frame_sp);
1549 if (PyErr_Occurred()) {
1557ScriptInterpreterPythonImpl::CreateScriptedProcessInterface() {
1558 return std::make_unique<ScriptedProcessPythonInterface>(*
this);
1562ScriptInterpreterPythonImpl::CreateScriptedThreadInterface() {
1563 return std::make_shared<ScriptedThreadPythonInterface>(*
this);
1567ScriptInterpreterPythonImpl::CreateScriptedThreadPlanInterface() {
1568 return std::make_shared<ScriptedThreadPlanPythonInterface>(*
this);
1572ScriptInterpreterPythonImpl::CreateOperatingSystemInterface() {
1573 return std::make_shared<OperatingSystemPythonInterface>(*
this);
1577ScriptInterpreterPythonImpl::CreateStructuredDataFromScriptObject(
1579 void *ptr =
const_cast<void *
>(obj.
GetPointer());
1580 PythonObject py_obj(PyRefType::Borrowed,
static_cast<PyObject *
>(ptr));
1581 if (!py_obj.IsValid() || py_obj.IsNone())
1583 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1584 return py_obj.CreateStructuredObject();
1588ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
1592 if (class_name ==
nullptr || class_name[0] ==
'\0')
1598 Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
1599 ScriptInterpreterPythonImpl *python_interpreter =
1600 GetPythonInterpreter(debugger);
1602 if (!python_interpreter)
1605 Locker py_lock(
this,
1606 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1608 PythonObject ret_val =
1609 SWIGBridge::LLDBSwigPythonCreateScriptedBreakpointResolver(
1610 class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
1614 new StructuredPythonObject(std::move(ret_val)));
1617bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
1619 bool should_continue =
false;
1621 if (implementor_sp) {
1622 Locker py_lock(
this,
1623 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1624 should_continue = SWIGBridge::LLDBSwigPythonCallBreakpointResolver(
1625 implementor_sp->GetValue(),
"__callback__", sym_ctx);
1626 if (PyErr_Occurred()) {
1631 return should_continue;
1635ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
1638 if (implementor_sp) {
1639 Locker py_lock(
this,
1640 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1641 depth_as_int = SWIGBridge::LLDBSwigPythonCallBreakpointResolver(
1642 implementor_sp->GetValue(),
"__get_depth__",
nullptr);
1643 if (PyErr_Occurred()) {
1657 TargetSP target_sp,
const char *class_name,
1661 error.SetErrorString(
"No target for scripted stop-hook.");
1665 if (class_name ==
nullptr || class_name[0] ==
'\0') {
1666 error.SetErrorString(
"No class name for scripted stop-hook.");
1670 ScriptInterpreterPythonImpl *python_interpreter =
1671 GetPythonInterpreter(m_debugger);
1673 if (!python_interpreter) {
1674 error.SetErrorString(
"No script interpreter for scripted stop-hook.");
1678 Locker py_lock(
this,
1679 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1681 PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateScriptedStopHook(
1682 target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
1686 new StructuredPythonObject(std::move(ret_val)));
1689bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
1692 assert(implementor_sp &&
1693 "can't call a stop hook with an invalid implementor");
1694 assert(stream_sp &&
"can't call a stop hook with an invalid stream");
1696 Locker py_lock(
this,
1697 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1701 bool ret_val = SWIGBridge::LLDBSwigPythonStopHookCallHandleStop(
1702 implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
1707ScriptInterpreterPythonImpl::LoadPluginModule(
const FileSpec &file_spec,
1709 if (!FileSystem::Instance().Exists(file_spec)) {
1710 error.SetErrorString(
"no such file");
1718 if (LoadScriptingModule(file_spec.
GetPath().c_str(), load_script_options,
1728 if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
1734 Locker py_lock(
this,
1735 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1736 TargetSP target_sp(target->shared_from_this());
1738 auto setting = (PyObject *)SWIGBridge::LLDBSWIGPython_GetDynamicSetting(
1739 generic->GetValue(), setting_name, target_sp);
1744 PythonDictionary py_dict =
1745 unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
1750 return py_dict.CreateStructuredDictionary();
1754ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
1756 if (class_name ==
nullptr || class_name[0] ==
'\0')
1763 Target *target = exe_ctx.GetTargetPtr();
1769 ScriptInterpreterPythonImpl *python_interpreter =
1770 GetPythonInterpreter(debugger);
1772 if (!python_interpreter)
1775 Locker py_lock(
this,
1776 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1777 PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateSyntheticProvider(
1778 class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
1781 new StructuredPythonObject(std::move(ret_val)));
1785ScriptInterpreterPythonImpl::CreateScriptCommandObject(
const char *class_name) {
1786 DebuggerSP debugger_sp(m_debugger.shared_from_this());
1788 if (class_name ==
nullptr || class_name[0] ==
'\0')
1791 if (!debugger_sp.get())
1794 Locker py_lock(
this,
1795 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1796 PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateCommandObject(
1797 class_name, m_dictionary_name.c_str(), debugger_sp);
1799 if (ret_val.IsValid())
1801 new StructuredPythonObject(std::move(ret_val)));
1806bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1807 const char *oneliner, std::string &output,
const void *name_token) {
1810 return GenerateTypeScriptFunction(input, output, name_token);
1813bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1814 const char *oneliner, std::string &output,
const void *name_token) {
1817 return GenerateTypeSynthClass(input, output, name_token);
1820Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
1821 StringList &user_input, std::string &output,
bool has_extra_args,
1823 static uint32_t num_created_functions = 0;
1827 if (user_input.
GetSize() == 0) {
1828 error.SetErrorString(
"No input data.");
1832 std::string auto_generated_function_name(GenerateUniqueName(
1833 "lldb_autogen_python_bp_callback_func_", num_created_functions));
1835 sstr.
Printf(
"def %s (frame, bp_loc, extra_args, internal_dict):",
1836 auto_generated_function_name.c_str());
1838 sstr.
Printf(
"def %s (frame, bp_loc, internal_dict):",
1839 auto_generated_function_name.c_str());
1841 error = GenerateFunction(sstr.
GetData(), user_input, is_callback);
1842 if (!
error.Success())
1846 output.assign(auto_generated_function_name);
1850bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
1851 StringList &user_input, std::string &output,
bool is_callback) {
1852 static uint32_t num_created_functions = 0;
1856 if (user_input.
GetSize() == 0)
1859 std::string auto_generated_function_name(GenerateUniqueName(
1860 "lldb_autogen_python_wp_callback_func_", num_created_functions));
1861 sstr.
Printf(
"def %s (frame, wp, internal_dict):",
1862 auto_generated_function_name.c_str());
1864 if (!GenerateFunction(sstr.
GetData(), user_input, is_callback).Success())
1868 output.assign(auto_generated_function_name);
1872bool ScriptInterpreterPythonImpl::GetScriptedSummary(
1879 if (!valobj.get()) {
1880 retval.assign(
"<no object>");
1884 void *old_callee =
nullptr;
1886 if (callee_wrapper_sp) {
1891 void *new_callee = old_callee;
1894 if (python_function_name && *python_function_name) {
1896 Locker py_lock(
this, Locker::AcquireLock | Locker::InitSession |
1902 Timer scoped_timer(func_cat,
"LLDBSwigPythonCallTypeScript");
1903 ret_val = SWIGBridge::LLDBSwigPythonCallTypeScript(
1904 python_function_name, GetSessionDictionary().get(), valobj,
1905 &new_callee, options_sp, retval);
1909 retval.assign(
"<no function name>");
1913 if (new_callee && old_callee != new_callee) {
1914 Locker py_lock(
this,
1915 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1916 callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
1917 PythonObject(PyRefType::Borrowed,
static_cast<PyObject *
>(new_callee)));
1923bool ScriptInterpreterPythonImpl::FormatterCallbackFunction(
1924 const char *python_function_name,
TypeImplSP type_impl_sp) {
1925 Locker py_lock(
this,
1926 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1927 return SWIGBridge::LLDBSwigPythonFormatterCallbackFunction(
1928 python_function_name, m_dictionary_name.c_str(), type_impl_sp);
1931bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
1934 CommandDataPython *bp_option_data = (CommandDataPython *)baton;
1935 const char *python_function_name = bp_option_data->script_source.c_str();
1941 Target *target = exe_ctx.GetTargetPtr();
1947 ScriptInterpreterPythonImpl *python_interpreter =
1948 GetPythonInterpreter(debugger);
1950 if (!python_interpreter)
1953 if (python_function_name && python_function_name[0]) {
1954 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
1956 if (breakpoint_sp) {
1958 breakpoint_sp->FindLocationByID(break_loc_id));
1960 if (stop_frame_sp && bp_loc_sp) {
1961 bool ret_val =
true;
1963 Locker py_lock(python_interpreter, Locker::AcquireLock |
1964 Locker::InitSession |
1966 Expected<bool> maybe_ret_val =
1967 SWIGBridge::LLDBSwigPythonBreakpointCallbackFunction(
1968 python_function_name,
1969 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
1970 bp_loc_sp, bp_option_data->m_extra_args);
1972 if (!maybe_ret_val) {
1974 llvm::handleAllErrors(
1975 maybe_ret_val.takeError(),
1976 [&](PythonException &E) {
1977 debugger.GetErrorStream() << E.ReadBacktrace();
1979 [&](
const llvm::ErrorInfoBase &E) {
1980 debugger.GetErrorStream() << E.message();
1984 ret_val = maybe_ret_val.get();
1996bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
2000 const char *python_function_name = wp_option_data->
script_source.c_str();
2006 Target *target = exe_ctx.GetTargetPtr();
2012 ScriptInterpreterPythonImpl *python_interpreter =
2013 GetPythonInterpreter(debugger);
2015 if (!python_interpreter)
2018 if (python_function_name && python_function_name[0]) {
2019 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2022 if (stop_frame_sp && wp_sp) {
2023 bool ret_val =
true;
2025 Locker py_lock(python_interpreter, Locker::AcquireLock |
2026 Locker::InitSession |
2028 ret_val = SWIGBridge::LLDBSwigPythonWatchpointCallbackFunction(
2029 python_function_name,
2030 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2042size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2044 if (!implementor_sp)
2049 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2056 Locker py_lock(
this,
2057 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2058 ret_val = SWIGBridge::LLDBSwigPython_CalculateNumChildren(implementor, max);
2066 if (!implementor_sp)
2072 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2078 Locker py_lock(
this,
2079 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2080 PyObject *child_ptr =
2081 SWIGBridge::LLDBSwigPython_GetChildAtIndex(implementor, idx);
2082 if (child_ptr !=
nullptr && child_ptr != Py_None) {
2084 (
lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2085 if (sb_value_ptr ==
nullptr)
2086 Py_XDECREF(child_ptr);
2088 ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
2091 Py_XDECREF(child_ptr);
2098int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2100 if (!implementor_sp)
2106 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2113 Locker py_lock(
this,
2114 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2115 ret_val = SWIGBridge::LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
2121bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2123 bool ret_val =
false;
2125 if (!implementor_sp)
2131 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2136 Locker py_lock(
this,
2137 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2139 SWIGBridge::LLDBSwigPython_UpdateSynthProviderInstance(implementor);
2145bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2147 bool ret_val =
false;
2149 if (!implementor_sp)
2155 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2160 Locker py_lock(
this,
2161 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2162 ret_val = SWIGBridge::LLDBSwigPython_MightHaveChildrenSynthProviderInstance(
2173 if (!implementor_sp)
2179 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2184 Locker py_lock(
this,
2185 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2186 PyObject *child_ptr =
2187 SWIGBridge::LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2188 if (child_ptr !=
nullptr && child_ptr != Py_None) {
2190 (
lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2191 if (sb_value_ptr ==
nullptr)
2192 Py_XDECREF(child_ptr);
2194 ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
2197 Py_XDECREF(child_ptr);
2204ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2206 Locker py_lock(
this,
2207 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2209 if (!implementor_sp)
2216 PythonObject implementor(PyRefType::Borrowed,
2217 (PyObject *)generic->GetValue());
2218 if (!implementor.IsAllocated())
2221 llvm::Expected<PythonObject> expected_py_return =
2222 implementor.CallMethod(
"get_type_name");
2224 if (!expected_py_return) {
2225 llvm::consumeError(expected_py_return.takeError());
2229 PythonObject py_return = std::move(expected_py_return.get());
2230 if (!py_return.IsAllocated() || !PythonString::Check(py_return.get()))
2233 PythonString type_name(PyRefType::Borrowed, py_return.get());
2237bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2238 const char *impl_function,
Process *process, std::string &output,
2242 error.SetErrorString(
"no process");
2245 if (!impl_function || !impl_function[0]) {
2246 error.SetErrorString(
"no function to execute");
2251 Locker py_lock(
this,
2252 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2253 ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordProcess(
2254 impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
2257 error.SetErrorString(
"python script evaluation failed");
2262bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2263 const char *impl_function,
Thread *thread, std::string &output,
2266 error.SetErrorString(
"no thread");
2269 if (!impl_function || !impl_function[0]) {
2270 error.SetErrorString(
"no function to execute");
2274 Locker py_lock(
this,
2275 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2276 if (std::optional<std::string> result =
2277 SWIGBridge::LLDBSWIGPythonRunScriptKeywordThread(
2278 impl_function, m_dictionary_name.c_str(),
2279 thread->shared_from_this())) {
2280 output = std::move(*result);
2283 error.SetErrorString(
"python script evaluation failed");
2287bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2288 const char *impl_function,
Target *target, std::string &output,
2292 error.SetErrorString(
"no thread");
2295 if (!impl_function || !impl_function[0]) {
2296 error.SetErrorString(
"no function to execute");
2301 TargetSP target_sp(target->shared_from_this());
2302 Locker py_lock(
this,
2303 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2304 ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordTarget(
2305 impl_function, m_dictionary_name.c_str(), target_sp, output);
2307 error.SetErrorString(
"python script evaluation failed");
2312bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2313 const char *impl_function,
StackFrame *frame, std::string &output,
2316 error.SetErrorString(
"no frame");
2319 if (!impl_function || !impl_function[0]) {
2320 error.SetErrorString(
"no function to execute");
2324 Locker py_lock(
this,
2325 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2326 if (std::optional<std::string> result =
2327 SWIGBridge::LLDBSWIGPythonRunScriptKeywordFrame(
2328 impl_function, m_dictionary_name.c_str(),
2329 frame->shared_from_this())) {
2330 output = std::move(*result);
2333 error.SetErrorString(
"python script evaluation failed");
2337bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2338 const char *impl_function,
ValueObject *value, std::string &output,
2342 error.SetErrorString(
"no value");
2345 if (!impl_function || !impl_function[0]) {
2346 error.SetErrorString(
"no function to execute");
2351 Locker py_lock(
this,
2352 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2353 ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordValue(
2354 impl_function, m_dictionary_name.c_str(), value->
GetSP(), output);
2356 error.SetErrorString(
"python script evaluation failed");
2361uint64_t replace_all(std::string &str,
const std::string &oldStr,
2362 const std::string &newStr) {
2364 uint64_t matches = 0;
2365 while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2367 str.replace(pos, oldStr.length(), newStr);
2368 pos += newStr.length();
2373bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2377 namespace fs = llvm::sys::fs;
2378 namespace path = llvm::sys::path;
2384 if (!pathname || !pathname[0]) {
2385 error.SetErrorString(
"empty path");
2389 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2390 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2393 if (!io_redirect_or_error) {
2394 error = io_redirect_or_error.takeError();
2401 Locker py_lock(
this,
2402 Locker::AcquireLock |
2405 Locker::FreeAcquiredLock |
2410 auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2411 if (directory.empty()) {
2412 return llvm::createStringError(
"invalid directory name");
2415 replace_all(directory,
"\\",
"\\\\");
2416 replace_all(directory,
"'",
"\\'");
2420 command_stream.
Printf(
"if not (sys.path.__contains__('%s')):\n "
2421 "sys.path.insert(1,'%s');\n\n",
2422 directory.c_str(), directory.c_str());
2423 bool syspath_retval =
2424 ExecuteMultipleLines(command_stream.
GetData(), exc_options).Success();
2425 if (!syspath_retval)
2426 return llvm::createStringError(
"Python sys.path handling failed");
2428 return llvm::Error::success();
2431 std::string module_name(pathname);
2432 bool possible_package =
false;
2434 if (extra_search_dir) {
2435 if (llvm::Error e = ExtendSysPath(extra_search_dir.
GetPath())) {
2436 error = std::move(e);
2441 FileSystem::Instance().Resolve(module_file);
2444 std::error_code ec = status(module_file.GetPath(), st);
2446 if (ec || st.type() == fs::file_type::status_error ||
2447 st.type() == fs::file_type::type_unknown ||
2448 st.type() == fs::file_type::file_not_found) {
2451 if (strchr(pathname,
'\\') || strchr(pathname,
'/')) {
2452 error.SetErrorStringWithFormatv(
"invalid pathname '{0}'", pathname);
2456 possible_package =
true;
2457 }
else if (is_directory(st) || is_regular_file(st)) {
2458 if (module_file.GetDirectory().IsEmpty()) {
2459 error.SetErrorStringWithFormatv(
"invalid directory name '{0}'", pathname);
2463 ExtendSysPath(module_file.GetDirectory().GetCString())) {
2464 error = std::move(e);
2467 module_name = module_file.GetFilename().GetCString();
2469 error.SetErrorString(
"no known way to import this module specification");
2475 llvm::StringRef extension = llvm::sys::path::extension(module_name);
2476 if (!extension.empty()) {
2477 if (extension ==
".py")
2478 module_name.resize(module_name.length() - 3);
2479 else if (extension ==
".pyc")
2480 module_name.resize(module_name.length() - 4);
2483 if (!possible_package && module_name.find(
'.') != llvm::StringRef::npos) {
2484 error.SetErrorStringWithFormat(
2485 "Python does not allow dots in module names: %s", module_name.c_str());
2489 if (module_name.find(
'-') != llvm::StringRef::npos) {
2490 error.SetErrorStringWithFormat(
2491 "Python discourages dashes in module names: %s", module_name.c_str());
2497 command_stream.
Clear();
2498 command_stream.
Printf(
"sys.modules.__contains__('%s')", module_name.c_str());
2499 bool does_contain =
false;
2502 const bool does_contain_executed = ExecuteOneLineWithReturn(
2504 ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options);
2506 const bool was_imported_globally = does_contain_executed && does_contain;
2507 const bool was_imported_locally =
2508 GetSessionDictionary()
2509 .GetItemForKey(PythonString(module_name))
2513 command_stream.
Clear();
2515 if (was_imported_globally || was_imported_locally) {
2516 if (!was_imported_locally)
2517 command_stream.
Printf(
"import %s ; reload_module(%s)",
2518 module_name.c_str(), module_name.c_str());
2520 command_stream.
Printf(
"reload_module(%s)", module_name.c_str());
2522 command_stream.
Printf(
"import %s", module_name.c_str());
2524 error = ExecuteMultipleLines(command_stream.
GetData(), exc_options);
2530 if (!SWIGBridge::LLDBSwigPythonCallModuleInit(
2531 module_name.c_str(), m_dictionary_name.c_str(),
2532 m_debugger.shared_from_this())) {
2533 error.SetErrorString(
"calling __lldb_init_module failed");
2539 command_stream.
Clear();
2540 command_stream.
Printf(
"%s", module_name.c_str());
2541 void *module_pyobj =
nullptr;
2542 if (ExecuteOneLineWithReturn(
2544 ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2547 *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2548 PyRefType::Owned,
static_cast<PyObject *
>(module_pyobj)));
2554bool ScriptInterpreterPythonImpl::IsReservedWord(
const char *word) {
2555 if (!word || !word[0])
2558 llvm::StringRef word_sr(word);
2562 if (word_sr.find(
'"') != llvm::StringRef::npos ||
2563 word_sr.find(
'\'') != llvm::StringRef::npos)
2567 command_stream.
Printf(
"keyword.iskeyword('%s')", word);
2573 if (ExecuteOneLineWithReturn(command_stream.
GetData(),
2574 ScriptInterpreter::eScriptReturnTypeBool,
2580ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2582 : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2583 m_old_asynch(debugger_sp->GetAsyncExecution()) {
2584 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2585 m_debugger_sp->SetAsyncExecution(
false);
2586 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2587 m_debugger_sp->SetAsyncExecution(
true);
2590ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
2591 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2592 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2595bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2596 const char *impl_function, llvm::StringRef args,
2600 if (!impl_function) {
2601 error.SetErrorString(
"no function to execute");
2608 if (!debugger_sp.get()) {
2609 error.SetErrorString(
"invalid Debugger pointer");
2613 bool ret_val =
false;
2615 std::string err_msg;
2618 Locker py_lock(
this,
2619 Locker::AcquireLock | Locker::InitSession |
2621 Locker::FreeLock | Locker::TearDownSession);
2623 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2625 std::string args_str = args.str();
2626 ret_val = SWIGBridge::LLDBSwigPythonCallCommand(
2627 impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2628 cmd_retobj, exe_ctx_ref_sp);
2632 error.SetErrorString(
"unable to execute script function");
2633 else if (cmd_retobj.
GetStatus() == eReturnStatusFailed)
2640bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2645 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2646 error.SetErrorString(
"no function to execute");
2653 if (!debugger_sp.get()) {
2654 error.SetErrorString(
"invalid Debugger pointer");
2658 bool ret_val =
false;
2660 std::string err_msg;
2663 Locker py_lock(
this,
2664 Locker::AcquireLock | Locker::InitSession |
2666 Locker::FreeLock | Locker::TearDownSession);
2668 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2670 std::string args_str = args.str();
2671 ret_val = SWIGBridge::LLDBSwigPythonCallCommandObject(
2672 static_cast<PyObject *
>(impl_obj_sp->GetValue()), debugger_sp,
2673 args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
2677 error.SetErrorString(
"unable to execute script function");
2678 else if (cmd_retobj.
GetStatus() == eReturnStatusFailed)
2685bool ScriptInterpreterPythonImpl::RunScriptBasedParsedCommand(
2690 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2691 error.SetErrorString(
"no function to execute");
2698 if (!debugger_sp.get()) {
2699 error.SetErrorString(
"invalid Debugger pointer");
2703 bool ret_val =
false;
2705 std::string err_msg;
2708 Locker py_lock(
this,
2709 Locker::AcquireLock | Locker::InitSession |
2711 Locker::FreeLock | Locker::TearDownSession);
2713 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2718 args_arr_sp->AddStringItem(entry.ref());
2722 ret_val = SWIGBridge::LLDBSwigPythonCallParsedCommandObject(
2723 static_cast<PyObject *
>(impl_obj_sp->GetValue()), debugger_sp,
2724 args_impl, cmd_retobj, exe_ctx_ref_sp);
2728 error.SetErrorString(
"unable to execute script function");
2729 else if (cmd_retobj.
GetStatus() == eReturnStatusFailed)
2736std::optional<std::string>
2737ScriptInterpreterPythonImpl::GetRepeatCommandForScriptedCommand(
2739 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2740 return std::nullopt;
2744 if (!debugger_sp.get())
2745 return std::nullopt;
2747 std::optional<std::string> ret_val;
2750 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN,
2756 std::string command;
2758 ret_val = SWIGBridge::LLDBSwigPythonGetRepeatCommandForScriptedCommand(
2759 static_cast<PyObject *
>(impl_obj_sp->GetValue()), command);
2767bool ScriptInterpreterPythonImpl::GetDocumentationForItem(
const char *item,
2768 std::string &dest) {
2771 if (!item || !*item)
2774 std::string command(item);
2775 command +=
".__doc__";
2779 char *result_ptr =
nullptr;
2781 if (ExecuteOneLineWithReturn(
2782 command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
2786 dest.assign(result_ptr);
2791 str_stream <<
"Function " << item
2792 <<
" was not found. Containing module might be missing.";
2793 dest = std::string(str_stream.
GetString());
2798bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
2802 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2807 PythonObject implementor(PyRefType::Borrowed,
2808 (PyObject *)cmd_obj_sp->GetValue());
2810 if (!implementor.IsAllocated())
2813 llvm::Expected<PythonObject> expected_py_return =
2814 implementor.CallMethod(
"get_short_help");
2816 if (!expected_py_return) {
2817 llvm::consumeError(expected_py_return.takeError());
2821 PythonObject py_return = std::move(expected_py_return.get());
2823 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2824 PythonString py_string(PyRefType::Borrowed, py_return.get());
2825 llvm::StringRef return_data(py_string.GetString());
2826 dest.assign(return_data.data(), return_data.size());
2833uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
2835 uint32_t result = 0;
2837 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2839 static char callee_name[] =
"get_flags";
2844 PythonObject implementor(PyRefType::Borrowed,
2845 (PyObject *)cmd_obj_sp->GetValue());
2847 if (!implementor.IsAllocated())
2850 PythonObject pmeth(PyRefType::Owned,
2851 PyObject_GetAttrString(implementor.get(), callee_name));
2853 if (PyErr_Occurred())
2856 if (!pmeth.IsAllocated())
2859 if (PyCallable_Check(pmeth.get()) == 0) {
2860 if (PyErr_Occurred())
2865 if (PyErr_Occurred())
2868 long long py_return = unwrapOrSetPythonException(
2869 As<long long>(implementor.CallMethod(callee_name)));
2872 if (PyErr_Occurred()) {
2883ScriptInterpreterPythonImpl::GetOptionsForCommandObject(
2887 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2889 static char callee_name[] =
"get_options_definition";
2894 PythonObject implementor(PyRefType::Borrowed,
2895 (PyObject *)cmd_obj_sp->GetValue());
2897 if (!implementor.IsAllocated())
2900 PythonObject pmeth(PyRefType::Owned,
2901 PyObject_GetAttrString(implementor.get(), callee_name));
2903 if (PyErr_Occurred())
2906 if (!pmeth.IsAllocated())
2909 if (PyCallable_Check(pmeth.get()) == 0) {
2910 if (PyErr_Occurred())
2915 if (PyErr_Occurred())
2918 PythonDictionary py_return = unwrapOrSetPythonException(
2919 As<PythonDictionary>(implementor.CallMethod(callee_name)));
2922 if (PyErr_Occurred()) {
2927 return py_return.CreateStructuredObject();
2931ScriptInterpreterPythonImpl::GetArgumentsForCommandObject(
2935 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2937 static char callee_name[] =
"get_args_definition";
2942 PythonObject implementor(PyRefType::Borrowed,
2943 (PyObject *)cmd_obj_sp->GetValue());
2945 if (!implementor.IsAllocated())
2948 PythonObject pmeth(PyRefType::Owned,
2949 PyObject_GetAttrString(implementor.get(), callee_name));
2951 if (PyErr_Occurred())
2954 if (!pmeth.IsAllocated())
2957 if (PyCallable_Check(pmeth.get()) == 0) {
2958 if (PyErr_Occurred())
2963 if (PyErr_Occurred())
2966 PythonList py_return = unwrapOrSetPythonException(
2967 As<PythonList>(implementor.CallMethod(callee_name)));
2970 if (PyErr_Occurred()) {
2975 return py_return.CreateStructuredObject();
2979ScriptInterpreterPythonImpl::OptionParsingStartedForCommandObject(
2982 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2984 static char callee_name[] =
"option_parsing_started";
2989 PythonObject implementor(PyRefType::Borrowed,
2990 (PyObject *)cmd_obj_sp->GetValue());
2992 if (!implementor.IsAllocated())
2995 PythonObject pmeth(PyRefType::Owned,
2996 PyObject_GetAttrString(implementor.get(), callee_name));
2998 if (PyErr_Occurred())
3001 if (!pmeth.IsAllocated())
3004 if (PyCallable_Check(pmeth.get()) == 0) {
3005 if (PyErr_Occurred())
3010 if (PyErr_Occurred())
3015 unwrapOrSetPythonException(
3016 As<bool>(implementor.CallMethod(callee_name)));
3019 if (PyErr_Occurred()) {
3027ScriptInterpreterPythonImpl::SetOptionValueForCommandObject(
3029 llvm::StringRef long_option, llvm::StringRef value) {
3032 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3034 static char callee_name[] =
"set_option_value";
3039 PythonObject implementor(PyRefType::Borrowed,
3040 (PyObject *)cmd_obj_sp->GetValue());
3042 if (!implementor.IsAllocated())
3045 PythonObject pmeth(PyRefType::Owned,
3046 PyObject_GetAttrString(implementor.get(), callee_name));
3048 if (PyErr_Occurred())
3051 if (!pmeth.IsAllocated())
3054 if (PyCallable_Check(pmeth.get()) == 0) {
3055 if (PyErr_Occurred())
3060 if (PyErr_Occurred())
3066 PythonObject ctx_ref_obj = SWIGBridge::ToSWIGWrapper(exe_ctx_ref_sp);
3068 bool py_return = unwrapOrSetPythonException(
3069 As<bool>(implementor.CallMethod(callee_name, ctx_ref_obj, long_option.str().c_str(),
3070 value.str().c_str())));
3073 if (PyErr_Occurred()) {
3081bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3085 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3090 PythonObject implementor(PyRefType::Borrowed,
3091 (PyObject *)cmd_obj_sp->GetValue());
3093 if (!implementor.IsAllocated())
3096 llvm::Expected<PythonObject> expected_py_return =
3097 implementor.CallMethod(
"get_long_help");
3099 if (!expected_py_return) {
3100 llvm::consumeError(expected_py_return.takeError());
3104 PythonObject py_return = std::move(expected_py_return.get());
3106 bool got_string =
false;
3107 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3108 PythonString str(PyRefType::Borrowed, py_return.get());
3109 llvm::StringRef str_data(str.GetString());
3110 dest.assign(str_data.data(), str_data.size());
3117std::unique_ptr<ScriptInterpreterLocker>
3118ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3119 std::unique_ptr<ScriptInterpreterLocker> py_lock(
new Locker(
3120 this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3121 Locker::FreeLock | Locker::TearDownSession));
3125void ScriptInterpreterPythonImpl::Initialize() {
3132 InitializePythonRAII initialize_guard;
3139 PyRun_SimpleString(
"import sys");
3140 AddToSysPath(AddLocation::End,
".");
3146 if (
FileSpec file_spec = GetPythonDir())
3147 AddToSysPath(AddLocation::Beginning, file_spec.
GetPath(
false));
3148 if (
FileSpec file_spec = HostInfo::GetShlibDir())
3149 AddToSysPath(AddLocation::Beginning, file_spec.
GetPath(
false));
3151 PyRun_SimpleString(
"sys.dont_write_bytecode = 1; import "
3152 "lldb.embedded_interpreter; from "
3153 "lldb.embedded_interpreter import run_python_interpreter; "
3154 "from lldb.embedded_interpreter import run_one_line");
3156#if LLDB_USE_PYTHON_SET_INTERRUPT
3160 RestoreSignalHandlerScope save_sigint(SIGINT);
3166 PyRun_SimpleString(
"def lldb_setup_sigint_handler():\n"
3168 " def signal_handler(sig, frame):\n"
3169 " raise KeyboardInterrupt()\n"
3170 " signal.signal(signal.SIGINT, signal_handler);\n"
3171 "lldb_setup_sigint_handler();\n"
3172 "del lldb_setup_sigint_handler\n");
3176void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3178 std::string path_copy;
3180 std::string statement;
3181 if (location == AddLocation::Beginning) {
3182 statement.assign(
"sys.path.insert(0,\"");
3183 statement.append(path);
3184 statement.append(
"\")");
3186 statement.assign(
"sys.path.append(\"");
3187 statement.append(path);
3188 statement.append(
"\")");
3190 PyRun_SimpleString(statement.c_str());
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOGF(log,...)
#define LLDB_LOGV(log,...)
#define LLDB_PLUGIN_DEFINE(PluginName)
#define LLDB_SCOPED_TIMER()
A command line argument class.
bool GetQuotedCommandString(std::string &command) const
"lldb/Breakpoint/BreakpointOptions.h" Class that manages the options on a breakpoint or breakpoint lo...
void SetCallback(BreakpointHitCallback callback, const lldb::BatonSP &baton_sp, bool synchronous=false)
Adds a callback to the breakpoint option set.
void AppendErrorWithFormatv(const char *format, Args &&... args)
bool GetInteractive() const
void void AppendError(llvm::StringRef in_string)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
lldb::ReturnStatus GetStatus() const
A uniqued constant string class.
A class to manage flag bits.
void RunIOHandlerAsync(const lldb::IOHandlerSP &reader_sp, bool cancel_top_handler=true)
Run the given IO handler and return immediately.
ScriptInterpreter * GetScriptInterpreter(bool can_create=true, std::optional< lldb::ScriptLanguage > language={})
bool GetSetLLDBGlobals() const
bool GetMaskoutErrors() const
ExecuteScriptOptions & SetMaskoutErrors(bool maskout)
ExecuteScriptOptions & SetSetLLDBGlobals(bool set)
ExecuteScriptOptions & SetEnableIO(bool enable)
Execution context objects refer to objects in the execution of the program that is being debugged.
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
void AppendPathComponent(llvm::StringRef component)
void SetDirectory(ConstString directory)
Directory string set accessor.
bool RemoveLastPathComponent()
Removes the last path component by replacing the current path with its parent.
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
llvm::StringRef GetFileNameExtension() const
Extract the extension of the file.
An abstract base class for files.
bool IsValid() const override
IsValid.
virtual Status Flush()
Flush the current stream.
lldb::StreamFileSP GetErrorStreamFileSP()
lldb::StreamFileSP GetOutputStreamFileSP()
bool GetInitSession() const
LoadScriptOptions & SetInitSession(bool b)
LoadScriptOptions & SetSilent(bool b)
void PutCString(const char *cstr)
A plug-in interface definition class for debugging a process.
lldb::FileSP GetOutputFile() const
lldb::FileSP GetErrorFile() const
void Flush()
Flush our output and error file handles.
lldb::FileSP GetInputFile() const
const void * GetPointer() const
This base class provides an interface to stack frames.
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
ExecutionContextRef exe_ctx_ref
const char * GetData() const
llvm::StringRef GetString() const
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
std::string CopyList(const char *item_preamble=nullptr, const char *items_sep="\n") const
size_t SplitIntoLines(const std::string &lines)
void AppendString(const std::string &s)
const char * GetStringAtIndex(size_t idx) const
std::shared_ptr< Generic > GenericSP
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
std::shared_ptr< Array > ArraySP
Defines a symbol context baton that can be handed other debug core functions.
lldb::BreakpointSP GetBreakpointByID(lldb::break_id_t break_id)
WatchpointList & GetWatchpointList()
A timer class that simplifies common timing metrics.
A collection of ValueObject values that.
lldb::ValueObjectSP GetSP()
lldb::WatchpointSP FindByID(lldb::watch_id_t watchID) const
Returns a shared pointer to the watchpoint with id watchID, const version.
"lldb/Breakpoint/WatchpointOptions.h" Class that manages the options on a watchpoint.
void SetCallback(WatchpointHitCallback callback, const lldb::BatonSP &baton_sp, bool synchronous=false)
Adds a callback to the watchpoint option set.
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
ScriptedCommandSynchronicity
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::BreakpointLocation > BreakpointLocationSP
std::shared_ptr< lldb_private::IOHandler > IOHandlerSP
std::shared_ptr< lldb_private::ScriptInterpreter > ScriptInterpreterSP
std::shared_ptr< lldb_private::ScriptedThreadPlanInterface > ScriptedThreadPlanInterfaceSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
std::shared_ptr< lldb_private::TypeSummaryOptions > TypeSummaryOptionsSP
std::shared_ptr< lldb_private::OperatingSystemInterface > OperatingSystemInterfaceSP
std::shared_ptr< lldb_private::Stream > StreamSP
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
std::shared_ptr< lldb_private::ScriptedThreadInterface > ScriptedThreadInterfaceSP
std::shared_ptr< lldb_private::ValueObjectList > ValueObjectListSP
std::shared_ptr< lldb_private::Debugger > DebuggerSP
std::shared_ptr< lldb_private::Watchpoint > WatchpointSP
std::shared_ptr< lldb_private::StreamFile > StreamFileSP
std::shared_ptr< lldb_private::TypeImpl > TypeImplSP
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::File > FileSP
std::unique_ptr< lldb_private::ScriptedProcessInterface > ScriptedProcessInterfaceUP
std::shared_ptr< lldb_private::ExecutionContextRef > ExecutionContextRefSP
std::string script_source