9#include "lldb/Host/Config.h"
47#include "llvm/ADT/STLExtras.h"
48#include "llvm/ADT/StringRef.h"
49#include "llvm/Support/Error.h"
50#include "llvm/Support/FileSystem.h"
51#include "llvm/Support/FormatAdapters.h"
68extern "C" PyObject *PyInit__lldb(
void);
70#define LLDBSwigPyInit PyInit__lldb
74#define LLDB_USE_PYTHON_SET_INTERRUPT 0
77#define LLDB_USE_PYTHON_SET_INTERRUPT \
78 (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
81static ScriptInterpreterPythonImpl *GetPythonInterpreter(
Debugger &debugger) {
84 return static_cast<ScriptInterpreterPythonImpl *
>(script_interpreter);
95struct InitializePythonRAII {
97 InitializePythonRAII() {
98 InitializePythonHome();
102 if (!Py_IsInitialized()) {
103#ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
106 bool ReadlinePatched =
false;
107 for (
auto *p = PyImport_Inittab; p->name !=
nullptr; p++) {
108 if (strcmp(p->name,
"readline") == 0) {
109 p->initfunc = initlldb_readline;
113 if (!ReadlinePatched) {
114 PyImport_AppendInittab(
"readline", initlldb_readline);
115 ReadlinePatched =
true;
120 PyImport_AppendInittab(
"_lldb", LLDBSwigPyInit);
126#if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
128 InitializeThreadsPrivate();
130 InitializeThreadsPrivate();
135 ~InitializePythonRAII() {
136 if (m_was_already_initialized) {
138 LLDB_LOGV(log,
"Releasing PyGILState. Returning to state = {0}locked",
139 m_gil_state == PyGILState_UNLOCKED ?
"un" :
"");
140 PyGILState_Release(m_gil_state);
148 void InitializePythonHome() {
149#if LLDB_EMBED_PYTHON_HOME
150 typedef wchar_t *str_type;
151 static str_type g_python_home = []() -> str_type {
152 const char *lldb_python_home = LLDB_PYTHON_HOME;
153 const char *absolute_python_home =
nullptr;
154 llvm::SmallString<64> path;
155 if (llvm::sys::path::is_absolute(lldb_python_home)) {
156 absolute_python_home = lldb_python_home;
158 FileSpec spec = HostInfo::GetShlibDir();
162 llvm::sys::path::append(path, lldb_python_home);
163 absolute_python_home = path.c_str();
166 return Py_DecodeLocale(absolute_python_home, &size);
168 if (g_python_home !=
nullptr) {
169 Py_SetPythonHome(g_python_home);
174 void InitializeThreadsPrivate() {
181#if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3)
183 if (PyGILState_Check())
189#if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 9) || (PY_MAJOR_VERSION < 3)
190 if (PyEval_ThreadsInitialized()) {
196 m_was_already_initialized =
true;
197 m_gil_state = PyGILState_Ensure();
198 LLDB_LOGV(log,
"Ensured PyGILState. Previous state = {0}locked\n",
199 m_gil_state == PyGILState_UNLOCKED ?
"un" :
"");
203#if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 9) || (PY_MAJOR_VERSION < 3)
208 PyEval_InitThreads();
214 PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
215 bool m_was_already_initialized =
false;
218#if LLDB_USE_PYTHON_SET_INTERRUPT
221struct RestoreSignalHandlerScope {
223 struct sigaction m_prev_handler;
225 RestoreSignalHandlerScope(
int signal_code) : m_signal_code(signal_code) {
227 std::memset(&m_prev_handler, 0,
sizeof(m_prev_handler));
229 struct sigaction *new_handler =
nullptr;
230 int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler);
231 lldbassert(signal_err == 0 &&
"sigaction failed to read handler");
233 ~RestoreSignalHandlerScope() {
234 int signal_err = ::sigaction(m_signal_code, &m_prev_handler,
nullptr);
235 lldbassert(signal_err == 0 &&
"sigaction failed to restore old handler");
241void ScriptInterpreterPython::ComputePythonDirForApple(
243 auto style = llvm::sys::path::Style::posix;
245 llvm::StringRef path_ref(path.begin(), path.size());
246 auto rbegin = llvm::sys::path::rbegin(path_ref, style);
247 auto rend = llvm::sys::path::rend(path_ref);
248 auto framework = std::find(rbegin, rend,
"LLDB.framework");
249 if (framework == rend) {
250 ComputePythonDir(path);
253 path.resize(framework - rend);
254 llvm::sys::path::append(path, style,
"LLDB.framework",
"Resources",
"Python");
257void ScriptInterpreterPython::ComputePythonDir(
262 llvm::sys::path::remove_filename(path);
263 llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
268 std::replace(path.begin(), path.end(),
'\\',
'/');
272FileSpec ScriptInterpreterPython::GetPythonDir() {
274 FileSpec spec = HostInfo::GetShlibDir();
277 llvm::SmallString<64> path;
280#if defined(__APPLE__)
281 ComputePythonDirForApple(path);
283 ComputePythonDir(path);
291static const char GetInterpreterInfoScript[] = R
"(
295def main(lldb_python_dir, python_exe_relative_path):
297 "lldb-pythonpath": lldb_python_dir,
298 "language": "python",
299 "prefix": sys.prefix,
300 "executable": os.path.join(sys.prefix, python_exe_relative_path)
305static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH;
309 FileSpec python_dir_spec = GetPythonDir();
310 if (!python_dir_spec)
312 PythonScript get_info(GetInterpreterInfoScript);
313 auto info_json = unwrapIgnoringErrors(
314 As<PythonDictionary>(get_info(PythonString(python_dir_spec.
GetPath()),
315 PythonString(python_exe_relative_path))));
318 return info_json.CreateStructuredDictionary();
321void ScriptInterpreterPython::SharedLibraryDirectoryHelper(
332 llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
333 for (
auto it = llvm::sys::path::begin(libdir),
334 end = llvm::sys::path::end(libdir);
343 FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
347llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() {
348 return "Embedded Python interpreter";
351void ScriptInterpreterPython::Initialize() {
352 static llvm::once_flag g_once_flag;
353 llvm::call_once(g_once_flag, []() {
354 PluginManager::RegisterPlugin(GetPluginNameStatic(),
355 GetPluginDescriptionStatic(),
357 ScriptInterpreterPythonImpl::CreateInstance);
358 ScriptInterpreterPythonImpl::Initialize();
362void ScriptInterpreterPython::Terminate() {}
364ScriptInterpreterPythonImpl::Locker::Locker(
365 ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
368 m_teardown_session((on_leave & TearDownSession) == TearDownSession),
369 m_python_interpreter(py_interpreter) {
371 if ((on_entry & InitSession) == InitSession) {
372 if (!DoInitSession(on_entry, in, out, err)) {
374 m_teardown_session =
false;
379bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
381 m_GILState = PyGILState_Ensure();
382 LLDB_LOGV(log,
"Ensured PyGILState. Previous state = {0}locked",
383 m_GILState == PyGILState_UNLOCKED ?
"un" :
"");
390 m_python_interpreter->SetThreadState(PyThreadState_Get());
391 m_python_interpreter->IncrementLockCount();
395bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
398 if (!m_python_interpreter)
400 return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
403bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
405 LLDB_LOGV(log,
"Releasing PyGILState. Returning to state = {0}locked",
406 m_GILState == PyGILState_UNLOCKED ?
"un" :
"");
407 PyGILState_Release(m_GILState);
408 m_python_interpreter->DecrementLockCount();
412bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
413 if (!m_python_interpreter)
415 m_python_interpreter->LeaveSession();
419ScriptInterpreterPythonImpl::Locker::~Locker() {
420 if (m_teardown_session)
425ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(
Debugger &debugger)
426 : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
427 m_saved_stderr(), m_main_module(),
428 m_session_dict(PyInitialValue::
Invalid),
429 m_sys_module_dict(PyInitialValue::
Invalid), m_run_one_line_function(),
430 m_run_one_line_str_global(),
431 m_dictionary_name(m_debugger.GetInstanceName()),
433 m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
434 m_command_thread_state(nullptr) {
436 m_dictionary_name.append(
"_dict");
438 run_string.
Printf(
"%s = dict()", m_dictionary_name.c_str());
440 Locker locker(
this, Locker::AcquireLock, Locker::FreeAcquiredLock);
441 PyRun_SimpleString(run_string.
GetData());
445 "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
446 m_dictionary_name.c_str());
447 PyRun_SimpleString(run_string.
GetData());
452 run_string.
Printf(
"run_one_line (%s, 'from importlib import reload as reload_module')",
453 m_dictionary_name.c_str());
454 PyRun_SimpleString(run_string.
GetData());
462 "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp')",
463 m_dictionary_name.c_str());
464 PyRun_SimpleString(run_string.
GetData());
467 run_string.
Printf(
"run_one_line (%s, 'import lldb.embedded_interpreter; from "
468 "lldb.embedded_interpreter import run_python_interpreter; "
469 "from lldb.embedded_interpreter import run_one_line')",
470 m_dictionary_name.c_str());
471 PyRun_SimpleString(run_string.
GetData());
474 run_string.
Printf(
"run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
476 m_dictionary_name.c_str(), m_debugger.GetID());
477 PyRun_SimpleString(run_string.
GetData());
480ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
486 auto gil_state = PyGILState_Ensure();
487 m_session_dict.Reset();
488 PyGILState_Release(gil_state);
491void ScriptInterpreterPythonImpl::IOHandlerActivated(
IOHandler &io_handler,
493 const char *instructions =
nullptr;
495 switch (m_active_io_handler) {
499 instructions = R
"(Enter your Python command(s). Type 'DONE' to end.
500def function (frame, bp_loc, internal_dict):
501 """frame: the lldb.SBFrame for the location at which you stopped
502 bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
503 internal_dict: an LLDB support object not to be used"""
507 instructions =
"Enter your Python command(s). Type 'DONE' to end.\n";
513 if (output_sp && interactive) {
514 output_sp->PutCString(instructions);
520void ScriptInterpreterPythonImpl::IOHandlerInputComplete(
IOHandler &io_handler,
523 bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
525 switch (m_active_io_handler) {
529 std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
530 (std::vector<std::reference_wrapper<BreakpointOptions>> *)
534 auto data_up = std::make_unique<CommandDataPython>();
537 data_up->user_source.SplitIntoLines(data);
539 if (GenerateBreakpointCommandCallbackData(data_up->user_source,
540 data_up->script_source,
544 auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
546 bp_options.SetCallback(
547 ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
548 }
else if (!batch_mode) {
551 error_sp->Printf(
"Warning: No command attached to breakpoint.\n");
561 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
562 data_up->user_source.SplitIntoLines(data);
564 if (GenerateWatchpointCommandCallbackData(data_up->user_source,
565 data_up->script_source,
568 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
570 ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
571 }
else if (!batch_mode) {
574 error_sp->Printf(
"Warning: No command attached to breakpoint.\n");
584ScriptInterpreterPythonImpl::CreateInstance(
Debugger &debugger) {
585 return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
588void ScriptInterpreterPythonImpl::LeaveSession() {
591 log->
PutCString(
"ScriptInterpreterPythonImpl::LeaveSession()");
594 PyRun_SimpleString(
"lldb.debugger = None; lldb.target = None; lldb.process "
595 "= None; lldb.thread = None; lldb.frame = None");
602 if (PyThreadState_GetDict()) {
603 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
604 if (sys_module_dict.IsValid()) {
605 if (m_saved_stdin.IsValid()) {
606 sys_module_dict.SetItemForKey(PythonString(
"stdin"), m_saved_stdin);
607 m_saved_stdin.Reset();
609 if (m_saved_stdout.IsValid()) {
610 sys_module_dict.SetItemForKey(PythonString(
"stdout"), m_saved_stdout);
611 m_saved_stdout.Reset();
613 if (m_saved_stderr.IsValid()) {
614 sys_module_dict.SetItemForKey(PythonString(
"stderr"), m_saved_stderr);
615 m_saved_stderr.Reset();
620 m_session_is_active =
false;
623bool ScriptInterpreterPythonImpl::SetStdHandle(
FileSP file_sp,
625 PythonObject &save_file,
627 if (!file_sp || !*file_sp) {
631 File &file = *file_sp;
636 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
638 auto new_file = PythonFile::FromFile(file, mode);
640 llvm::consumeError(new_file.takeError());
644 save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
646 sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
650bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
656 if (m_session_is_active) {
659 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
660 ") session is already active, returning without doing anything",
667 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
")",
670 m_session_is_active =
true;
674 if (on_entry_flags & Locker::InitGlobals) {
675 run_string.
Printf(
"run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
676 m_dictionary_name.c_str(), m_debugger.GetID());
678 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64
")",
680 run_string.
PutCString(
"; lldb.target = lldb.debugger.GetSelectedTarget()");
681 run_string.
PutCString(
"; lldb.process = lldb.target.GetProcess()");
682 run_string.
PutCString(
"; lldb.thread = lldb.process.GetSelectedThread ()");
683 run_string.
PutCString(
"; lldb.frame = lldb.thread.GetSelectedFrame ()");
688 run_string.
Printf(
"run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
689 m_dictionary_name.c_str(), m_debugger.GetID());
691 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64
")",
696 PyRun_SimpleString(run_string.
GetData());
699 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
700 if (sys_module_dict.IsValid()) {
703 if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
704 m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
707 if (on_entry_flags & Locker::NoSTDIN) {
708 m_saved_stdin.Reset();
710 if (!SetStdHandle(in_sp,
"stdin", m_saved_stdin,
"r")) {
712 SetStdHandle(top_in_sp,
"stdin", m_saved_stdin,
"r");
716 if (!SetStdHandle(out_sp,
"stdout", m_saved_stdout,
"w")) {
718 SetStdHandle(top_out_sp->GetFileSP(),
"stdout", m_saved_stdout,
"w");
721 if (!SetStdHandle(err_sp,
"stderr", m_saved_stderr,
"w")) {
723 SetStdHandle(top_err_sp->GetFileSP(),
"stderr", m_saved_stderr,
"w");
727 if (PyErr_Occurred())
733PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
734 if (!m_main_module.IsValid())
735 m_main_module = unwrapIgnoringErrors(PythonModule::Import(
"__main__"));
736 return m_main_module;
739PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
740 if (m_session_dict.IsValid())
741 return m_session_dict;
743 PythonObject &main_module = GetMainModule();
744 if (!main_module.IsValid())
745 return m_session_dict;
747 PythonDictionary main_dict(PyRefType::Borrowed,
748 PyModule_GetDict(main_module.get()));
749 if (!main_dict.IsValid())
750 return m_session_dict;
752 m_session_dict = unwrapIgnoringErrors(
753 As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
754 return m_session_dict;
757PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
758 if (m_sys_module_dict.IsValid())
759 return m_sys_module_dict;
760 PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import(
"sys"));
761 m_sys_module_dict = sys_module.GetDictionary();
762 return m_sys_module_dict;
765llvm::Expected<unsigned>
766ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
767 const llvm::StringRef &callable_name) {
768 if (callable_name.empty()) {
769 return llvm::createStringError(
770 llvm::inconvertibleErrorCode(),
771 "called with empty callable name.");
773 Locker py_lock(
this, Locker::AcquireLock |
774 Locker::InitSession |
776 auto dict = PythonModule::MainModule()
777 .ResolveName<PythonDictionary>(m_dictionary_name);
778 auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
779 callable_name, dict);
780 if (!pfunc.IsAllocated()) {
781 return llvm::createStringError(
782 llvm::inconvertibleErrorCode(),
783 "can't find callable: %s", callable_name.str().c_str());
785 llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
787 return arg_info.takeError();
788 return arg_info.get().max_positional_args;
791static std::string GenerateUniqueName(
const char *base_name_wanted,
792 uint32_t &functions_counter,
793 const void *name_token =
nullptr) {
796 if (!base_name_wanted)
797 return std::string();
800 sstr.
Printf(
"%s_%d", base_name_wanted, functions_counter++);
802 sstr.
Printf(
"%s_%p", base_name_wanted, name_token);
807bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
808 if (m_run_one_line_function.IsValid())
811 PythonObject module(PyRefType::Borrowed,
812 PyImport_AddModule(
"lldb.embedded_interpreter"));
813 if (!module.IsValid())
816 PythonDictionary module_dict(PyRefType::Borrowed,
817 PyModule_GetDict(module.get()));
818 if (!module_dict.IsValid())
821 m_run_one_line_function =
822 module_dict.GetItemForKey(PythonString(
"run_one_line"));
823 m_run_one_line_str_global =
824 module_dict.GetItemForKey(PythonString(
"g_run_one_line_str"));
825 return m_run_one_line_function.IsValid();
828bool ScriptInterpreterPythonImpl::ExecuteOneLine(
831 std::string command_str = command.str();
833 if (!m_valid_session)
836 if (!command.empty()) {
843 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
844 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
846 if (!io_redirect_or_error) {
849 "failed to redirect I/O: {0}\n",
850 llvm::fmt_consume(io_redirect_or_error.takeError()));
852 llvm::consumeError(io_redirect_or_error.takeError());
858 bool success =
false;
870 Locker::AcquireLock | Locker::InitSession |
873 Locker::FreeAcquiredLock | Locker::TearDownSession,
878 PythonDictionary &session_dict = GetSessionDictionary();
879 if (session_dict.IsValid()) {
880 if (GetEmbeddedInterpreterModuleObjects()) {
881 if (PyCallable_Check(m_run_one_line_function.get())) {
884 Py_BuildValue(
"(Os)", session_dict.get(), command_str.c_str()));
885 if (pargs.IsValid()) {
886 PythonObject return_value(
888 PyObject_CallObject(m_run_one_line_function.get(),
890 if (return_value.IsValid())
910 "python failed attempting to evaluate '%s'\n", command_str.c_str());
916 result->
AppendError(
"empty command passed to python\n");
920void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
934 IOHandlerSP io_handler_sp(
new IOHandlerPythonInterpreter(debugger,
this));
940bool ScriptInterpreterPythonImpl::Interrupt() {
941#if LLDB_USE_PYTHON_SET_INTERRUPT
945 if (!IsExecutingPython())
949 PyErr_SetInterrupt();
959 if (IsExecutingPython()) {
960 PyThreadState *state = PyThreadState_GET();
962 state = GetThreadState();
964 long tid = state->thread_id;
965 PyThreadState_Swap(state);
966 int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
968 "ScriptInterpreterPythonImpl::Interrupt() sending "
969 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
975 "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
981bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
985 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
986 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
989 if (!io_redirect_or_error) {
990 llvm::consumeError(io_redirect_or_error.takeError());
997 Locker::AcquireLock | Locker::InitSession |
1000 Locker::FreeAcquiredLock | Locker::TearDownSession,
1004 PythonModule &main_module = GetMainModule();
1005 PythonDictionary globals = main_module.GetDictionary();
1007 PythonDictionary locals = GetSessionDictionary();
1008 if (!locals.IsValid())
1009 locals = unwrapIgnoringErrors(
1010 As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1011 if (!locals.IsValid())
1014 Expected<PythonObject> maybe_py_return =
1015 runStringOneLine(in_string, globals, locals);
1017 if (!maybe_py_return) {
1018 llvm::handleAllErrors(
1019 maybe_py_return.takeError(),
1020 [&](PythonException &E) {
1022 if (options.GetMaskoutErrors()) {
1023 if (E.Matches(PyExc_SyntaxError)) {
1029 [](
const llvm::ErrorInfoBase &E) {});
1033 PythonObject py_return = std::move(maybe_py_return.get());
1034 assert(py_return.IsValid());
1036 switch (return_type) {
1037 case eScriptReturnTypeCharPtr:
1039 const char format[3] =
"s#";
1040 return PyArg_Parse(py_return.get(), format, (
char **)ret_value);
1042 case eScriptReturnTypeCharStrOrNone:
1045 const char format[3] =
"z";
1046 return PyArg_Parse(py_return.get(), format, (
char **)ret_value);
1048 case eScriptReturnTypeBool: {
1049 const char format[2] =
"b";
1050 return PyArg_Parse(py_return.get(), format, (
bool *)ret_value);
1052 case eScriptReturnTypeShortInt: {
1053 const char format[2] =
"h";
1054 return PyArg_Parse(py_return.get(), format, (
short *)ret_value);
1056 case eScriptReturnTypeShortIntUnsigned: {
1057 const char format[2] =
"H";
1058 return PyArg_Parse(py_return.get(), format, (
unsigned short *)ret_value);
1060 case eScriptReturnTypeInt: {
1061 const char format[2] =
"i";
1062 return PyArg_Parse(py_return.get(), format, (
int *)ret_value);
1064 case eScriptReturnTypeIntUnsigned: {
1065 const char format[2] =
"I";
1066 return PyArg_Parse(py_return.get(), format, (
unsigned int *)ret_value);
1068 case eScriptReturnTypeLongInt: {
1069 const char format[2] =
"l";
1070 return PyArg_Parse(py_return.get(), format, (
long *)ret_value);
1072 case eScriptReturnTypeLongIntUnsigned: {
1073 const char format[2] =
"k";
1074 return PyArg_Parse(py_return.get(), format, (
unsigned long *)ret_value);
1076 case eScriptReturnTypeLongLong: {
1077 const char format[2] =
"L";
1078 return PyArg_Parse(py_return.get(), format, (
long long *)ret_value);
1080 case eScriptReturnTypeLongLongUnsigned: {
1081 const char format[2] =
"K";
1082 return PyArg_Parse(py_return.get(), format,
1083 (
unsigned long long *)ret_value);
1085 case eScriptReturnTypeFloat: {
1086 const char format[2] =
"f";
1087 return PyArg_Parse(py_return.get(), format, (
float *)ret_value);
1089 case eScriptReturnTypeDouble: {
1090 const char format[2] =
"d";
1091 return PyArg_Parse(py_return.get(), format, (
double *)ret_value);
1093 case eScriptReturnTypeChar: {
1094 const char format[2] =
"c";
1095 return PyArg_Parse(py_return.get(), format, (
char *)ret_value);
1097 case eScriptReturnTypeOpaqueObject: {
1098 *((PyObject **)ret_value) = py_return.release();
1102 llvm_unreachable(
"Fully covered switch!");
1105Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1108 if (in_string ==
nullptr)
1111 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1112 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1115 if (!io_redirect_or_error)
1116 return Status(io_redirect_or_error.takeError());
1121 Locker::AcquireLock | Locker::InitSession |
1124 Locker::FreeAcquiredLock | Locker::TearDownSession,
1128 PythonModule &main_module = GetMainModule();
1129 PythonDictionary globals = main_module.GetDictionary();
1131 PythonDictionary locals = GetSessionDictionary();
1132 if (!locals.IsValid())
1133 locals = unwrapIgnoringErrors(
1134 As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1135 if (!locals.IsValid())
1138 Expected<PythonObject> return_value =
1139 runStringMultiLine(in_string, globals, locals);
1141 if (!return_value) {
1143 llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
1144 llvm::Error error = llvm::createStringError(
1145 llvm::inconvertibleErrorCode(), E.ReadBacktrace());
1146 if (!options.GetMaskoutErrors())
1156void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1157 std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1160 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1161 " ", *
this, &bp_options_vec);
1164void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1167 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1168 " ", *
this, wp_options);
1171Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1176 std::string function_signature = function_name;
1178 llvm::Expected<unsigned> maybe_args =
1179 GetMaxPositionalArgumentsForCallable(function_name);
1181 error.SetErrorStringWithFormat(
1182 "could not get num args: %s",
1183 llvm::toString(maybe_args.takeError()).c_str());
1186 size_t max_args = *maybe_args;
1188 bool uses_extra_args =
false;
1189 if (max_args >= 4) {
1190 uses_extra_args =
true;
1191 function_signature +=
"(frame, bp_loc, extra_args, internal_dict)";
1192 }
else if (max_args >= 3) {
1193 if (extra_args_sp) {
1194 error.SetErrorString(
"cannot pass extra_args to a three argument callback"
1198 uses_extra_args =
false;
1199 function_signature +=
"(frame, bp_loc, internal_dict)";
1201 error.SetErrorStringWithFormat(
"expected 3 or 4 argument "
1202 "function, %s can only take %zu",
1203 function_name, max_args);
1207 SetBreakpointCommandCallback(bp_options, function_signature.c_str(),
1208 extra_args_sp, uses_extra_args,
1213Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1215 std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
1217 error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1218 cmd_data_up->script_source,
1225 std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1227 ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1231Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1234 return SetBreakpointCommandCallback(bp_options, command_body_text, {},
1235 false, is_callback);
1239Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1243 auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1249 data_up->user_source.SplitIntoLines(command_body_text);
1250 Status error = GenerateBreakpointCommandCallbackData(
1251 data_up->user_source, data_up->script_source, uses_extra_args,
1253 if (
error.Success()) {
1255 std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1257 ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1264void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1267 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
1274 data_up->user_source.AppendString(user_input);
1275 data_up->script_source.assign(user_input);
1277 if (GenerateWatchpointCommandCallbackData(
1278 data_up->user_source, data_up->script_source, is_callback)) {
1280 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
1282 ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
1286Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1289 std::string function_def_string(function_def.
CopyList());
1292 function_def_string.c_str(),
1297Status ScriptInterpreterPythonImpl::GenerateFunction(
const char *signature,
1301 int num_lines = input.
GetSize();
1302 if (num_lines == 0) {
1303 error.SetErrorString(
"No input data.");
1307 if (!signature || *signature == 0) {
1308 error.SetErrorString(
"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(
"ScriptInterpreterPythonImpl::GenerateFunction(is_callback="
1336 "true) = ERROR: python function is multiline.");
1340 " __return_val = None");
1342 " def __user_code():");
1346 for (
int i = 0; i < num_lines; ++i) {
1352 " __return_val = __user_code()");
1356 " for key in new_keys:");
1359 " internal_dict[key] = global_dict[key]");
1362 " if key not in old_keys:");
1365 " del global_dict[key]");
1368 " return __return_val");
1371 error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
1376bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1377 StringList &user_input, std::string &output,
const void *name_token) {
1378 static uint32_t num_created_functions = 0;
1383 if (user_input.
GetSize() == 0)
1389 std::string auto_generated_function_name(
1390 GenerateUniqueName(
"lldb_autogen_python_type_print_func",
1391 num_created_functions, name_token));
1392 sstr.
Printf(
"def %s (valobj, internal_dict):",
1393 auto_generated_function_name.c_str());
1395 if (!GenerateFunction(sstr.
GetData(), user_input,
false)
1400 output.assign(auto_generated_function_name);
1404bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1405 StringList &user_input, std::string &output) {
1406 static uint32_t num_created_functions = 0;
1411 if (user_input.
GetSize() == 0)
1414 std::string auto_generated_function_name(GenerateUniqueName(
1415 "lldb_autogen_python_cmd_alias_func", num_created_functions));
1417 sstr.
Printf(
"def %s (debugger, args, exe_ctx, result, internal_dict):",
1418 auto_generated_function_name.c_str());
1420 if (!GenerateFunction(sstr.
GetData(), user_input,
false)
1425 output.assign(auto_generated_function_name);
1429bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1430 StringList &user_input, std::string &output,
const void *name_token) {
1431 static uint32_t num_created_classes = 0;
1433 int num_lines = user_input.
GetSize();
1437 if (user_input.
GetSize() == 0)
1442 std::string auto_generated_class_name(GenerateUniqueName(
1443 "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1449 sstr.
Printf(
"class %s:", auto_generated_class_name.c_str());
1455 for (
int i = 0; i < num_lines; ++i) {
1464 if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).
Success())
1469 output.assign(auto_generated_class_name);
1474ScriptInterpreterPythonImpl::CreateFrameRecognizer(
const char *class_name) {
1475 if (class_name ==
nullptr || class_name[0] ==
'\0')
1478 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1479 PythonObject ret_val = SWIGBridge::LLDBSWIGPython_CreateFrameRecognizer(
1480 class_name, m_dictionary_name.c_str());
1483 new StructuredPythonObject(std::move(ret_val)));
1489 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1491 if (!os_plugin_object_sp)
1498 PythonObject implementor(PyRefType::Borrowed,
1499 (PyObject *)generic->GetValue());
1501 if (!implementor.IsAllocated())
1504 PythonObject py_return(PyRefType::Owned,
1505 SWIGBridge::LLDBSwigPython_GetRecognizedArguments(
1506 implementor.get(), frame_sp));
1509 if (PyErr_Occurred()) {
1513 if (py_return.get()) {
1514 PythonList result_list(PyRefType::Borrowed, py_return.get());
1516 for (
size_t i = 0; i < result_list.GetSize(); i++) {
1517 PyObject *item = result_list.GetItemAtIndex(i).get();
1519 (
lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
1521 SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
1523 result->Append(valobj_sp);
1531ScriptInterpreterPythonImpl::CreateScriptedProcessInterface() {
1532 return std::make_unique<ScriptedProcessPythonInterface>(*
this);
1536ScriptInterpreterPythonImpl::CreateScriptedThreadInterface() {
1537 return std::make_shared<ScriptedThreadPythonInterface>(*
this);
1541ScriptInterpreterPythonImpl::CreateOperatingSystemInterface() {
1542 return std::make_shared<OperatingSystemPythonInterface>(*
this);
1546ScriptInterpreterPythonImpl::CreateStructuredDataFromScriptObject(
1548 void *ptr =
const_cast<void *
>(obj.
GetPointer());
1549 PythonObject py_obj(PyRefType::Borrowed,
static_cast<PyObject *
>(ptr));
1550 if (!py_obj.IsValid() || py_obj.IsNone())
1552 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1553 return py_obj.CreateStructuredObject();
1559 if (class_name ==
nullptr || class_name[0] ==
'\0')
1562 if (!thread_plan_sp.get())
1565 Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
1566 ScriptInterpreterPythonImpl *python_interpreter =
1567 GetPythonInterpreter(debugger);
1569 if (!python_interpreter)
1572 Locker py_lock(
this,
1573 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1574 PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateScriptedThreadPlan(
1575 class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
1576 error_str, thread_plan_sp);
1581 new StructuredPythonObject(std::move(ret_val)));
1584bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop(
1586 bool explains_stop =
true;
1591 Locker py_lock(
this,
1592 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1593 explains_stop = SWIGBridge::LLDBSWIGPythonCallThreadPlan(
1594 generic->GetValue(),
"explains_stop", event, script_error);
1598 return explains_stop;
1601bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop(
1603 bool should_stop =
true;
1608 Locker py_lock(
this,
1609 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1610 should_stop = SWIGBridge::LLDBSWIGPythonCallThreadPlan(
1611 generic->GetValue(),
"should_stop", event, script_error);
1618bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale(
1620 bool is_stale =
true;
1625 Locker py_lock(
this,
1626 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1627 is_stale = SWIGBridge::LLDBSWIGPythonCallThreadPlan(
1628 generic->GetValue(),
"is_stale", (
Event *)
nullptr, script_error);
1635lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState(
1637 bool should_step =
false;
1642 Locker py_lock(
this,
1643 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1644 should_step = SWIGBridge::LLDBSWIGPythonCallThreadPlan(
1645 generic->GetValue(),
"should_step", (
Event *)
nullptr, script_error);
1655ScriptInterpreterPythonImpl::ScriptedThreadPlanGetStopDescription(
1657 bool &script_error) {
1662 script_error =
true;
1665 Locker py_lock(
this,
1666 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1667 return SWIGBridge::LLDBSWIGPythonCallThreadPlan(
1668 generic->GetValue(),
"stop_description", stream, script_error);
1673ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
1677 if (class_name ==
nullptr || class_name[0] ==
'\0')
1683 Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
1684 ScriptInterpreterPythonImpl *python_interpreter =
1685 GetPythonInterpreter(debugger);
1687 if (!python_interpreter)
1690 Locker py_lock(
this,
1691 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1693 PythonObject ret_val =
1694 SWIGBridge::LLDBSwigPythonCreateScriptedBreakpointResolver(
1695 class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
1699 new StructuredPythonObject(std::move(ret_val)));
1702bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
1704 bool should_continue =
false;
1706 if (implementor_sp) {
1707 Locker py_lock(
this,
1708 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1709 should_continue = SWIGBridge::LLDBSwigPythonCallBreakpointResolver(
1710 implementor_sp->GetValue(),
"__callback__", sym_ctx);
1711 if (PyErr_Occurred()) {
1716 return should_continue;
1720ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
1723 if (implementor_sp) {
1724 Locker py_lock(
this,
1725 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1726 depth_as_int = SWIGBridge::LLDBSwigPythonCallBreakpointResolver(
1727 implementor_sp->GetValue(),
"__get_depth__",
nullptr);
1728 if (PyErr_Occurred()) {
1742 TargetSP target_sp,
const char *class_name,
1746 error.SetErrorString(
"No target for scripted stop-hook.");
1750 if (class_name ==
nullptr || class_name[0] ==
'\0') {
1751 error.SetErrorString(
"No class name for scripted stop-hook.");
1755 ScriptInterpreterPythonImpl *python_interpreter =
1756 GetPythonInterpreter(m_debugger);
1758 if (!python_interpreter) {
1759 error.SetErrorString(
"No script interpreter for scripted stop-hook.");
1763 Locker py_lock(
this,
1764 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1766 PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateScriptedStopHook(
1767 target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
1771 new StructuredPythonObject(std::move(ret_val)));
1774bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
1777 assert(implementor_sp &&
1778 "can't call a stop hook with an invalid implementor");
1779 assert(stream_sp &&
"can't call a stop hook with an invalid stream");
1781 Locker py_lock(
this,
1782 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1786 bool ret_val = SWIGBridge::LLDBSwigPythonStopHookCallHandleStop(
1787 implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
1792ScriptInterpreterPythonImpl::LoadPluginModule(
const FileSpec &file_spec,
1794 if (!FileSystem::Instance().Exists(file_spec)) {
1795 error.SetErrorString(
"no such file");
1803 if (LoadScriptingModule(file_spec.
GetPath().c_str(), load_script_options,
1813 if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
1819 Locker py_lock(
this,
1820 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1821 TargetSP target_sp(target->shared_from_this());
1823 auto setting = (PyObject *)SWIGBridge::LLDBSWIGPython_GetDynamicSetting(
1824 generic->GetValue(), setting_name, target_sp);
1829 PythonDictionary py_dict =
1830 unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
1835 return py_dict.CreateStructuredDictionary();
1839ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
1841 if (class_name ==
nullptr || class_name[0] ==
'\0')
1848 Target *target = exe_ctx.GetTargetPtr();
1854 ScriptInterpreterPythonImpl *python_interpreter =
1855 GetPythonInterpreter(debugger);
1857 if (!python_interpreter)
1860 Locker py_lock(
this,
1861 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1862 PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateSyntheticProvider(
1863 class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
1866 new StructuredPythonObject(std::move(ret_val)));
1870ScriptInterpreterPythonImpl::CreateScriptCommandObject(
const char *class_name) {
1871 DebuggerSP debugger_sp(m_debugger.shared_from_this());
1873 if (class_name ==
nullptr || class_name[0] ==
'\0')
1876 if (!debugger_sp.get())
1879 Locker py_lock(
this,
1880 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1881 PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateCommandObject(
1882 class_name, m_dictionary_name.c_str(), debugger_sp);
1884 if (ret_val.IsValid())
1886 new StructuredPythonObject(std::move(ret_val)));
1891bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1892 const char *oneliner, std::string &output,
const void *name_token) {
1895 return GenerateTypeScriptFunction(input, output, name_token);
1898bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1899 const char *oneliner, std::string &output,
const void *name_token) {
1902 return GenerateTypeSynthClass(input, output, name_token);
1905Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
1906 StringList &user_input, std::string &output,
bool has_extra_args,
1908 static uint32_t num_created_functions = 0;
1912 if (user_input.
GetSize() == 0) {
1913 error.SetErrorString(
"No input data.");
1917 std::string auto_generated_function_name(GenerateUniqueName(
1918 "lldb_autogen_python_bp_callback_func_", num_created_functions));
1920 sstr.
Printf(
"def %s (frame, bp_loc, extra_args, internal_dict):",
1921 auto_generated_function_name.c_str());
1923 sstr.
Printf(
"def %s (frame, bp_loc, internal_dict):",
1924 auto_generated_function_name.c_str());
1926 error = GenerateFunction(sstr.
GetData(), user_input, is_callback);
1927 if (!
error.Success())
1931 output.assign(auto_generated_function_name);
1935bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
1936 StringList &user_input, std::string &output,
bool is_callback) {
1937 static uint32_t num_created_functions = 0;
1941 if (user_input.
GetSize() == 0)
1944 std::string auto_generated_function_name(GenerateUniqueName(
1945 "lldb_autogen_python_wp_callback_func_", num_created_functions));
1946 sstr.
Printf(
"def %s (frame, wp, internal_dict):",
1947 auto_generated_function_name.c_str());
1949 if (!GenerateFunction(sstr.
GetData(), user_input, is_callback).Success())
1953 output.assign(auto_generated_function_name);
1957bool ScriptInterpreterPythonImpl::GetScriptedSummary(
1964 if (!valobj.get()) {
1965 retval.assign(
"<no object>");
1969 void *old_callee =
nullptr;
1971 if (callee_wrapper_sp) {
1976 void *new_callee = old_callee;
1979 if (python_function_name && *python_function_name) {
1981 Locker py_lock(
this, Locker::AcquireLock | Locker::InitSession |
1987 Timer scoped_timer(func_cat,
"LLDBSwigPythonCallTypeScript");
1988 ret_val = SWIGBridge::LLDBSwigPythonCallTypeScript(
1989 python_function_name, GetSessionDictionary().get(), valobj,
1990 &new_callee, options_sp, retval);
1994 retval.assign(
"<no function name>");
1998 if (new_callee && old_callee != new_callee) {
1999 Locker py_lock(
this,
2000 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2001 callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
2002 PythonObject(PyRefType::Borrowed,
static_cast<PyObject *
>(new_callee)));
2008bool ScriptInterpreterPythonImpl::FormatterCallbackFunction(
2009 const char *python_function_name,
TypeImplSP type_impl_sp) {
2010 Locker py_lock(
this,
2011 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2012 return SWIGBridge::LLDBSwigPythonFormatterCallbackFunction(
2013 python_function_name, m_dictionary_name.c_str(), type_impl_sp);
2016bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
2019 CommandDataPython *bp_option_data = (CommandDataPython *)baton;
2020 const char *python_function_name = bp_option_data->script_source.c_str();
2026 Target *target = exe_ctx.GetTargetPtr();
2032 ScriptInterpreterPythonImpl *python_interpreter =
2033 GetPythonInterpreter(debugger);
2035 if (!python_interpreter)
2038 if (python_function_name && python_function_name[0]) {
2039 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2041 if (breakpoint_sp) {
2043 breakpoint_sp->FindLocationByID(break_loc_id));
2045 if (stop_frame_sp && bp_loc_sp) {
2046 bool ret_val =
true;
2048 Locker py_lock(python_interpreter, Locker::AcquireLock |
2049 Locker::InitSession |
2051 Expected<bool> maybe_ret_val =
2052 SWIGBridge::LLDBSwigPythonBreakpointCallbackFunction(
2053 python_function_name,
2054 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2055 bp_loc_sp, bp_option_data->m_extra_args);
2057 if (!maybe_ret_val) {
2059 llvm::handleAllErrors(
2060 maybe_ret_val.takeError(),
2061 [&](PythonException &E) {
2062 debugger.GetErrorStream() << E.ReadBacktrace();
2064 [&](
const llvm::ErrorInfoBase &E) {
2065 debugger.GetErrorStream() << E.message();
2069 ret_val = maybe_ret_val.get();
2081bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
2085 const char *python_function_name = wp_option_data->
script_source.c_str();
2091 Target *target = exe_ctx.GetTargetPtr();
2097 ScriptInterpreterPythonImpl *python_interpreter =
2098 GetPythonInterpreter(debugger);
2100 if (!python_interpreter)
2103 if (python_function_name && python_function_name[0]) {
2104 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2107 if (stop_frame_sp && wp_sp) {
2108 bool ret_val =
true;
2110 Locker py_lock(python_interpreter, Locker::AcquireLock |
2111 Locker::InitSession |
2113 ret_val = SWIGBridge::LLDBSwigPythonWatchpointCallbackFunction(
2114 python_function_name,
2115 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2127size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2129 if (!implementor_sp)
2134 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2141 Locker py_lock(
this,
2142 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2143 ret_val = SWIGBridge::LLDBSwigPython_CalculateNumChildren(implementor, max);
2151 if (!implementor_sp)
2157 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2163 Locker py_lock(
this,
2164 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2165 PyObject *child_ptr =
2166 SWIGBridge::LLDBSwigPython_GetChildAtIndex(implementor, idx);
2167 if (child_ptr !=
nullptr && child_ptr != Py_None) {
2169 (
lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2170 if (sb_value_ptr ==
nullptr)
2171 Py_XDECREF(child_ptr);
2173 ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
2176 Py_XDECREF(child_ptr);
2183int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2185 if (!implementor_sp)
2191 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2198 Locker py_lock(
this,
2199 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2200 ret_val = SWIGBridge::LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
2206bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2208 bool ret_val =
false;
2210 if (!implementor_sp)
2216 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2221 Locker py_lock(
this,
2222 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2224 SWIGBridge::LLDBSwigPython_UpdateSynthProviderInstance(implementor);
2230bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2232 bool ret_val =
false;
2234 if (!implementor_sp)
2240 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2245 Locker py_lock(
this,
2246 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2247 ret_val = SWIGBridge::LLDBSwigPython_MightHaveChildrenSynthProviderInstance(
2258 if (!implementor_sp)
2264 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2269 Locker py_lock(
this,
2270 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2271 PyObject *child_ptr =
2272 SWIGBridge::LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2273 if (child_ptr !=
nullptr && child_ptr != Py_None) {
2275 (
lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2276 if (sb_value_ptr ==
nullptr)
2277 Py_XDECREF(child_ptr);
2279 ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
2282 Py_XDECREF(child_ptr);
2289ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2291 Locker py_lock(
this,
2292 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2294 if (!implementor_sp)
2301 PythonObject implementor(PyRefType::Borrowed,
2302 (PyObject *)generic->GetValue());
2303 if (!implementor.IsAllocated())
2306 llvm::Expected<PythonObject> expected_py_return =
2307 implementor.CallMethod(
"get_type_name");
2309 if (!expected_py_return) {
2310 llvm::consumeError(expected_py_return.takeError());
2314 PythonObject py_return = std::move(expected_py_return.get());
2315 if (!py_return.IsAllocated() || !PythonString::Check(py_return.get()))
2318 PythonString type_name(PyRefType::Borrowed, py_return.get());
2322bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2323 const char *impl_function,
Process *process, std::string &output,
2327 error.SetErrorString(
"no process");
2330 if (!impl_function || !impl_function[0]) {
2331 error.SetErrorString(
"no function to execute");
2336 Locker py_lock(
this,
2337 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2338 ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordProcess(
2339 impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
2342 error.SetErrorString(
"python script evaluation failed");
2347bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2348 const char *impl_function,
Thread *thread, std::string &output,
2351 error.SetErrorString(
"no thread");
2354 if (!impl_function || !impl_function[0]) {
2355 error.SetErrorString(
"no function to execute");
2359 Locker py_lock(
this,
2360 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2361 if (std::optional<std::string> result =
2362 SWIGBridge::LLDBSWIGPythonRunScriptKeywordThread(
2363 impl_function, m_dictionary_name.c_str(),
2364 thread->shared_from_this())) {
2365 output = std::move(*result);
2368 error.SetErrorString(
"python script evaluation failed");
2372bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2373 const char *impl_function,
Target *target, std::string &output,
2377 error.SetErrorString(
"no thread");
2380 if (!impl_function || !impl_function[0]) {
2381 error.SetErrorString(
"no function to execute");
2386 TargetSP target_sp(target->shared_from_this());
2387 Locker py_lock(
this,
2388 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2389 ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordTarget(
2390 impl_function, m_dictionary_name.c_str(), target_sp, output);
2392 error.SetErrorString(
"python script evaluation failed");
2397bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2398 const char *impl_function,
StackFrame *frame, std::string &output,
2401 error.SetErrorString(
"no frame");
2404 if (!impl_function || !impl_function[0]) {
2405 error.SetErrorString(
"no function to execute");
2409 Locker py_lock(
this,
2410 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2411 if (std::optional<std::string> result =
2412 SWIGBridge::LLDBSWIGPythonRunScriptKeywordFrame(
2413 impl_function, m_dictionary_name.c_str(),
2414 frame->shared_from_this())) {
2415 output = std::move(*result);
2418 error.SetErrorString(
"python script evaluation failed");
2422bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2423 const char *impl_function,
ValueObject *value, std::string &output,
2427 error.SetErrorString(
"no value");
2430 if (!impl_function || !impl_function[0]) {
2431 error.SetErrorString(
"no function to execute");
2436 Locker py_lock(
this,
2437 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2438 ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordValue(
2439 impl_function, m_dictionary_name.c_str(), value->
GetSP(), output);
2441 error.SetErrorString(
"python script evaluation failed");
2446uint64_t replace_all(std::string &str,
const std::string &oldStr,
2447 const std::string &newStr) {
2449 uint64_t matches = 0;
2450 while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2452 str.replace(pos, oldStr.length(), newStr);
2453 pos += newStr.length();
2458bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2462 namespace fs = llvm::sys::fs;
2463 namespace path = llvm::sys::path;
2469 if (!pathname || !pathname[0]) {
2470 error.SetErrorString(
"empty path");
2474 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2475 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2478 if (!io_redirect_or_error) {
2479 error = io_redirect_or_error.takeError();
2486 Locker py_lock(
this,
2487 Locker::AcquireLock |
2490 Locker::FreeAcquiredLock |
2495 auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2496 if (directory.empty()) {
2497 return llvm::make_error<llvm::StringError>(
2498 "invalid directory name", llvm::inconvertibleErrorCode());
2501 replace_all(directory,
"\\",
"\\\\");
2502 replace_all(directory,
"'",
"\\'");
2506 command_stream.
Printf(
"if not (sys.path.__contains__('%s')):\n "
2507 "sys.path.insert(1,'%s');\n\n",
2508 directory.c_str(), directory.c_str());
2509 bool syspath_retval =
2510 ExecuteMultipleLines(command_stream.
GetData(), exc_options).Success();
2511 if (!syspath_retval) {
2512 return llvm::make_error<llvm::StringError>(
2513 "Python sys.path handling failed", llvm::inconvertibleErrorCode());
2516 return llvm::Error::success();
2519 std::string module_name(pathname);
2520 bool possible_package =
false;
2522 if (extra_search_dir) {
2523 if (llvm::Error e = ExtendSysPath(extra_search_dir.
GetPath())) {
2524 error = std::move(e);
2529 FileSystem::Instance().Resolve(module_file);
2532 std::error_code ec = status(module_file.GetPath(), st);
2534 if (ec || st.type() == fs::file_type::status_error ||
2535 st.type() == fs::file_type::type_unknown ||
2536 st.type() == fs::file_type::file_not_found) {
2539 if (strchr(pathname,
'\\') || strchr(pathname,
'/')) {
2540 error.SetErrorStringWithFormatv(
"invalid pathname '{0}'", pathname);
2544 possible_package =
true;
2545 }
else if (is_directory(st) || is_regular_file(st)) {
2546 if (module_file.GetDirectory().IsEmpty()) {
2547 error.SetErrorStringWithFormatv(
"invalid directory name '{0}'", pathname);
2551 ExtendSysPath(module_file.GetDirectory().GetCString())) {
2552 error = std::move(e);
2555 module_name = module_file.GetFilename().GetCString();
2557 error.SetErrorString(
"no known way to import this module specification");
2563 llvm::StringRef extension = llvm::sys::path::extension(module_name);
2564 if (!extension.empty()) {
2565 if (extension ==
".py")
2566 module_name.resize(module_name.length() - 3);
2567 else if (extension ==
".pyc")
2568 module_name.resize(module_name.length() - 4);
2571 if (!possible_package && module_name.find(
'.') != llvm::StringRef::npos) {
2572 error.SetErrorStringWithFormat(
2573 "Python does not allow dots in module names: %s", module_name.c_str());
2577 if (module_name.find(
'-') != llvm::StringRef::npos) {
2578 error.SetErrorStringWithFormat(
2579 "Python discourages dashes in module names: %s", module_name.c_str());
2585 command_stream.
Clear();
2586 command_stream.
Printf(
"sys.modules.__contains__('%s')", module_name.c_str());
2587 bool does_contain =
false;
2590 const bool does_contain_executed = ExecuteOneLineWithReturn(
2592 ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options);
2594 const bool was_imported_globally = does_contain_executed && does_contain;
2595 const bool was_imported_locally =
2596 GetSessionDictionary()
2597 .GetItemForKey(PythonString(module_name))
2601 command_stream.
Clear();
2603 if (was_imported_globally || was_imported_locally) {
2604 if (!was_imported_locally)
2605 command_stream.
Printf(
"import %s ; reload_module(%s)",
2606 module_name.c_str(), module_name.c_str());
2608 command_stream.
Printf(
"reload_module(%s)", module_name.c_str());
2610 command_stream.
Printf(
"import %s", module_name.c_str());
2612 error = ExecuteMultipleLines(command_stream.
GetData(), exc_options);
2618 if (!SWIGBridge::LLDBSwigPythonCallModuleInit(
2619 module_name.c_str(), m_dictionary_name.c_str(),
2620 m_debugger.shared_from_this())) {
2621 error.SetErrorString(
"calling __lldb_init_module failed");
2627 command_stream.
Clear();
2628 command_stream.
Printf(
"%s", module_name.c_str());
2629 void *module_pyobj =
nullptr;
2630 if (ExecuteOneLineWithReturn(
2632 ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2635 *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2636 PyRefType::Owned,
static_cast<PyObject *
>(module_pyobj)));
2642bool ScriptInterpreterPythonImpl::IsReservedWord(
const char *word) {
2643 if (!word || !word[0])
2646 llvm::StringRef word_sr(word);
2650 if (word_sr.find(
'"') != llvm::StringRef::npos ||
2651 word_sr.find(
'\'') != llvm::StringRef::npos)
2655 command_stream.
Printf(
"keyword.iskeyword('%s')", word);
2661 if (ExecuteOneLineWithReturn(command_stream.
GetData(),
2662 ScriptInterpreter::eScriptReturnTypeBool,
2668ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2670 : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2671 m_old_asynch(debugger_sp->GetAsyncExecution()) {
2672 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2673 m_debugger_sp->SetAsyncExecution(
false);
2674 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2675 m_debugger_sp->SetAsyncExecution(
true);
2678ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
2679 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2680 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2683bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2684 const char *impl_function, llvm::StringRef args,
2688 if (!impl_function) {
2689 error.SetErrorString(
"no function to execute");
2696 if (!debugger_sp.get()) {
2697 error.SetErrorString(
"invalid Debugger pointer");
2701 bool ret_val =
false;
2703 std::string err_msg;
2706 Locker py_lock(
this,
2707 Locker::AcquireLock | Locker::InitSession |
2709 Locker::FreeLock | Locker::TearDownSession);
2711 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2713 std::string args_str = args.str();
2714 ret_val = SWIGBridge::LLDBSwigPythonCallCommand(
2715 impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2716 cmd_retobj, exe_ctx_ref_sp);
2720 error.SetErrorString(
"unable to execute script function");
2721 else if (cmd_retobj.
GetStatus() == eReturnStatusFailed)
2728bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2733 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2734 error.SetErrorString(
"no function to execute");
2741 if (!debugger_sp.get()) {
2742 error.SetErrorString(
"invalid Debugger pointer");
2746 bool ret_val =
false;
2748 std::string err_msg;
2751 Locker py_lock(
this,
2752 Locker::AcquireLock | Locker::InitSession |
2754 Locker::FreeLock | Locker::TearDownSession);
2756 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2758 std::string args_str = args.str();
2759 ret_val = SWIGBridge::LLDBSwigPythonCallCommandObject(
2760 static_cast<PyObject *
>(impl_obj_sp->GetValue()), debugger_sp,
2761 args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
2765 error.SetErrorString(
"unable to execute script function");
2766 else if (cmd_retobj.
GetStatus() == eReturnStatusFailed)
2773bool ScriptInterpreterPythonImpl::RunScriptBasedParsedCommand(
2778 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2779 error.SetErrorString(
"no function to execute");
2786 if (!debugger_sp.get()) {
2787 error.SetErrorString(
"invalid Debugger pointer");
2791 bool ret_val =
false;
2793 std::string err_msg;
2796 Locker py_lock(
this,
2797 Locker::AcquireLock | Locker::InitSession |
2799 Locker::FreeLock | Locker::TearDownSession);
2801 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2806 args_arr_sp->AddStringItem(entry.ref());
2810 ret_val = SWIGBridge::LLDBSwigPythonCallParsedCommandObject(
2811 static_cast<PyObject *
>(impl_obj_sp->GetValue()), debugger_sp,
2812 args_impl, cmd_retobj, exe_ctx_ref_sp);
2816 error.SetErrorString(
"unable to execute script function");
2817 else if (cmd_retobj.
GetStatus() == eReturnStatusFailed)
2828bool ScriptInterpreterPythonImpl::GetDocumentationForItem(
const char *item,
2829 std::string &dest) {
2832 if (!item || !*item)
2835 std::string command(item);
2836 command +=
".__doc__";
2840 char *result_ptr =
nullptr;
2842 if (ExecuteOneLineWithReturn(
2843 command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
2847 dest.assign(result_ptr);
2852 str_stream <<
"Function " << item
2853 <<
" was not found. Containing module might be missing.";
2854 dest = std::string(str_stream.
GetString());
2859bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
2863 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2868 PythonObject implementor(PyRefType::Borrowed,
2869 (PyObject *)cmd_obj_sp->GetValue());
2871 if (!implementor.IsAllocated())
2874 llvm::Expected<PythonObject> expected_py_return =
2875 implementor.CallMethod(
"get_short_help");
2877 if (!expected_py_return) {
2878 llvm::consumeError(expected_py_return.takeError());
2882 PythonObject py_return = std::move(expected_py_return.get());
2884 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2885 PythonString py_string(PyRefType::Borrowed, py_return.get());
2886 llvm::StringRef return_data(py_string.GetString());
2887 dest.assign(return_data.data(), return_data.size());
2894uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
2896 uint32_t result = 0;
2898 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2900 static char callee_name[] =
"get_flags";
2905 PythonObject implementor(PyRefType::Borrowed,
2906 (PyObject *)cmd_obj_sp->GetValue());
2908 if (!implementor.IsAllocated())
2911 PythonObject pmeth(PyRefType::Owned,
2912 PyObject_GetAttrString(implementor.get(), callee_name));
2914 if (PyErr_Occurred())
2917 if (!pmeth.IsAllocated())
2920 if (PyCallable_Check(pmeth.get()) == 0) {
2921 if (PyErr_Occurred())
2926 if (PyErr_Occurred())
2929 long long py_return = unwrapOrSetPythonException(
2930 As<long long>(implementor.CallMethod(callee_name)));
2933 if (PyErr_Occurred()) {
2944ScriptInterpreterPythonImpl::GetOptionsForCommandObject(
2948 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2950 static char callee_name[] =
"get_options_definition";
2955 PythonObject implementor(PyRefType::Borrowed,
2956 (PyObject *)cmd_obj_sp->GetValue());
2958 if (!implementor.IsAllocated())
2961 PythonObject pmeth(PyRefType::Owned,
2962 PyObject_GetAttrString(implementor.get(), callee_name));
2964 if (PyErr_Occurred())
2967 if (!pmeth.IsAllocated())
2970 if (PyCallable_Check(pmeth.get()) == 0) {
2971 if (PyErr_Occurred())
2976 if (PyErr_Occurred())
2979 PythonDictionary py_return = unwrapOrSetPythonException(
2980 As<PythonDictionary>(implementor.CallMethod(callee_name)));
2983 if (PyErr_Occurred()) {
2988 return py_return.CreateStructuredObject();
2992ScriptInterpreterPythonImpl::GetArgumentsForCommandObject(
2996 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2998 static char callee_name[] =
"get_args_definition";
3003 PythonObject implementor(PyRefType::Borrowed,
3004 (PyObject *)cmd_obj_sp->GetValue());
3006 if (!implementor.IsAllocated())
3009 PythonObject pmeth(PyRefType::Owned,
3010 PyObject_GetAttrString(implementor.get(), callee_name));
3012 if (PyErr_Occurred())
3015 if (!pmeth.IsAllocated())
3018 if (PyCallable_Check(pmeth.get()) == 0) {
3019 if (PyErr_Occurred())
3024 if (PyErr_Occurred())
3027 PythonList py_return = unwrapOrSetPythonException(
3028 As<PythonList>(implementor.CallMethod(callee_name)));
3031 if (PyErr_Occurred()) {
3036 return py_return.CreateStructuredObject();
3040ScriptInterpreterPythonImpl::OptionParsingStartedForCommandObject(
3043 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3045 static char callee_name[] =
"option_parsing_started";
3050 PythonObject implementor(PyRefType::Borrowed,
3051 (PyObject *)cmd_obj_sp->GetValue());
3053 if (!implementor.IsAllocated())
3056 PythonObject pmeth(PyRefType::Owned,
3057 PyObject_GetAttrString(implementor.get(), callee_name));
3059 if (PyErr_Occurred())
3062 if (!pmeth.IsAllocated())
3065 if (PyCallable_Check(pmeth.get()) == 0) {
3066 if (PyErr_Occurred())
3071 if (PyErr_Occurred())
3076 unwrapOrSetPythonException(
3077 As<bool>(implementor.CallMethod(callee_name)));
3080 if (PyErr_Occurred()) {
3088ScriptInterpreterPythonImpl::SetOptionValueForCommandObject(
3090 llvm::StringRef long_option, llvm::StringRef value) {
3093 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3095 static char callee_name[] =
"set_option_value";
3100 PythonObject implementor(PyRefType::Borrowed,
3101 (PyObject *)cmd_obj_sp->GetValue());
3103 if (!implementor.IsAllocated())
3106 PythonObject pmeth(PyRefType::Owned,
3107 PyObject_GetAttrString(implementor.get(), callee_name));
3109 if (PyErr_Occurred())
3112 if (!pmeth.IsAllocated())
3115 if (PyCallable_Check(pmeth.get()) == 0) {
3116 if (PyErr_Occurred())
3121 if (PyErr_Occurred())
3127 PythonObject ctx_ref_obj = SWIGBridge::ToSWIGWrapper(exe_ctx_ref_sp);
3129 bool py_return = unwrapOrSetPythonException(
3130 As<bool>(implementor.CallMethod(callee_name, ctx_ref_obj, long_option.str().c_str(),
3131 value.str().c_str())));
3134 if (PyErr_Occurred()) {
3142bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3146 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3151 PythonObject implementor(PyRefType::Borrowed,
3152 (PyObject *)cmd_obj_sp->GetValue());
3154 if (!implementor.IsAllocated())
3157 llvm::Expected<PythonObject> expected_py_return =
3158 implementor.CallMethod(
"get_long_help");
3160 if (!expected_py_return) {
3161 llvm::consumeError(expected_py_return.takeError());
3165 PythonObject py_return = std::move(expected_py_return.get());
3167 bool got_string =
false;
3168 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3169 PythonString str(PyRefType::Borrowed, py_return.get());
3170 llvm::StringRef str_data(str.GetString());
3171 dest.assign(str_data.data(), str_data.size());
3178std::unique_ptr<ScriptInterpreterLocker>
3179ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3180 std::unique_ptr<ScriptInterpreterLocker> py_lock(
new Locker(
3181 this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3182 Locker::FreeLock | Locker::TearDownSession));
3186void ScriptInterpreterPythonImpl::Initialize() {
3193 InitializePythonRAII initialize_guard;
3200 PyRun_SimpleString(
"import sys");
3201 AddToSysPath(AddLocation::End,
".");
3207 if (
FileSpec file_spec = GetPythonDir())
3208 AddToSysPath(AddLocation::Beginning, file_spec.
GetPath(
false));
3209 if (
FileSpec file_spec = HostInfo::GetShlibDir())
3210 AddToSysPath(AddLocation::Beginning, file_spec.
GetPath(
false));
3212 PyRun_SimpleString(
"sys.dont_write_bytecode = 1; import "
3213 "lldb.embedded_interpreter; from "
3214 "lldb.embedded_interpreter import run_python_interpreter; "
3215 "from lldb.embedded_interpreter import run_one_line");
3217#if LLDB_USE_PYTHON_SET_INTERRUPT
3221 RestoreSignalHandlerScope save_sigint(SIGINT);
3227 PyRun_SimpleString(
"def lldb_setup_sigint_handler():\n"
3229 " def signal_handler(sig, frame):\n"
3230 " raise KeyboardInterrupt()\n"
3231 " signal.signal(signal.SIGINT, signal_handler);\n"
3232 "lldb_setup_sigint_handler();\n"
3233 "del lldb_setup_sigint_handler\n");
3237void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3239 std::string path_copy;
3241 std::string statement;
3242 if (location == AddLocation::Beginning) {
3243 statement.assign(
"sys.path.insert(0,\"");
3244 statement.append(path);
3245 statement.append(
"\")");
3247 statement.assign(
"sys.path.append(\"");
3248 statement.append(path);
3249 statement.append(
"\")");
3251 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.
"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
A stream class that can stream formatted output to a file.
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::ThreadPlan > ThreadPlanSP
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::ValueObject > ValueObjectSP
std::shared_ptr< lldb_private::TypeSummaryOptions > TypeSummaryOptionsSP
std::shared_ptr< lldb_private::OperatingSystemInterface > OperatingSystemInterfaceSP
StateType
Process and Thread States.
@ eStateRunning
Process or thread is running and can't be examined.
@ eStateStepping
Process or thread is in the process of stepping and can not be examined.
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