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 PY_VERSION_HEX >= 0x03020000
77static ScriptInterpreterPythonImpl *GetPythonInterpreter(
Debugger &debugger) {
80 return static_cast<ScriptInterpreterPythonImpl *
>(script_interpreter);
91struct InitializePythonRAII {
93 InitializePythonRAII() {
94#if PY_VERSION_HEX >= 0x03080000
96 PyConfig_InitPythonConfig(&config);
99#if LLDB_EMBED_PYTHON_HOME
100 static std::string g_python_home = []() -> std::string {
101 if (llvm::sys::path::is_absolute(LLDB_PYTHON_HOME))
102 return LLDB_PYTHON_HOME;
104 FileSpec spec = HostInfo::GetShlibDir();
110 if (!g_python_home.empty()) {
111#if PY_VERSION_HEX >= 0x03080000
112 PyConfig_SetBytesString(&config, &config.home, g_python_home.c_str());
115 wchar_t *python_home_w = Py_DecodeLocale(g_python_home.c_str(), &size);
116 Py_SetPythonHome(python_home_w);
117 PyMem_RawFree(python_home_w);
124 if (!Py_IsInitialized()) {
125#ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
128 bool ReadlinePatched =
false;
129 for (
auto *p = PyImport_Inittab; p->name !=
nullptr; p++) {
130 if (strcmp(p->name,
"readline") == 0) {
131 p->initfunc = initlldb_readline;
135 if (!ReadlinePatched) {
136 PyImport_AppendInittab(
"readline", initlldb_readline);
137 ReadlinePatched =
true;
142 PyImport_AppendInittab(
"_lldb", LLDBSwigPyInit);
145#if PY_VERSION_HEX >= 0x03080000
146 config.install_signal_handlers = 0;
147 Py_InitializeFromConfig(&config);
148 PyConfig_Clear(&config);
149 InitializeThreadsPrivate();
154#if PY_VERSION_HEX >= 0x03020000
156 InitializeThreadsPrivate();
158 InitializeThreadsPrivate();
164 ~InitializePythonRAII() {
165 if (m_was_already_initialized) {
167 LLDB_LOGV(log,
"Releasing PyGILState. Returning to state = {0}locked",
168 m_gil_state == PyGILState_UNLOCKED ?
"un" :
"");
169 PyGILState_Release(m_gil_state);
177 void InitializeThreadsPrivate() {
184#if PY_VERSION_HEX >= 0x03070000
186 if (PyGILState_Check())
192#if PY_VERSION_HEX < 0x03090000
193 if (PyEval_ThreadsInitialized()) {
199 m_was_already_initialized =
true;
200 m_gil_state = PyGILState_Ensure();
201 LLDB_LOGV(log,
"Ensured PyGILState. Previous state = {0}locked\n",
202 m_gil_state == PyGILState_UNLOCKED ?
"un" :
"");
206#if PY_VERSION_HEX < 0x03090000
211 PyEval_InitThreads();
217 PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
218 bool m_was_already_initialized =
false;
221#if LLDB_USE_PYTHON_SET_INTERRUPT
224struct RestoreSignalHandlerScope {
226 struct sigaction m_prev_handler;
228 RestoreSignalHandlerScope(
int signal_code) : m_signal_code(signal_code) {
230 std::memset(&m_prev_handler, 0,
sizeof(m_prev_handler));
232 struct sigaction *new_handler =
nullptr;
233 int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler);
234 lldbassert(signal_err == 0 &&
"sigaction failed to read handler");
236 ~RestoreSignalHandlerScope() {
237 int signal_err = ::sigaction(m_signal_code, &m_prev_handler,
nullptr);
238 lldbassert(signal_err == 0 &&
"sigaction failed to restore old handler");
244void ScriptInterpreterPython::ComputePythonDirForApple(
246 auto style = llvm::sys::path::Style::posix;
248 llvm::StringRef path_ref(path.begin(), path.size());
249 auto rbegin = llvm::sys::path::rbegin(path_ref, style);
250 auto rend = llvm::sys::path::rend(path_ref);
251 auto framework = std::find(rbegin, rend,
"LLDB.framework");
252 if (framework == rend) {
253 ComputePythonDir(path);
256 path.resize(framework - rend);
257 llvm::sys::path::append(path, style,
"LLDB.framework",
"Resources",
"Python");
260void ScriptInterpreterPython::ComputePythonDir(
265 llvm::sys::path::remove_filename(path);
266 llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
271 std::replace(path.begin(), path.end(),
'\\',
'/');
275FileSpec ScriptInterpreterPython::GetPythonDir() {
277 FileSpec spec = HostInfo::GetShlibDir();
280 llvm::SmallString<64> path;
283#if defined(__APPLE__)
284 ComputePythonDirForApple(path);
286 ComputePythonDir(path);
294static const char GetInterpreterInfoScript[] = R
"(
298def main(lldb_python_dir, python_exe_relative_path):
300 "lldb-pythonpath": lldb_python_dir,
301 "language": "python",
302 "prefix": sys.prefix,
303 "executable": os.path.join(sys.prefix, python_exe_relative_path)
308static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH;
312 FileSpec python_dir_spec = GetPythonDir();
313 if (!python_dir_spec)
315 PythonScript get_info(GetInterpreterInfoScript);
316 auto info_json = unwrapIgnoringErrors(
317 As<PythonDictionary>(get_info(PythonString(python_dir_spec.
GetPath()),
318 PythonString(python_exe_relative_path))));
321 return info_json.CreateStructuredDictionary();
324void ScriptInterpreterPython::SharedLibraryDirectoryHelper(
335 llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
336 for (
auto it = llvm::sys::path::begin(libdir),
337 end = llvm::sys::path::end(libdir);
346 FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
350llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() {
351 return "Embedded Python interpreter";
354void ScriptInterpreterPython::Initialize() {
355 static llvm::once_flag g_once_flag;
356 llvm::call_once(g_once_flag, []() {
357 PluginManager::RegisterPlugin(GetPluginNameStatic(),
358 GetPluginDescriptionStatic(),
360 ScriptInterpreterPythonImpl::CreateInstance);
361 ScriptInterpreterPythonImpl::Initialize();
365void ScriptInterpreterPython::Terminate() {}
367ScriptInterpreterPythonImpl::Locker::Locker(
368 ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
371 m_teardown_session((on_leave & TearDownSession) == TearDownSession),
372 m_python_interpreter(py_interpreter) {
374 if ((on_entry & InitSession) == InitSession) {
375 if (!DoInitSession(on_entry, in, out, err)) {
377 m_teardown_session =
false;
382bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
384 m_GILState = PyGILState_Ensure();
385 LLDB_LOGV(log,
"Ensured PyGILState. Previous state = {0}locked",
386 m_GILState == PyGILState_UNLOCKED ?
"un" :
"");
393 m_python_interpreter->SetThreadState(PyThreadState_Get());
394 m_python_interpreter->IncrementLockCount();
398bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
401 if (!m_python_interpreter)
403 return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
406bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
408 LLDB_LOGV(log,
"Releasing PyGILState. Returning to state = {0}locked",
409 m_GILState == PyGILState_UNLOCKED ?
"un" :
"");
410 PyGILState_Release(m_GILState);
411 m_python_interpreter->DecrementLockCount();
415bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
416 if (!m_python_interpreter)
418 m_python_interpreter->LeaveSession();
422ScriptInterpreterPythonImpl::Locker::~Locker() {
423 if (m_teardown_session)
428ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(
Debugger &debugger)
429 : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
430 m_saved_stderr(), m_main_module(),
431 m_session_dict(PyInitialValue::
Invalid),
432 m_sys_module_dict(PyInitialValue::
Invalid), m_run_one_line_function(),
433 m_run_one_line_str_global(),
434 m_dictionary_name(m_debugger.GetInstanceName()),
436 m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
437 m_command_thread_state(nullptr) {
439 m_dictionary_name.append(
"_dict");
441 run_string.
Printf(
"%s = dict()", m_dictionary_name.c_str());
443 Locker locker(
this, Locker::AcquireLock, Locker::FreeAcquiredLock);
444 PyRun_SimpleString(run_string.
GetData());
448 "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
449 m_dictionary_name.c_str());
450 PyRun_SimpleString(run_string.
GetData());
456 "run_one_line (%s, 'from importlib import reload as reload_module')",
457 m_dictionary_name.c_str());
458 PyRun_SimpleString(run_string.
GetData());
466 "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp')",
467 m_dictionary_name.c_str());
468 PyRun_SimpleString(run_string.
GetData());
471 run_string.
Printf(
"run_one_line (%s, 'import lldb.embedded_interpreter; from "
472 "lldb.embedded_interpreter import run_python_interpreter; "
473 "from lldb.embedded_interpreter import run_one_line')",
474 m_dictionary_name.c_str());
475 PyRun_SimpleString(run_string.
GetData());
478 run_string.
Printf(
"run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
480 m_dictionary_name.c_str(), m_debugger.GetID());
481 PyRun_SimpleString(run_string.
GetData());
484ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
490 auto gil_state = PyGILState_Ensure();
491 m_session_dict.Reset();
492 PyGILState_Release(gil_state);
495void ScriptInterpreterPythonImpl::IOHandlerActivated(
IOHandler &io_handler,
497 const char *instructions =
nullptr;
499 switch (m_active_io_handler) {
503 instructions = R
"(Enter your Python command(s). Type 'DONE' to end.
504def function (frame, bp_loc, internal_dict):
505 """frame: the lldb.SBFrame for the location at which you stopped
506 bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
507 internal_dict: an LLDB support object not to be used"""
511 instructions =
"Enter your Python command(s). Type 'DONE' to end.\n";
517 if (output_sp && interactive) {
518 output_sp->PutCString(instructions);
524void ScriptInterpreterPythonImpl::IOHandlerInputComplete(
IOHandler &io_handler,
527 bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
529 switch (m_active_io_handler) {
533 std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
534 (std::vector<std::reference_wrapper<BreakpointOptions>> *)
538 auto data_up = std::make_unique<CommandDataPython>();
541 data_up->user_source.SplitIntoLines(data);
543 if (GenerateBreakpointCommandCallbackData(data_up->user_source,
544 data_up->script_source,
548 auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
550 bp_options.SetCallback(
551 ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
552 }
else if (!batch_mode) {
555 error_sp->Printf(
"Warning: No command attached to breakpoint.\n");
565 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
566 data_up->user_source.SplitIntoLines(data);
568 if (GenerateWatchpointCommandCallbackData(data_up->user_source,
569 data_up->script_source,
572 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
574 ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
575 }
else if (!batch_mode) {
578 error_sp->Printf(
"Warning: No command attached to breakpoint.\n");
588ScriptInterpreterPythonImpl::CreateInstance(
Debugger &debugger) {
589 return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
592void ScriptInterpreterPythonImpl::LeaveSession() {
595 log->
PutCString(
"ScriptInterpreterPythonImpl::LeaveSession()");
598 PyRun_SimpleString(
"lldb.debugger = None; lldb.target = None; lldb.process "
599 "= None; lldb.thread = None; lldb.frame = None");
606 if (PyThreadState_GetDict()) {
607 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
608 if (sys_module_dict.IsValid()) {
609 if (m_saved_stdin.IsValid()) {
610 sys_module_dict.SetItemForKey(PythonString(
"stdin"), m_saved_stdin);
611 m_saved_stdin.Reset();
613 if (m_saved_stdout.IsValid()) {
614 sys_module_dict.SetItemForKey(PythonString(
"stdout"), m_saved_stdout);
615 m_saved_stdout.Reset();
617 if (m_saved_stderr.IsValid()) {
618 sys_module_dict.SetItemForKey(PythonString(
"stderr"), m_saved_stderr);
619 m_saved_stderr.Reset();
624 m_session_is_active =
false;
627bool ScriptInterpreterPythonImpl::SetStdHandle(
FileSP file_sp,
629 PythonObject &save_file,
631 if (!file_sp || !*file_sp) {
635 File &file = *file_sp;
640 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
642 auto new_file = PythonFile::FromFile(file, mode);
644 llvm::consumeError(new_file.takeError());
648 save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
650 sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
654bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
660 if (m_session_is_active) {
663 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
664 ") session is already active, returning without doing anything",
671 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
")",
674 m_session_is_active =
true;
678 if (on_entry_flags & Locker::InitGlobals) {
679 run_string.
Printf(
"run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
680 m_dictionary_name.c_str(), m_debugger.GetID());
682 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64
")",
684 run_string.
PutCString(
"; lldb.target = lldb.debugger.GetSelectedTarget()");
685 run_string.
PutCString(
"; lldb.process = lldb.target.GetProcess()");
686 run_string.
PutCString(
"; lldb.thread = lldb.process.GetSelectedThread ()");
687 run_string.
PutCString(
"; lldb.frame = lldb.thread.GetSelectedFrame ()");
692 run_string.
Printf(
"run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
693 m_dictionary_name.c_str(), m_debugger.GetID());
695 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64
")",
700 PyRun_SimpleString(run_string.
GetData());
703 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
704 if (sys_module_dict.IsValid()) {
707 if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
708 m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
711 if (on_entry_flags & Locker::NoSTDIN) {
712 m_saved_stdin.Reset();
714 if (!SetStdHandle(in_sp,
"stdin", m_saved_stdin,
"r")) {
716 SetStdHandle(top_in_sp,
"stdin", m_saved_stdin,
"r");
720 if (!SetStdHandle(out_sp,
"stdout", m_saved_stdout,
"w")) {
722 SetStdHandle(top_out_sp->GetFileSP(),
"stdout", m_saved_stdout,
"w");
725 if (!SetStdHandle(err_sp,
"stderr", m_saved_stderr,
"w")) {
727 SetStdHandle(top_err_sp->GetFileSP(),
"stderr", m_saved_stderr,
"w");
731 if (PyErr_Occurred())
737PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
738 if (!m_main_module.IsValid())
739 m_main_module = unwrapIgnoringErrors(PythonModule::Import(
"__main__"));
740 return m_main_module;
743PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
744 if (m_session_dict.IsValid())
745 return m_session_dict;
747 PythonObject &main_module = GetMainModule();
748 if (!main_module.IsValid())
749 return m_session_dict;
751 PythonDictionary main_dict(PyRefType::Borrowed,
752 PyModule_GetDict(main_module.get()));
753 if (!main_dict.IsValid())
754 return m_session_dict;
756 m_session_dict = unwrapIgnoringErrors(
757 As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
758 return m_session_dict;
761PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
762 if (m_sys_module_dict.IsValid())
763 return m_sys_module_dict;
764 PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import(
"sys"));
765 m_sys_module_dict = sys_module.GetDictionary();
766 return m_sys_module_dict;
769llvm::Expected<unsigned>
770ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
771 const llvm::StringRef &callable_name) {
772 if (callable_name.empty()) {
773 return llvm::createStringError(llvm::inconvertibleErrorCode(),
774 "called with empty callable name.");
777 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
778 auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
780 auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
781 callable_name, dict);
782 if (!pfunc.IsAllocated()) {
783 return llvm::createStringError(llvm::inconvertibleErrorCode(),
784 "can't find callable: %s",
785 callable_name.str().c_str());
787 llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
789 return arg_info.takeError();
790 return arg_info.get().max_positional_args;
793static std::string GenerateUniqueName(
const char *base_name_wanted,
794 uint32_t &functions_counter,
795 const void *name_token =
nullptr) {
798 if (!base_name_wanted)
799 return std::string();
802 sstr.
Printf(
"%s_%d", base_name_wanted, functions_counter++);
804 sstr.
Printf(
"%s_%p", base_name_wanted, name_token);
809bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
810 if (m_run_one_line_function.IsValid())
813 PythonObject module(PyRefType::Borrowed,
814 PyImport_AddModule(
"lldb.embedded_interpreter"));
815 if (!module.IsValid())
818 PythonDictionary module_dict(PyRefType::Borrowed,
819 PyModule_GetDict(module.get()));
820 if (!module_dict.IsValid())
823 m_run_one_line_function =
824 module_dict.GetItemForKey(PythonString(
"run_one_line"));
825 m_run_one_line_str_global =
826 module_dict.GetItemForKey(PythonString(
"g_run_one_line_str"));
827 return m_run_one_line_function.IsValid();
830bool ScriptInterpreterPythonImpl::ExecuteOneLine(
833 std::string command_str = command.str();
835 if (!m_valid_session)
838 if (!command.empty()) {
845 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
846 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
848 if (!io_redirect_or_error) {
851 "failed to redirect I/O: {0}\n",
852 llvm::fmt_consume(io_redirect_or_error.takeError()));
854 llvm::consumeError(io_redirect_or_error.takeError());
860 bool success =
false;
872 Locker::AcquireLock | Locker::InitSession |
875 Locker::FreeAcquiredLock | Locker::TearDownSession,
880 PythonDictionary &session_dict = GetSessionDictionary();
881 if (session_dict.IsValid()) {
882 if (GetEmbeddedInterpreterModuleObjects()) {
883 if (PyCallable_Check(m_run_one_line_function.get())) {
886 Py_BuildValue(
"(Os)", session_dict.get(), command_str.c_str()));
887 if (pargs.IsValid()) {
888 PythonObject return_value(
890 PyObject_CallObject(m_run_one_line_function.get(),
892 if (return_value.IsValid())
912 "python failed attempting to evaluate '%s'\n", command_str.c_str());
918 result->
AppendError(
"empty command passed to python\n");
922void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
936 IOHandlerSP io_handler_sp(
new IOHandlerPythonInterpreter(debugger,
this));
942bool ScriptInterpreterPythonImpl::Interrupt() {
943#if LLDB_USE_PYTHON_SET_INTERRUPT
947 if (!IsExecutingPython())
951 PyErr_SetInterrupt();
961 if (IsExecutingPython()) {
962 PyThreadState *state = PyThreadState_GET();
964 state = GetThreadState();
966 long tid = state->thread_id;
967 PyThreadState_Swap(state);
968 int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
970 "ScriptInterpreterPythonImpl::Interrupt() sending "
971 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
977 "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
983bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
987 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
988 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
991 if (!io_redirect_or_error) {
992 llvm::consumeError(io_redirect_or_error.takeError());
999 Locker::AcquireLock | Locker::InitSession |
1002 Locker::FreeAcquiredLock | Locker::TearDownSession,
1006 PythonModule &main_module = GetMainModule();
1007 PythonDictionary globals = main_module.GetDictionary();
1009 PythonDictionary locals = GetSessionDictionary();
1010 if (!locals.IsValid())
1011 locals = unwrapIgnoringErrors(
1012 As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1013 if (!locals.IsValid())
1016 Expected<PythonObject> maybe_py_return =
1017 runStringOneLine(in_string, globals, locals);
1019 if (!maybe_py_return) {
1020 llvm::handleAllErrors(
1021 maybe_py_return.takeError(),
1022 [&](PythonException &E) {
1024 if (options.GetMaskoutErrors()) {
1025 if (E.Matches(PyExc_SyntaxError)) {
1031 [](
const llvm::ErrorInfoBase &E) {});
1035 PythonObject py_return = std::move(maybe_py_return.get());
1036 assert(py_return.IsValid());
1038 switch (return_type) {
1039 case eScriptReturnTypeCharPtr:
1041 const char format[3] =
"s#";
1042 return PyArg_Parse(py_return.get(), format, (
char **)ret_value);
1044 case eScriptReturnTypeCharStrOrNone:
1047 const char format[3] =
"z";
1048 return PyArg_Parse(py_return.get(), format, (
char **)ret_value);
1050 case eScriptReturnTypeBool: {
1051 const char format[2] =
"b";
1052 return PyArg_Parse(py_return.get(), format, (
bool *)ret_value);
1054 case eScriptReturnTypeShortInt: {
1055 const char format[2] =
"h";
1056 return PyArg_Parse(py_return.get(), format, (
short *)ret_value);
1058 case eScriptReturnTypeShortIntUnsigned: {
1059 const char format[2] =
"H";
1060 return PyArg_Parse(py_return.get(), format, (
unsigned short *)ret_value);
1062 case eScriptReturnTypeInt: {
1063 const char format[2] =
"i";
1064 return PyArg_Parse(py_return.get(), format, (
int *)ret_value);
1066 case eScriptReturnTypeIntUnsigned: {
1067 const char format[2] =
"I";
1068 return PyArg_Parse(py_return.get(), format, (
unsigned int *)ret_value);
1070 case eScriptReturnTypeLongInt: {
1071 const char format[2] =
"l";
1072 return PyArg_Parse(py_return.get(), format, (
long *)ret_value);
1074 case eScriptReturnTypeLongIntUnsigned: {
1075 const char format[2] =
"k";
1076 return PyArg_Parse(py_return.get(), format, (
unsigned long *)ret_value);
1078 case eScriptReturnTypeLongLong: {
1079 const char format[2] =
"L";
1080 return PyArg_Parse(py_return.get(), format, (
long long *)ret_value);
1082 case eScriptReturnTypeLongLongUnsigned: {
1083 const char format[2] =
"K";
1084 return PyArg_Parse(py_return.get(), format,
1085 (
unsigned long long *)ret_value);
1087 case eScriptReturnTypeFloat: {
1088 const char format[2] =
"f";
1089 return PyArg_Parse(py_return.get(), format, (
float *)ret_value);
1091 case eScriptReturnTypeDouble: {
1092 const char format[2] =
"d";
1093 return PyArg_Parse(py_return.get(), format, (
double *)ret_value);
1095 case eScriptReturnTypeChar: {
1096 const char format[2] =
"c";
1097 return PyArg_Parse(py_return.get(), format, (
char *)ret_value);
1099 case eScriptReturnTypeOpaqueObject: {
1100 *((PyObject **)ret_value) = py_return.release();
1104 llvm_unreachable(
"Fully covered switch!");
1107Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1110 if (in_string ==
nullptr)
1113 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1114 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1117 if (!io_redirect_or_error)
1118 return Status::FromError(io_redirect_or_error.takeError());
1123 Locker::AcquireLock | Locker::InitSession |
1126 Locker::FreeAcquiredLock | Locker::TearDownSession,
1130 PythonModule &main_module = GetMainModule();
1131 PythonDictionary globals = main_module.GetDictionary();
1133 PythonDictionary locals = GetSessionDictionary();
1134 if (!locals.IsValid())
1135 locals = unwrapIgnoringErrors(
1136 As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1137 if (!locals.IsValid())
1140 Expected<PythonObject> return_value =
1141 runStringMultiLine(in_string, globals, locals);
1143 if (!return_value) {
1145 llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
1146 llvm::Error error = llvm::createStringError(
1147 llvm::inconvertibleErrorCode(), E.ReadBacktrace());
1148 if (!options.GetMaskoutErrors())
1152 return Status::FromError(std::move(
error));
1158void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1159 std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1162 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1163 " ", *
this, &bp_options_vec);
1166void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1169 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1170 " ", *
this, wp_options);
1173Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1178 std::string function_signature = function_name;
1180 llvm::Expected<unsigned> maybe_args =
1181 GetMaxPositionalArgumentsForCallable(function_name);
1183 error = Status::FromErrorStringWithFormat(
1184 "could not get num args: %s",
1185 llvm::toString(maybe_args.takeError()).c_str());
1188 size_t max_args = *maybe_args;
1190 bool uses_extra_args =
false;
1191 if (max_args >= 4) {
1192 uses_extra_args =
true;
1193 function_signature +=
"(frame, bp_loc, extra_args, internal_dict)";
1194 }
else if (max_args >= 3) {
1195 if (extra_args_sp) {
1196 error = Status::FromErrorStringWithFormat(
1197 "cannot pass extra_args to a three argument callback");
1200 uses_extra_args =
false;
1201 function_signature +=
"(frame, bp_loc, internal_dict)";
1203 error = Status::FromErrorStringWithFormat(
"expected 3 or 4 argument "
1204 "function, %s can only take %zu",
1205 function_name, max_args);
1209 SetBreakpointCommandCallback(bp_options, function_signature.c_str(),
1210 extra_args_sp, uses_extra_args,
1215Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1217 std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
1219 error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1220 cmd_data_up->script_source,
1227 std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1229 ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1233Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1236 return SetBreakpointCommandCallback(bp_options, command_body_text, {},
1237 false, is_callback);
1241Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1245 auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1251 data_up->user_source.SplitIntoLines(command_body_text);
1252 Status error = GenerateBreakpointCommandCallbackData(
1253 data_up->user_source, data_up->script_source, uses_extra_args,
1255 if (
error.Success()) {
1257 std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1259 ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1266void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1268 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
1275 data_up->user_source.AppendString(user_input);
1276 data_up->script_source.assign(user_input);
1278 if (GenerateWatchpointCommandCallbackData(
1279 data_up->user_source, data_up->script_source, is_callback)) {
1281 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
1283 ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
1287Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1290 std::string function_def_string(function_def.
CopyList());
1297Status ScriptInterpreterPythonImpl::GenerateFunction(
const char *signature,
1301 int num_lines = input.
GetSize();
1302 if (num_lines == 0) {
1303 error = Status::FromErrorString(
"No input data.");
1307 if (!signature || *signature == 0) {
1308 error = Status::FromErrorString(
"No output function name.");
1316 " global_dict = globals()");
1318 " new_keys = internal_dict.keys()");
1321 " old_keys = global_dict.keys()");
1323 " global_dict.update(internal_dict)");
1330 if (num_lines == 1) {
1335 return Status::FromErrorString(
1336 "ScriptInterpreterPythonImpl::GenerateFunction(is_callback="
1337 "true) = ERROR: python function is multiline.");
1341 " __return_val = None");
1343 " def __user_code():");
1347 for (
int i = 0; i < num_lines; ++i) {
1353 " __return_val = __user_code()");
1357 " for key in new_keys:");
1360 " internal_dict[key] = global_dict[key]");
1363 " if key not in old_keys:");
1366 " del global_dict[key]");
1369 " return __return_val");
1372 error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
1377bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1378 StringList &user_input, std::string &output,
const void *name_token) {
1379 static uint32_t num_created_functions = 0;
1384 if (user_input.
GetSize() == 0)
1390 std::string auto_generated_function_name(
1391 GenerateUniqueName(
"lldb_autogen_python_type_print_func",
1392 num_created_functions, name_token));
1393 sstr.
Printf(
"def %s (valobj, internal_dict):",
1394 auto_generated_function_name.c_str());
1396 if (!GenerateFunction(sstr.
GetData(), user_input,
false)
1401 output.assign(auto_generated_function_name);
1405bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1406 StringList &user_input, std::string &output) {
1407 static uint32_t num_created_functions = 0;
1412 if (user_input.
GetSize() == 0)
1415 std::string auto_generated_function_name(GenerateUniqueName(
1416 "lldb_autogen_python_cmd_alias_func", num_created_functions));
1418 sstr.
Printf(
"def %s (debugger, args, exe_ctx, result, internal_dict):",
1419 auto_generated_function_name.c_str());
1421 if (!GenerateFunction(sstr.
GetData(), user_input,
false)
1426 output.assign(auto_generated_function_name);
1430bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1431 StringList &user_input, std::string &output,
const void *name_token) {
1432 static uint32_t num_created_classes = 0;
1434 int num_lines = user_input.
GetSize();
1438 if (user_input.
GetSize() == 0)
1443 std::string auto_generated_class_name(GenerateUniqueName(
1444 "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1450 sstr.
Printf(
"class %s:", auto_generated_class_name.c_str());
1456 for (
int i = 0; i < num_lines; ++i) {
1465 if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).
Success())
1470 output.assign(auto_generated_class_name);
1475ScriptInterpreterPythonImpl::CreateFrameRecognizer(
const char *class_name) {
1476 if (class_name ==
nullptr || class_name[0] ==
'\0')
1479 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1480 PythonObject ret_val = SWIGBridge::LLDBSWIGPython_CreateFrameRecognizer(
1481 class_name, m_dictionary_name.c_str());
1484 new StructuredPythonObject(std::move(ret_val)));
1490 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1492 if (!os_plugin_object_sp)
1499 PythonObject implementor(PyRefType::Borrowed,
1500 (PyObject *)generic->GetValue());
1502 if (!implementor.IsAllocated())
1505 PythonObject py_return(PyRefType::Owned,
1506 SWIGBridge::LLDBSwigPython_GetRecognizedArguments(
1507 implementor.get(), frame_sp));
1510 if (PyErr_Occurred()) {
1514 if (py_return.get()) {
1515 PythonList result_list(PyRefType::Borrowed, py_return.get());
1517 for (
size_t i = 0; i < result_list.GetSize(); i++) {
1518 PyObject *item = result_list.GetItemAtIndex(i).get();
1520 (
lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
1522 SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
1524 result->Append(valobj_sp);
1531bool ScriptInterpreterPythonImpl::ShouldHide(
1534 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1536 if (!os_plugin_object_sp)
1543 PythonObject implementor(PyRefType::Borrowed,
1544 (PyObject *)generic->GetValue());
1546 if (!implementor.IsAllocated())
1550 SWIGBridge::LLDBSwigPython_ShouldHide(implementor.get(), frame_sp);
1553 if (PyErr_Occurred()) {
1561ScriptInterpreterPythonImpl::CreateScriptedProcessInterface() {
1562 return std::make_unique<ScriptedProcessPythonInterface>(*
this);
1566ScriptInterpreterPythonImpl::CreateScriptedStopHookInterface() {
1567 return std::make_shared<ScriptedStopHookPythonInterface>(*
this);
1571ScriptInterpreterPythonImpl::CreateScriptedThreadInterface() {
1572 return std::make_shared<ScriptedThreadPythonInterface>(*
this);
1576ScriptInterpreterPythonImpl::CreateScriptedThreadPlanInterface() {
1577 return std::make_shared<ScriptedThreadPlanPythonInterface>(*
this);
1581ScriptInterpreterPythonImpl::CreateOperatingSystemInterface() {
1582 return std::make_shared<OperatingSystemPythonInterface>(*
this);
1586ScriptInterpreterPythonImpl::CreateStructuredDataFromScriptObject(
1588 void *ptr =
const_cast<void *
>(obj.
GetPointer());
1589 PythonObject py_obj(PyRefType::Borrowed,
static_cast<PyObject *
>(ptr));
1590 if (!py_obj.IsValid() || py_obj.IsNone())
1592 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1593 return py_obj.CreateStructuredObject();
1597ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
1601 if (class_name ==
nullptr || class_name[0] ==
'\0')
1607 Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
1608 ScriptInterpreterPythonImpl *python_interpreter =
1609 GetPythonInterpreter(debugger);
1611 if (!python_interpreter)
1614 Locker py_lock(
this,
1615 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1617 PythonObject ret_val =
1618 SWIGBridge::LLDBSwigPythonCreateScriptedBreakpointResolver(
1619 class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
1623 new StructuredPythonObject(std::move(ret_val)));
1626bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
1628 bool should_continue =
false;
1630 if (implementor_sp) {
1631 Locker py_lock(
this,
1632 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1633 should_continue = SWIGBridge::LLDBSwigPythonCallBreakpointResolver(
1634 implementor_sp->GetValue(),
"__callback__", sym_ctx);
1635 if (PyErr_Occurred()) {
1640 return should_continue;
1644ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
1647 if (implementor_sp) {
1648 Locker py_lock(
this,
1649 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1650 depth_as_int = SWIGBridge::LLDBSwigPythonCallBreakpointResolver(
1651 implementor_sp->GetValue(),
"__get_depth__",
nullptr);
1652 if (PyErr_Occurred()) {
1666ScriptInterpreterPythonImpl::LoadPluginModule(
const FileSpec &file_spec,
1668 if (!FileSystem::Instance().Exists(file_spec)) {
1669 error = Status::FromErrorString(
"no such file");
1677 if (LoadScriptingModule(file_spec.
GetPath().c_str(), load_script_options,
1687 if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
1693 Locker py_lock(
this,
1694 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1695 TargetSP target_sp(target->shared_from_this());
1697 auto setting = (PyObject *)SWIGBridge::LLDBSWIGPython_GetDynamicSetting(
1698 generic->GetValue(), setting_name, target_sp);
1703 PythonDictionary py_dict =
1704 unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
1709 return py_dict.CreateStructuredDictionary();
1713ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
1715 if (class_name ==
nullptr || class_name[0] ==
'\0')
1722 Target *target = exe_ctx.GetTargetPtr();
1728 ScriptInterpreterPythonImpl *python_interpreter =
1729 GetPythonInterpreter(debugger);
1731 if (!python_interpreter)
1734 Locker py_lock(
this,
1735 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1736 PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateSyntheticProvider(
1737 class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
1740 new StructuredPythonObject(std::move(ret_val)));
1744ScriptInterpreterPythonImpl::CreateScriptCommandObject(
const char *class_name) {
1745 DebuggerSP debugger_sp(m_debugger.shared_from_this());
1747 if (class_name ==
nullptr || class_name[0] ==
'\0')
1750 if (!debugger_sp.get())
1753 Locker py_lock(
this,
1754 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1755 PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateCommandObject(
1756 class_name, m_dictionary_name.c_str(), debugger_sp);
1758 if (ret_val.IsValid())
1760 new StructuredPythonObject(std::move(ret_val)));
1765bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1766 const char *oneliner, std::string &output,
const void *name_token) {
1769 return GenerateTypeScriptFunction(input, output, name_token);
1772bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1773 const char *oneliner, std::string &output,
const void *name_token) {
1776 return GenerateTypeSynthClass(input, output, name_token);
1779Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
1780 StringList &user_input, std::string &output,
bool has_extra_args,
1782 static uint32_t num_created_functions = 0;
1786 if (user_input.
GetSize() == 0) {
1787 error = Status::FromErrorString(
"No input data.");
1791 std::string auto_generated_function_name(GenerateUniqueName(
1792 "lldb_autogen_python_bp_callback_func_", num_created_functions));
1794 sstr.
Printf(
"def %s (frame, bp_loc, extra_args, internal_dict):",
1795 auto_generated_function_name.c_str());
1797 sstr.
Printf(
"def %s (frame, bp_loc, internal_dict):",
1798 auto_generated_function_name.c_str());
1800 error = GenerateFunction(sstr.
GetData(), user_input, is_callback);
1801 if (!
error.Success())
1805 output.assign(auto_generated_function_name);
1809bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
1810 StringList &user_input, std::string &output,
bool is_callback) {
1811 static uint32_t num_created_functions = 0;
1815 if (user_input.
GetSize() == 0)
1818 std::string auto_generated_function_name(GenerateUniqueName(
1819 "lldb_autogen_python_wp_callback_func_", num_created_functions));
1820 sstr.
Printf(
"def %s (frame, wp, internal_dict):",
1821 auto_generated_function_name.c_str());
1823 if (!GenerateFunction(sstr.
GetData(), user_input, is_callback).Success())
1827 output.assign(auto_generated_function_name);
1831bool ScriptInterpreterPythonImpl::GetScriptedSummary(
1838 if (!valobj.get()) {
1839 retval.assign(
"<no object>");
1843 void *old_callee =
nullptr;
1845 if (callee_wrapper_sp) {
1850 void *new_callee = old_callee;
1853 if (python_function_name && *python_function_name) {
1855 Locker py_lock(
this, Locker::AcquireLock | Locker::InitSession |
1861 Timer scoped_timer(func_cat,
"LLDBSwigPythonCallTypeScript");
1862 ret_val = SWIGBridge::LLDBSwigPythonCallTypeScript(
1863 python_function_name, GetSessionDictionary().get(), valobj,
1864 &new_callee, options_sp, retval);
1868 retval.assign(
"<no function name>");
1872 if (new_callee && old_callee != new_callee) {
1873 Locker py_lock(
this,
1874 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1875 callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
1876 PythonObject(PyRefType::Borrowed,
static_cast<PyObject *
>(new_callee)));
1882bool ScriptInterpreterPythonImpl::FormatterCallbackFunction(
1883 const char *python_function_name,
TypeImplSP type_impl_sp) {
1884 Locker py_lock(
this,
1885 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1886 return SWIGBridge::LLDBSwigPythonFormatterCallbackFunction(
1887 python_function_name, m_dictionary_name.c_str(), type_impl_sp);
1890bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
1893 CommandDataPython *bp_option_data = (CommandDataPython *)baton;
1894 const char *python_function_name = bp_option_data->script_source.c_str();
1900 Target *target = exe_ctx.GetTargetPtr();
1906 ScriptInterpreterPythonImpl *python_interpreter =
1907 GetPythonInterpreter(debugger);
1909 if (!python_interpreter)
1912 if (python_function_name && python_function_name[0]) {
1913 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
1915 if (breakpoint_sp) {
1917 breakpoint_sp->FindLocationByID(break_loc_id));
1919 if (stop_frame_sp && bp_loc_sp) {
1920 bool ret_val =
true;
1922 Locker py_lock(python_interpreter, Locker::AcquireLock |
1923 Locker::InitSession |
1925 Expected<bool> maybe_ret_val =
1926 SWIGBridge::LLDBSwigPythonBreakpointCallbackFunction(
1927 python_function_name,
1928 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
1929 bp_loc_sp, bp_option_data->m_extra_args);
1931 if (!maybe_ret_val) {
1933 llvm::handleAllErrors(
1934 maybe_ret_val.takeError(),
1935 [&](PythonException &E) {
1936 debugger.GetErrorStream() << E.ReadBacktrace();
1938 [&](
const llvm::ErrorInfoBase &E) {
1939 debugger.GetErrorStream() << E.message();
1943 ret_val = maybe_ret_val.get();
1955bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
1959 const char *python_function_name = wp_option_data->
script_source.c_str();
1965 Target *target = exe_ctx.GetTargetPtr();
1971 ScriptInterpreterPythonImpl *python_interpreter =
1972 GetPythonInterpreter(debugger);
1974 if (!python_interpreter)
1977 if (python_function_name && python_function_name[0]) {
1978 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
1981 if (stop_frame_sp && wp_sp) {
1982 bool ret_val =
true;
1984 Locker py_lock(python_interpreter, Locker::AcquireLock |
1985 Locker::InitSession |
1987 ret_val = SWIGBridge::LLDBSwigPythonWatchpointCallbackFunction(
1988 python_function_name,
1989 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2001size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2003 if (!implementor_sp)
2008 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2015 Locker py_lock(
this,
2016 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2017 ret_val = SWIGBridge::LLDBSwigPython_CalculateNumChildren(implementor, max);
2025 if (!implementor_sp)
2031 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2037 Locker py_lock(
this,
2038 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2039 PyObject *child_ptr =
2040 SWIGBridge::LLDBSwigPython_GetChildAtIndex(implementor, idx);
2041 if (child_ptr !=
nullptr && child_ptr != Py_None) {
2043 (
lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2044 if (sb_value_ptr ==
nullptr)
2045 Py_XDECREF(child_ptr);
2047 ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
2050 Py_XDECREF(child_ptr);
2057int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2059 if (!implementor_sp)
2065 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2072 Locker py_lock(
this,
2073 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2074 ret_val = SWIGBridge::LLDBSwigPython_GetIndexOfChildWithName(implementor,
2081bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2083 bool ret_val =
false;
2085 if (!implementor_sp)
2091 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2096 Locker py_lock(
this,
2097 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2099 SWIGBridge::LLDBSwigPython_UpdateSynthProviderInstance(implementor);
2105bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2107 bool ret_val =
false;
2109 if (!implementor_sp)
2115 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2120 Locker py_lock(
this,
2121 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2122 ret_val = SWIGBridge::LLDBSwigPython_MightHaveChildrenSynthProviderInstance(
2133 if (!implementor_sp)
2139 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2144 Locker py_lock(
this,
2145 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2146 PyObject *child_ptr =
2147 SWIGBridge::LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2148 if (child_ptr !=
nullptr && child_ptr != Py_None) {
2150 (
lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2151 if (sb_value_ptr ==
nullptr)
2152 Py_XDECREF(child_ptr);
2154 ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
2157 Py_XDECREF(child_ptr);
2164ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2166 Locker py_lock(
this,
2167 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2169 if (!implementor_sp)
2176 PythonObject implementor(PyRefType::Borrowed,
2177 (PyObject *)generic->GetValue());
2178 if (!implementor.IsAllocated())
2181 llvm::Expected<PythonObject> expected_py_return =
2182 implementor.CallMethod(
"get_type_name");
2184 if (!expected_py_return) {
2185 llvm::consumeError(expected_py_return.takeError());
2189 PythonObject py_return = std::move(expected_py_return.get());
2190 if (!py_return.IsAllocated() || !PythonString::Check(py_return.get()))
2193 PythonString type_name(PyRefType::Borrowed, py_return.get());
2197bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2198 const char *impl_function,
Process *process, std::string &output,
2202 error = Status::FromErrorString(
"no process");
2205 if (!impl_function || !impl_function[0]) {
2206 error = Status::FromErrorString(
"no function to execute");
2211 Locker py_lock(
this,
2212 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2213 ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordProcess(
2214 impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
2217 error = Status::FromErrorString(
"python script evaluation failed");
2222bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2223 const char *impl_function,
Thread *thread, std::string &output,
2226 error = Status::FromErrorString(
"no thread");
2229 if (!impl_function || !impl_function[0]) {
2230 error = Status::FromErrorString(
"no function to execute");
2234 Locker py_lock(
this,
2235 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2236 if (std::optional<std::string> result =
2237 SWIGBridge::LLDBSWIGPythonRunScriptKeywordThread(
2238 impl_function, m_dictionary_name.c_str(),
2239 thread->shared_from_this())) {
2240 output = std::move(*result);
2243 error = Status::FromErrorString(
"python script evaluation failed");
2247bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2248 const char *impl_function,
Target *target, std::string &output,
2252 error = Status::FromErrorString(
"no thread");
2255 if (!impl_function || !impl_function[0]) {
2256 error = Status::FromErrorString(
"no function to execute");
2261 TargetSP target_sp(target->shared_from_this());
2262 Locker py_lock(
this,
2263 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2264 ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordTarget(
2265 impl_function, m_dictionary_name.c_str(), target_sp, output);
2267 error = Status::FromErrorString(
"python script evaluation failed");
2272bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2273 const char *impl_function,
StackFrame *frame, std::string &output,
2276 error = Status::FromErrorString(
"no frame");
2279 if (!impl_function || !impl_function[0]) {
2280 error = Status::FromErrorString(
"no function to execute");
2284 Locker py_lock(
this,
2285 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2286 if (std::optional<std::string> result =
2287 SWIGBridge::LLDBSWIGPythonRunScriptKeywordFrame(
2288 impl_function, m_dictionary_name.c_str(),
2289 frame->shared_from_this())) {
2290 output = std::move(*result);
2293 error = Status::FromErrorString(
"python script evaluation failed");
2297bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2298 const char *impl_function,
ValueObject *value, std::string &output,
2302 error = Status::FromErrorString(
"no value");
2305 if (!impl_function || !impl_function[0]) {
2306 error = Status::FromErrorString(
"no function to execute");
2311 Locker py_lock(
this,
2312 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2313 ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordValue(
2314 impl_function, m_dictionary_name.c_str(), value->
GetSP(), output);
2316 error = Status::FromErrorString(
"python script evaluation failed");
2321uint64_t replace_all(std::string &str,
const std::string &oldStr,
2322 const std::string &newStr) {
2324 uint64_t matches = 0;
2325 while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2327 str.replace(pos, oldStr.length(), newStr);
2328 pos += newStr.length();
2333bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2337 namespace fs = llvm::sys::fs;
2338 namespace path = llvm::sys::path;
2344 if (!pathname || !pathname[0]) {
2345 error = Status::FromErrorString(
"empty path");
2349 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2350 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2353 if (!io_redirect_or_error) {
2354 error = Status::FromError(io_redirect_or_error.takeError());
2361 Locker py_lock(
this,
2362 Locker::AcquireLock |
2365 Locker::FreeAcquiredLock |
2370 auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2371 if (directory.empty()) {
2372 return llvm::createStringError(
"invalid directory name");
2375 replace_all(directory,
"\\",
"\\\\");
2376 replace_all(directory,
"'",
"\\'");
2380 command_stream.
Printf(
"if not (sys.path.__contains__('%s')):\n "
2381 "sys.path.insert(1,'%s');\n\n",
2382 directory.c_str(), directory.c_str());
2383 bool syspath_retval =
2384 ExecuteMultipleLines(command_stream.
GetData(), exc_options).Success();
2385 if (!syspath_retval)
2386 return llvm::createStringError(
"Python sys.path handling failed");
2388 return llvm::Error::success();
2391 std::string module_name(pathname);
2392 bool possible_package =
false;
2394 if (extra_search_dir) {
2395 if (llvm::Error e = ExtendSysPath(extra_search_dir.
GetPath())) {
2396 error = Status::FromError(std::move(e));
2401 FileSystem::Instance().Resolve(module_file);
2404 std::error_code ec = status(module_file.GetPath(), st);
2406 if (ec || st.type() == fs::file_type::status_error ||
2407 st.type() == fs::file_type::type_unknown ||
2408 st.type() == fs::file_type::file_not_found) {
2411 if (strchr(pathname,
'\\') || strchr(pathname,
'/')) {
2412 error = Status::FromErrorStringWithFormatv(
"invalid pathname '{0}'",
2417 possible_package =
true;
2418 }
else if (is_directory(st) || is_regular_file(st)) {
2419 if (module_file.GetDirectory().IsEmpty()) {
2420 error = Status::FromErrorStringWithFormatv(
2421 "invalid directory name '{0}'", pathname);
2425 ExtendSysPath(module_file.GetDirectory().GetCString())) {
2426 error = Status::FromError(std::move(e));
2429 module_name = module_file.GetFilename().GetCString();
2431 error = Status::FromErrorString(
2432 "no known way to import this module specification");
2438 llvm::StringRef extension = llvm::sys::path::extension(module_name);
2439 if (!extension.empty()) {
2440 if (extension ==
".py")
2441 module_name.resize(module_name.length() - 3);
2442 else if (extension ==
".pyc")
2443 module_name.resize(module_name.length() - 4);
2446 if (!possible_package && module_name.find(
'.') != llvm::StringRef::npos) {
2447 error = Status::FromErrorStringWithFormat(
2448 "Python does not allow dots in module names: %s", module_name.c_str());
2452 if (module_name.find(
'-') != llvm::StringRef::npos) {
2453 error = Status::FromErrorStringWithFormat(
2454 "Python discourages dashes in module names: %s", module_name.c_str());
2460 command_stream.
Clear();
2461 command_stream.
Printf(
"sys.modules.__contains__('%s')", module_name.c_str());
2462 bool does_contain =
false;
2465 const bool does_contain_executed = ExecuteOneLineWithReturn(
2467 ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain,
2470 const bool was_imported_globally = does_contain_executed && does_contain;
2471 const bool was_imported_locally =
2472 GetSessionDictionary()
2473 .GetItemForKey(PythonString(module_name))
2477 command_stream.
Clear();
2479 if (was_imported_globally || was_imported_locally) {
2480 if (!was_imported_locally)
2481 command_stream.
Printf(
"import %s ; reload_module(%s)",
2482 module_name.c_str(), module_name.c_str());
2484 command_stream.
Printf(
"reload_module(%s)", module_name.c_str());
2486 command_stream.
Printf(
"import %s", module_name.c_str());
2488 error = ExecuteMultipleLines(command_stream.
GetData(), exc_options);
2494 if (!SWIGBridge::LLDBSwigPythonCallModuleInit(
2495 module_name.c_str(), m_dictionary_name.c_str(),
2496 m_debugger.shared_from_this())) {
2497 error = Status::FromErrorString(
"calling __lldb_init_module failed");
2503 command_stream.
Clear();
2504 command_stream.
Printf(
"%s", module_name.c_str());
2505 void *module_pyobj =
nullptr;
2506 if (ExecuteOneLineWithReturn(
2508 ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2511 *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2512 PyRefType::Owned,
static_cast<PyObject *
>(module_pyobj)));
2518bool ScriptInterpreterPythonImpl::IsReservedWord(
const char *word) {
2519 if (!word || !word[0])
2522 llvm::StringRef word_sr(word);
2526 if (word_sr.find(
'"') != llvm::StringRef::npos ||
2527 word_sr.find(
'\'') != llvm::StringRef::npos)
2531 command_stream.
Printf(
"keyword.iskeyword('%s')", word);
2537 if (ExecuteOneLineWithReturn(command_stream.
GetData(),
2538 ScriptInterpreter::eScriptReturnTypeBool,
2544ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2546 : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2547 m_old_asynch(debugger_sp->GetAsyncExecution()) {
2548 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2549 m_debugger_sp->SetAsyncExecution(
false);
2550 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2551 m_debugger_sp->SetAsyncExecution(
true);
2554ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
2555 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2556 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2559bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2560 const char *impl_function, llvm::StringRef args,
2564 if (!impl_function) {
2565 error = Status::FromErrorString(
"no function to execute");
2572 if (!debugger_sp.get()) {
2573 error = Status::FromErrorString(
"invalid Debugger pointer");
2577 bool ret_val =
false;
2579 std::string err_msg;
2582 Locker py_lock(
this,
2583 Locker::AcquireLock | Locker::InitSession |
2585 Locker::FreeLock | Locker::TearDownSession);
2587 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2589 std::string args_str = args.str();
2590 ret_val = SWIGBridge::LLDBSwigPythonCallCommand(
2591 impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2592 cmd_retobj, exe_ctx_ref_sp);
2596 error = Status::FromErrorString(
"unable to execute script function");
2597 else if (cmd_retobj.
GetStatus() == eReturnStatusFailed)
2604bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2609 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2610 error = Status::FromErrorString(
"no function to execute");
2617 if (!debugger_sp.get()) {
2618 error = Status::FromErrorString(
"invalid Debugger pointer");
2622 bool ret_val =
false;
2624 std::string err_msg;
2627 Locker py_lock(
this,
2628 Locker::AcquireLock | Locker::InitSession |
2630 Locker::FreeLock | Locker::TearDownSession);
2632 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2634 std::string args_str = args.str();
2635 ret_val = SWIGBridge::LLDBSwigPythonCallCommandObject(
2636 static_cast<PyObject *
>(impl_obj_sp->GetValue()), debugger_sp,
2637 args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
2641 error = Status::FromErrorString(
"unable to execute script function");
2642 else if (cmd_retobj.
GetStatus() == eReturnStatusFailed)
2649bool ScriptInterpreterPythonImpl::RunScriptBasedParsedCommand(
2654 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2655 error = Status::FromErrorString(
"no function to execute");
2662 if (!debugger_sp.get()) {
2663 error = Status::FromErrorString(
"invalid Debugger pointer");
2667 bool ret_val =
false;
2669 std::string err_msg;
2672 Locker py_lock(
this,
2673 Locker::AcquireLock | Locker::InitSession |
2675 Locker::FreeLock | Locker::TearDownSession);
2677 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2682 args_arr_sp->AddStringItem(entry.ref());
2686 ret_val = SWIGBridge::LLDBSwigPythonCallParsedCommandObject(
2687 static_cast<PyObject *
>(impl_obj_sp->GetValue()), debugger_sp,
2688 args_impl, cmd_retobj, exe_ctx_ref_sp);
2692 error = Status::FromErrorString(
"unable to execute script function");
2693 else if (cmd_retobj.
GetStatus() == eReturnStatusFailed)
2700std::optional<std::string>
2701ScriptInterpreterPythonImpl::GetRepeatCommandForScriptedCommand(
2703 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2704 return std::nullopt;
2708 if (!debugger_sp.get())
2709 return std::nullopt;
2711 std::optional<std::string> ret_val;
2714 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN,
2720 std::string command;
2722 ret_val = SWIGBridge::LLDBSwigPythonGetRepeatCommandForScriptedCommand(
2723 static_cast<PyObject *
>(impl_obj_sp->GetValue()), command);
2729ScriptInterpreterPythonImpl::HandleArgumentCompletionForScriptedCommand(
2731 size_t args_pos,
size_t char_in_arg) {
2733 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2734 return completion_dict_sp;
2737 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN,
2740 completion_dict_sp =
2741 SWIGBridge::LLDBSwigPythonHandleArgumentCompletionForScriptedCommand(
2742 static_cast<PyObject *
>(impl_obj_sp->GetValue()), args, args_pos,
2745 return completion_dict_sp;
2749ScriptInterpreterPythonImpl::HandleOptionArgumentCompletionForScriptedCommand(
2751 size_t char_in_arg) {
2753 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2754 return completion_dict_sp;
2757 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN,
2760 completion_dict_sp = SWIGBridge::
2761 LLDBSwigPythonHandleOptionArgumentCompletionForScriptedCommand(
2762 static_cast<PyObject *
>(impl_obj_sp->GetValue()), long_option,
2765 return completion_dict_sp;
2771bool ScriptInterpreterPythonImpl::GetDocumentationForItem(
const char *item,
2772 std::string &dest) {
2775 if (!item || !*item)
2778 std::string command(item);
2779 command +=
".__doc__";
2783 char *result_ptr =
nullptr;
2785 if (ExecuteOneLineWithReturn(
2786 command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
2789 dest.assign(result_ptr);
2794 str_stream <<
"Function " << item
2795 <<
" was not found. Containing module might be missing.";
2796 dest = std::string(str_stream.
GetString());
2801bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
2805 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2810 PythonObject implementor(PyRefType::Borrowed,
2811 (PyObject *)cmd_obj_sp->GetValue());
2813 if (!implementor.IsAllocated())
2816 llvm::Expected<PythonObject> expected_py_return =
2817 implementor.CallMethod(
"get_short_help");
2819 if (!expected_py_return) {
2820 llvm::consumeError(expected_py_return.takeError());
2824 PythonObject py_return = std::move(expected_py_return.get());
2826 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2827 PythonString py_string(PyRefType::Borrowed, py_return.get());
2828 llvm::StringRef return_data(py_string.GetString());
2829 dest.assign(return_data.data(), return_data.size());
2836uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
2838 uint32_t result = 0;
2840 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2842 static char callee_name[] =
"get_flags";
2847 PythonObject implementor(PyRefType::Borrowed,
2848 (PyObject *)cmd_obj_sp->GetValue());
2850 if (!implementor.IsAllocated())
2853 PythonObject pmeth(PyRefType::Owned,
2854 PyObject_GetAttrString(implementor.get(), callee_name));
2856 if (PyErr_Occurred())
2859 if (!pmeth.IsAllocated())
2862 if (PyCallable_Check(pmeth.get()) == 0) {
2863 if (PyErr_Occurred())
2868 if (PyErr_Occurred())
2871 long long py_return = unwrapOrSetPythonException(
2872 As<long long>(implementor.CallMethod(callee_name)));
2875 if (PyErr_Occurred()) {
2886ScriptInterpreterPythonImpl::GetOptionsForCommandObject(
2890 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2892 static char callee_name[] =
"get_options_definition";
2897 PythonObject implementor(PyRefType::Borrowed,
2898 (PyObject *)cmd_obj_sp->GetValue());
2900 if (!implementor.IsAllocated())
2903 PythonObject pmeth(PyRefType::Owned,
2904 PyObject_GetAttrString(implementor.get(), callee_name));
2906 if (PyErr_Occurred())
2909 if (!pmeth.IsAllocated())
2912 if (PyCallable_Check(pmeth.get()) == 0) {
2913 if (PyErr_Occurred())
2918 if (PyErr_Occurred())
2921 PythonDictionary py_return = unwrapOrSetPythonException(
2922 As<PythonDictionary>(implementor.CallMethod(callee_name)));
2925 if (PyErr_Occurred()) {
2930 return py_return.CreateStructuredObject();
2934ScriptInterpreterPythonImpl::GetArgumentsForCommandObject(
2938 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2940 static char callee_name[] =
"get_args_definition";
2945 PythonObject implementor(PyRefType::Borrowed,
2946 (PyObject *)cmd_obj_sp->GetValue());
2948 if (!implementor.IsAllocated())
2951 PythonObject pmeth(PyRefType::Owned,
2952 PyObject_GetAttrString(implementor.get(), callee_name));
2954 if (PyErr_Occurred())
2957 if (!pmeth.IsAllocated())
2960 if (PyCallable_Check(pmeth.get()) == 0) {
2961 if (PyErr_Occurred())
2966 if (PyErr_Occurred())
2969 PythonList py_return = unwrapOrSetPythonException(
2970 As<PythonList>(implementor.CallMethod(callee_name)));
2973 if (PyErr_Occurred()) {
2978 return py_return.CreateStructuredObject();
2981void ScriptInterpreterPythonImpl::OptionParsingStartedForCommandObject(
2984 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2986 static char callee_name[] =
"option_parsing_started";
2991 PythonObject implementor(PyRefType::Borrowed,
2992 (PyObject *)cmd_obj_sp->GetValue());
2994 if (!implementor.IsAllocated())
2997 PythonObject pmeth(PyRefType::Owned,
2998 PyObject_GetAttrString(implementor.get(), callee_name));
3000 if (PyErr_Occurred())
3003 if (!pmeth.IsAllocated())
3006 if (PyCallable_Check(pmeth.get()) == 0) {
3007 if (PyErr_Occurred())
3012 if (PyErr_Occurred())
3017 unwrapOrSetPythonException(As<bool>(implementor.CallMethod(callee_name)));
3020 if (PyErr_Occurred()) {
3027bool ScriptInterpreterPythonImpl::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(As<bool>(
3069 implementor.CallMethod(callee_name, ctx_ref_obj,
3070 long_option.str().c_str(), 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::ScriptedStopHookInterface > ScriptedStopHookInterfaceSP
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::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