28#include "lldb/Host/Config.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/StringRef.h"
45#include "llvm/Support/Error.h"
46#include "llvm/Support/FileSystem.h"
47#include "llvm/Support/FormatAdapters.h"
66#define LLDBSwigPyInit PyInit__lldb
70#define LLDB_USE_PYTHON_SET_INTERRUPT 0
72#define LLDB_USE_PYTHON_SET_INTERRUPT 1
89struct InitializePythonRAII {
91 InitializePythonRAII() {
94 if (!Py_IsInitialized()) {
95#ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
98 PyImport_AppendInittab(
"readline", initlldb_readline);
105#if LLDB_EMBED_PYTHON_HOME
107 PyConfig_InitPythonConfig(&config);
109 static std::string g_python_home = []() -> std::string {
110 if (llvm::sys::path::is_absolute(LLDB_PYTHON_HOME))
111 return LLDB_PYTHON_HOME;
113 FileSpec spec = HostInfo::GetShlibDir();
119 if (!g_python_home.empty()) {
120 PyConfig_SetBytesString(&config, &config.home, g_python_home.c_str());
123 config.install_signal_handlers = 0;
124 Py_InitializeFromConfig(&config);
125 PyConfig_Clear(&config);
131 PyGILState_STATE gil_state = PyGILState_Ensure();
132 if (gil_state != PyGILState_UNLOCKED)
135 m_was_already_initialized =
true;
136 m_gil_state = gil_state;
138 "Ensured PyGILState. Previous state = {0}",
139 m_gil_state == PyGILState_UNLOCKED ?
"unlocked" :
"locked");
142 ~InitializePythonRAII() {
143 if (m_was_already_initialized) {
145 "Releasing PyGILState. Returning to state = {0}",
146 m_gil_state == PyGILState_UNLOCKED ?
"unlocked" :
"locked");
147 PyGILState_Release(m_gil_state);
155 PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
156 bool m_was_already_initialized =
false;
159#if LLDB_USE_PYTHON_SET_INTERRUPT
162struct RestoreSignalHandlerScope {
164 struct sigaction m_prev_handler;
166 RestoreSignalHandlerScope(
int signal_code) : m_signal_code(signal_code) {
168 std::memset(&m_prev_handler, 0,
sizeof(m_prev_handler));
170 struct sigaction *new_handler =
nullptr;
171 int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler);
172 lldbassert(signal_err == 0 &&
"sigaction failed to read handler");
174 ~RestoreSignalHandlerScope() {
175 int signal_err = ::sigaction(m_signal_code, &m_prev_handler,
nullptr);
176 lldbassert(signal_err == 0 &&
"sigaction failed to restore old handler");
184 auto style = llvm::sys::path::Style::posix;
186 llvm::StringRef path_ref(path.begin(), path.size());
187 auto rbegin = llvm::sys::path::rbegin(path_ref, style);
188 auto rend = llvm::sys::path::rend(path_ref);
189 auto framework = std::find(rbegin, rend,
"LLDB.framework");
190 if (framework == rend) {
194 path.resize(framework - rend);
195 llvm::sys::path::append(path, style,
"LLDB.framework",
"Resources",
"Python");
203 llvm::sys::path::remove_filename(path);
204 llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
209 std::replace(path.begin(), path.end(),
'\\',
'/');
215 FileSpec spec = HostInfo::GetShlibDir();
218 llvm::SmallString<64> path;
221#if defined(__APPLE__)
236def main(lldb_python_dir, python_exe_relative_path):
238 "lldb-pythonpath": lldb_python_dir,
239 "language": "python",
240 "prefix": sys.prefix,
241 "executable": os.path.join(sys.prefix, python_exe_relative_path)
251 if (!python_dir_spec)
259 return info_json.CreateStructuredDictionary();
274 llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
275 for (
auto it = llvm::sys::path::begin(libdir),
276 end = llvm::sys::path::end(libdir);
290 return "Embedded Python interpreter";
298 setenv(
"PYTHONMALLOC",
"malloc",
true);
301 HostInfo::SetSharedLibraryDirectoryHelper(
334 m_GILState == PyGILState_UNLOCKED ?
"unlocked" :
"locked");
356 "Releasing PyGILState. Returning to state = {0}",
357 m_GILState == PyGILState_UNLOCKED ?
"unlocked" :
"locked");
396 "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
404 "run_one_line (%s, 'from importlib import reload as reload_module')",
414 "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp')",
419 run_string.
Printf(
"run_one_line (%s, 'import lldb.embedded_interpreter; from "
420 "lldb.embedded_interpreter import run_python_interpreter; "
421 "from lldb.embedded_interpreter import run_one_line')",
426 run_string.
Printf(
"run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
438 auto gil_state = PyGILState_Ensure();
440 PyGILState_Release(gil_state);
445 const char *instructions =
nullptr;
451 instructions = R
"(Enter your Python command(s). Type 'DONE' to end.
452def function (frame, bp_loc, internal_dict):
453 """frame: the lldb.SBFrame for the location at which you stopped
454 bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
455 internal_dict: an LLDB support object not to be used"""
459 instructions =
"Enter your Python command(s). Type 'DONE' to end.\n";
463 if (instructions && interactive) {
475 bool batch_mode =
m_debugger.GetCommandInterpreter().GetBatchCommandMode();
481 std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
482 (std::vector<std::reference_wrapper<BreakpointOptions>> *)
484 for (BreakpointOptions &bp_options : *bp_options_vec) {
486 auto data_up = std::make_unique<CommandDataPython>();
489 data_up->user_source.SplitIntoLines(data);
492 data_up->script_source,
496 auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
498 bp_options.SetCallback(
500 }
else if (!batch_mode) {
502 LockedStreamFile locked_stream = error_sp->Lock();
503 locked_stream.
Printf(
"Warning: No command attached to breakpoint.\n");
510 WatchpointOptions *wp_options =
512 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
513 data_up->user_source.SplitIntoLines(data);
516 data_up->script_source,
519 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
522 }
else if (!batch_mode) {
524 LockedStreamFile locked_stream = error_sp->Lock();
525 locked_stream.
Printf(
"Warning: No command attached to breakpoint.\n");
535 return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
541 log->
PutCString(
"ScriptInterpreterPythonImpl::LeaveSession()");
544 RunSimpleString(
"lldb.debugger = None; lldb.target = None; lldb.process "
545 "= None; lldb.thread = None; lldb.frame = None");
552 if (PyThreadState_GetDict()) {
554 if (sys_module_dict.
IsValid()) {
577 if (!file_sp || !*file_sp) {
581 File &file = *file_sp;
590 llvm::consumeError(new_file.takeError());
594 save_file = sys_module_dict.
GetItemForKey(PythonString(py_name));
609 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
610 ") session is already active, returning without doing anything",
617 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
")",
625 run_string.
Printf(
"run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
628 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64
")",
630 run_string.
PutCString(
"; lldb.target = lldb.debugger.GetSelectedTarget()");
631 run_string.
PutCString(
"; lldb.process = lldb.target.GetProcess()");
632 run_string.
PutCString(
"; lldb.thread = lldb.process.GetSelectedThread ()");
633 run_string.
PutCString(
"; lldb.frame = lldb.thread.GetSelectedFrame ()");
638 run_string.
Printf(
"run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
641 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64
")",
650 if (sys_module_dict.
IsValid()) {
653 if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
654 m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
679 if (PyErr_Occurred())
700 PyModule_GetDict(main_module.
get()));
701 if (!main_dict.IsValid())
717llvm::Expected<unsigned>
719 const llvm::StringRef &callable_name) {
720 if (callable_name.empty()) {
721 return llvm::createStringError(llvm::inconvertibleErrorCode(),
722 "called with empty callable name.");
729 callable_name, dict);
731 return llvm::createStringError(llvm::inconvertibleErrorCode(),
732 "can't find callable: %s",
733 callable_name.str().c_str());
735 llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
737 return arg_info.takeError();
738 return arg_info.
get().max_positional_args;
742 uint32_t &functions_counter,
743 const void *name_token =
nullptr) {
746 if (!base_name_wanted)
747 return std::string();
750 sstr.
Printf(
"%s_%d", base_name_wanted, functions_counter++);
752 sstr.
Printf(
"%s_%p", base_name_wanted, name_token);
762 PyImport_AddModule(
"lldb.embedded_interpreter"));
763 if (!module.IsValid())
767 PyModule_GetDict(module.get()));
768 if (!module_dict.IsValid())
772 module_dict.GetItemForKey(
PythonString(
"run_one_line"));
774 module_dict.GetItemForKey(
PythonString(
"g_run_one_line_str"));
781 std::string command_str = command.str();
786 if (!command.empty()) {
793 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
796 if (!io_redirect_or_error) {
799 "failed to redirect I/O: {0}\n",
800 llvm::fmt_consume(io_redirect_or_error.takeError()));
802 llvm::consumeError(io_redirect_or_error.takeError());
808 bool success =
false;
834 Py_BuildValue(
"(Os)", session_dict.
get(), command_str.c_str()));
860 "python failed attempting to evaluate '%s'\n", command_str.c_str());
866 result->
AppendError(
"empty command passed to python\n");
891#if LLDB_USE_PYTHON_SET_INTERRUPT
899 PyErr_SetInterrupt();
910 PyThreadState *state = PyThreadState_Get();
914 long tid = PyThread_get_thread_ident();
915 PyThreadState_Swap(state);
916 int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
918 "ScriptInterpreterPythonImpl::Interrupt() sending "
919 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
925 "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
935 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
939 if (!io_redirect_or_error) {
940 llvm::consumeError(io_redirect_or_error.takeError());
964 Expected<PythonObject> maybe_py_return =
967 if (!maybe_py_return) {
968 llvm::handleAllErrors(
969 maybe_py_return.takeError(),
972 if (options.GetMaskoutErrors()) {
973 if (E.Matches(PyExc_SyntaxError)) {
979 [](
const llvm::ErrorInfoBase &E) {});
983 PythonObject py_return = std::move(maybe_py_return.get());
986 switch (return_type) {
987 case eScriptReturnTypeCharPtr:
989 const char format[3] =
"s#";
990 return PyArg_Parse(py_return.
get(), format, (
char **)ret_value);
992 case eScriptReturnTypeCharStrOrNone:
995 const char format[3] =
"z";
996 return PyArg_Parse(py_return.
get(), format, (
char **)ret_value);
998 case eScriptReturnTypeBool: {
999 const char format[2] =
"b";
1000 return PyArg_Parse(py_return.
get(), format, (
bool *)ret_value);
1002 case eScriptReturnTypeShortInt: {
1003 const char format[2] =
"h";
1004 return PyArg_Parse(py_return.
get(), format, (
short *)ret_value);
1006 case eScriptReturnTypeShortIntUnsigned: {
1007 const char format[2] =
"H";
1008 return PyArg_Parse(py_return.
get(), format, (
unsigned short *)ret_value);
1010 case eScriptReturnTypeInt: {
1011 const char format[2] =
"i";
1012 return PyArg_Parse(py_return.
get(), format, (
int *)ret_value);
1014 case eScriptReturnTypeIntUnsigned: {
1015 const char format[2] =
"I";
1016 return PyArg_Parse(py_return.
get(), format, (
unsigned int *)ret_value);
1018 case eScriptReturnTypeLongInt: {
1019 const char format[2] =
"l";
1020 return PyArg_Parse(py_return.
get(), format, (
long *)ret_value);
1022 case eScriptReturnTypeLongIntUnsigned: {
1023 const char format[2] =
"k";
1024 return PyArg_Parse(py_return.
get(), format, (
unsigned long *)ret_value);
1026 case eScriptReturnTypeLongLong: {
1027 const char format[2] =
"L";
1028 return PyArg_Parse(py_return.
get(), format, (
long long *)ret_value);
1030 case eScriptReturnTypeLongLongUnsigned: {
1031 const char format[2] =
"K";
1032 return PyArg_Parse(py_return.
get(), format,
1033 (
unsigned long long *)ret_value);
1035 case eScriptReturnTypeFloat: {
1036 const char format[2] =
"f";
1037 return PyArg_Parse(py_return.
get(), format, (
float *)ret_value);
1039 case eScriptReturnTypeDouble: {
1040 const char format[2] =
"d";
1041 return PyArg_Parse(py_return.
get(), format, (
double *)ret_value);
1043 case eScriptReturnTypeChar: {
1044 const char format[2] =
"c";
1045 return PyArg_Parse(py_return.
get(), format, (
char *)ret_value);
1047 case eScriptReturnTypeOpaqueObject: {
1048 *((PyObject **)ret_value) = py_return.
release();
1052 llvm_unreachable(
"Fully covered switch!");
1058 if (in_string ==
nullptr)
1061 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1065 if (!io_redirect_or_error)
1068 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1088 Expected<PythonObject> return_value =
1091 if (!return_value) {
1093 llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
1094 llvm::Error error = llvm::createStringError(
1095 llvm::inconvertibleErrorCode(), E.ReadBacktrace());
1096 if (!options.GetMaskoutErrors())
1107 std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1110 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1111 " ", *
this, &bp_options_vec);
1117 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1118 " ", *
this, wp_options);
1126 std::string function_signature = function_name;
1128 llvm::Expected<unsigned> maybe_args =
1132 "could not get num args: %s",
1133 llvm::toString(maybe_args.takeError()).c_str());
1136 size_t max_args = *maybe_args;
1138 bool uses_extra_args =
false;
1139 if (max_args >= 4) {
1140 uses_extra_args =
true;
1141 function_signature +=
"(frame, bp_loc, extra_args, internal_dict)";
1142 }
else if (max_args >= 3) {
1143 if (extra_args_sp) {
1145 "cannot pass extra_args to a three argument callback");
1148 uses_extra_args =
false;
1149 function_signature +=
"(frame, bp_loc, internal_dict)";
1152 "function, %s can only take %zu",
1153 function_name, max_args);
1158 extra_args_sp, uses_extra_args,
1165 std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
1168 cmd_data_up->script_source,
1175 std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1185 false, is_callback);
1193 auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1199 data_up->user_source.SplitIntoLines(command_body_text);
1201 data_up->user_source, data_up->script_source, uses_extra_args,
1203 if (
error.Success()) {
1205 std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1216 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
1223 data_up->user_source.AppendString(user_input);
1224 data_up->script_source.assign(user_input);
1227 data_up->user_source, data_up->script_source, is_callback)) {
1229 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
1238 std::string function_def_string(function_def.
CopyList());
1240 function_def_string.c_str());
1251 int num_lines = input.
GetSize();
1252 if (num_lines == 0) {
1257 if (!signature || *signature == 0) {
1263 StringList auto_generated_function;
1266 " global_dict = globals()");
1268 " new_keys = internal_dict.keys()");
1271 " old_keys = global_dict.keys()");
1273 " global_dict.update(internal_dict)");
1280 if (num_lines == 1) {
1286 "ScriptInterpreterPythonImpl::GenerateFunction(is_callback="
1287 "true) = ERROR: python function is multiline.");
1291 " __return_val = None");
1293 " def __user_code():");
1297 for (
int i = 0; i < num_lines; ++i) {
1303 " __return_val = __user_code()");
1307 " for key in new_keys:");
1310 " if key in old_keys:");
1313 " internal_dict[key] = global_dict[key]");
1315 " elif key in global_dict:");
1318 " del global_dict[key]");
1321 " return __return_val");
1330 StringList &user_input, std::string &output,
const void *name_token) {
1331 static uint32_t num_created_functions = 0;
1336 if (user_input.
GetSize() == 0)
1342 std::string auto_generated_function_name(
1344 num_created_functions, name_token));
1345 sstr.
Printf(
"def %s (valobj, internal_dict):",
1346 auto_generated_function_name.c_str());
1353 output.assign(auto_generated_function_name);
1358 StringList &user_input, std::string &output) {
1359 static uint32_t num_created_functions = 0;
1364 if (user_input.
GetSize() == 0)
1368 "lldb_autogen_python_cmd_alias_func", num_created_functions));
1370 sstr.
Printf(
"def %s (debugger, args, exe_ctx, result, internal_dict):",
1371 auto_generated_function_name.c_str());
1378 output.assign(auto_generated_function_name);
1383 StringList &user_input, std::string &output,
const void *name_token) {
1384 static uint32_t num_created_classes = 0;
1386 int num_lines = user_input.
GetSize();
1390 if (user_input.
GetSize() == 0)
1396 "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1402 sstr.
Printf(
"class %s:", auto_generated_class_name.c_str());
1408 for (
int i = 0; i < num_lines; ++i) {
1422 output.assign(auto_generated_class_name);
1428 if (class_name ==
nullptr || class_name[0] ==
'\0')
1444 if (!os_plugin_object_sp)
1452 (PyObject *)generic->GetValue());
1454 if (!implementor.IsAllocated())
1459 implementor.get(), frame_sp));
1462 if (PyErr_Occurred()) {
1466 if (py_return.
get()) {
1469 for (
size_t i = 0; i < result_list.GetSize(); i++) {
1470 PyObject *item = result_list.GetItemAtIndex(i).get();
1476 result->Append(valobj_sp);
1488 if (!os_plugin_object_sp)
1496 (PyObject *)generic->GetValue());
1498 if (!implementor.IsAllocated())
1505 if (PyErr_Occurred()) {
1514 return std::make_unique<ScriptedProcessPythonInterface>(*
this);
1519 return std::make_shared<ScriptedStopHookPythonInterface>(*
this);
1524 return std::make_shared<ScriptedBreakpointPythonInterface>(*
this);
1529 return std::make_shared<ScriptedThreadPythonInterface>(*
this);
1534 return std::make_shared<ScriptedFramePythonInterface>(*
this);
1539 return std::make_shared<ScriptedFrameProviderPythonInterface>(*
this);
1544 return std::make_shared<ScriptedThreadPlanPythonInterface>(*
this);
1549 return std::make_shared<OperatingSystemPythonInterface>(*
this);
1555 void *ptr =
const_cast<void *
>(obj.
GetPointer());
1558 if (!py_obj.IsValid() || py_obj.IsNone())
1560 return py_obj.CreateStructuredObject();
1573 LoadScriptOptions load_script_options =
1574 LoadScriptOptions().SetInitSession(
true).SetSilent(
false);
1585 if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
1593 TargetSP target_sp(target->shared_from_this());
1596 generic->GetValue(), setting_name, target_sp);
1613 if (class_name ==
nullptr || class_name[0] ==
'\0')
1629 if (!python_interpreter)
1645 if (class_name ==
nullptr || class_name[0] ==
'\0')
1648 if (!debugger_sp.get())
1664 const char *oneliner, std::string &output,
const void *name_token) {
1671 const char *oneliner, std::string &output,
const void *name_token) {
1678 StringList &user_input, std::string &output,
bool has_extra_args,
1680 static uint32_t num_created_functions = 0;
1684 if (user_input.
GetSize() == 0) {
1690 "lldb_autogen_python_bp_callback_func_", num_created_functions));
1692 sstr.
Printf(
"def %s (frame, bp_loc, extra_args, internal_dict):",
1693 auto_generated_function_name.c_str());
1695 sstr.
Printf(
"def %s (frame, bp_loc, internal_dict):",
1696 auto_generated_function_name.c_str());
1699 if (!
error.Success())
1703 output.assign(auto_generated_function_name);
1708 StringList &user_input, std::string &output,
bool is_callback) {
1709 static uint32_t num_created_functions = 0;
1713 if (user_input.
GetSize() == 0)
1717 "lldb_autogen_python_wp_callback_func_", num_created_functions));
1718 sstr.
Printf(
"def %s (frame, wp, internal_dict):",
1719 auto_generated_function_name.c_str());
1725 output.assign(auto_generated_function_name);
1736 if (!valobj.get()) {
1737 retval.assign(
"<no object>");
1741 void *old_callee =
nullptr;
1743 if (callee_wrapper_sp) {
1744 generic = callee_wrapper_sp->GetAsGeneric();
1746 old_callee =
generic->GetValue();
1748 void *new_callee = old_callee;
1751 if (python_function_name && *python_function_name) {
1758 static Timer::Category func_cat(
"LLDBSwigPythonCallTypeScript");
1759 Timer scoped_timer(func_cat,
"LLDBSwigPythonCallTypeScript");
1762 &new_callee, options_sp, retval);
1766 retval.assign(
"<no function name>");
1770 if (new_callee && old_callee != new_callee) {
1773 callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
1774 PythonObject(PyRefType::Borrowed,
static_cast<PyObject *
>(new_callee)));
1781 const char *python_function_name,
TypeImplSP type_impl_sp) {
1791 CommandDataPython *bp_option_data = (CommandDataPython *)baton;
1792 const char *python_function_name = bp_option_data->script_source.c_str();
1807 if (!python_interpreter)
1810 if (python_function_name && python_function_name[0]) {
1813 if (breakpoint_sp) {
1815 breakpoint_sp->FindLocationByID(break_loc_id));
1817 if (stop_frame_sp && bp_loc_sp) {
1818 bool ret_val =
true;
1823 Expected<bool> maybe_ret_val =
1825 python_function_name,
1827 bp_loc_sp, bp_option_data->m_extra_args);
1829 if (!maybe_ret_val) {
1831 llvm::handleAllErrors(
1832 maybe_ret_val.takeError(),
1834 *debugger.GetAsyncErrorStream() << E.ReadBacktrace();
1836 [&](
const llvm::ErrorInfoBase &E) {
1837 *debugger.GetAsyncErrorStream() << E.message();
1841 ret_val = maybe_ret_val.get();
1857 const char *python_function_name = wp_option_data->
script_source.c_str();
1872 if (!python_interpreter)
1875 if (python_function_name && python_function_name[0]) {
1879 if (stop_frame_sp && wp_sp) {
1880 bool ret_val =
true;
1886 python_function_name,
1901 if (!implementor_sp)
1906 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
1923 if (!implementor_sp)
1929 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
1937 PyObject *child_ptr =
1939 if (child_ptr !=
nullptr && child_ptr != Py_None) {
1942 if (sb_value_ptr ==
nullptr)
1943 Py_XDECREF(child_ptr);
1948 Py_XDECREF(child_ptr);
1957 if (!implementor_sp)
1958 return llvm::createStringError(
"Type has no child named '%s'", child_name);
1962 return llvm::createStringError(
"Type has no child named '%s'", child_name);
1963 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
1965 return llvm::createStringError(
"Type has no child named '%s'", child_name);
1977 return llvm::createStringError(
"Type has no child named '%s'", child_name);
1983 bool ret_val =
false;
1985 if (!implementor_sp)
1991 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2007 bool ret_val =
false;
2009 if (!implementor_sp)
2015 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2033 if (!implementor_sp)
2039 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2046 PyObject *child_ptr =
2048 if (child_ptr !=
nullptr && child_ptr != Py_None) {
2051 if (sb_value_ptr ==
nullptr)
2052 Py_XDECREF(child_ptr);
2057 Py_XDECREF(child_ptr);
2069 if (!implementor_sp)
2072 StructuredData::Generic *
generic = implementor_sp->GetAsGeneric();
2076 PythonObject implementor(PyRefType::Borrowed,
2077 (PyObject *)generic->GetValue());
2078 if (!implementor.IsAllocated())
2081 llvm::Expected<PythonObject> expected_py_return =
2082 implementor.CallMethod(
"get_type_name");
2084 if (!expected_py_return) {
2085 llvm::consumeError(expected_py_return.takeError());
2089 PythonObject py_return = std::move(expected_py_return.get());
2098 const char *impl_function,
Process *process, std::string &output,
2105 if (!impl_function || !impl_function[0]) {
2123 const char *impl_function,
Thread *thread, std::string &output,
2129 if (!impl_function || !impl_function[0]) {
2136 if (std::optional<std::string> result =
2139 thread->shared_from_this())) {
2140 output = std::move(*result);
2148 const char *impl_function,
Target *target, std::string &output,
2155 if (!impl_function || !impl_function[0]) {
2161 TargetSP target_sp(target->shared_from_this());
2173 const char *impl_function,
StackFrame *frame, std::string &output,
2179 if (!impl_function || !impl_function[0]) {
2186 if (std::optional<std::string> result =
2189 frame->shared_from_this())) {
2190 output = std::move(*result);
2198 const char *impl_function,
ValueObject *value, std::string &output,
2205 if (!impl_function || !impl_function[0]) {
2221uint64_t
replace_all(std::string &str,
const std::string &oldStr,
2222 const std::string &newStr) {
2224 uint64_t matches = 0;
2225 while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2227 str.replace(pos, oldStr.length(), newStr);
2228 pos += newStr.length();
2237 namespace fs = llvm::sys::fs;
2238 namespace path = llvm::sys::path;
2244 if (!pathname || !pathname[0]) {
2249 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2253 if (!io_redirect_or_error) {
2258 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
2270 auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2271 if (directory.empty()) {
2272 return llvm::createStringError(
"invalid directory name");
2279 StreamString command_stream;
2280 command_stream.
Printf(
"if not (sys.path.__contains__('%s')):\n "
2281 "sys.path.insert(1,'%s');\n\n",
2282 directory.c_str(), directory.c_str());
2283 bool syspath_retval =
2285 if (!syspath_retval)
2286 return llvm::createStringError(
"Python sys.path handling failed");
2288 return llvm::Error::success();
2291 std::string module_name(pathname);
2292 bool possible_package =
false;
2294 if (extra_search_dir) {
2295 if (llvm::Error e = ExtendSysPath(extra_search_dir.
GetPath())) {
2300 FileSpec module_file(pathname);
2304 std::error_code ec = status(module_file.GetPath(), st);
2306 if (ec || st.type() == fs::file_type::status_error ||
2307 st.type() == fs::file_type::type_unknown ||
2308 st.type() == fs::file_type::file_not_found) {
2311 if (strchr(pathname,
'\\') || strchr(pathname,
'/')) {
2317 possible_package =
true;
2318 }
else if (is_directory(st) || is_regular_file(st)) {
2319 if (module_file.GetDirectory().IsEmpty()) {
2321 "invalid directory name '{0}'", pathname);
2325 ExtendSysPath(module_file.GetDirectory().GetCString())) {
2329 module_name = module_file.GetFilename().GetCString();
2332 "no known way to import this module specification");
2338 llvm::StringRef extension = llvm::sys::path::extension(module_name);
2339 if (!extension.empty()) {
2340 if (extension ==
".py")
2341 module_name.resize(module_name.length() - 3);
2342 else if (extension ==
".pyc")
2343 module_name.resize(module_name.length() - 4);
2346 if (!possible_package && module_name.find(
'.') != llvm::StringRef::npos) {
2348 "Python does not allow dots in module names: %s", module_name.c_str());
2352 if (module_name.find(
'-') != llvm::StringRef::npos) {
2354 "Python discourages dashes in module names: %s", module_name.c_str());
2359 StreamString command_stream;
2360 command_stream.
Clear();
2361 command_stream.
Printf(
"sys.modules.__contains__('%s')", module_name.c_str());
2362 bool does_contain =
false;
2370 const bool was_imported_globally = does_contain_executed && does_contain;
2371 const bool was_imported_locally =
2377 command_stream.
Clear();
2379 if (was_imported_globally || was_imported_locally) {
2380 if (!was_imported_locally)
2381 command_stream.
Printf(
"import %s ; reload_module(%s)",
2382 module_name.c_str(), module_name.c_str());
2384 command_stream.
Printf(
"reload_module(%s)", module_name.c_str());
2386 command_stream.
Printf(
"import %s", module_name.c_str());
2403 command_stream.
Clear();
2404 command_stream.
Printf(
"%s", module_name.c_str());
2405 void *module_pyobj =
nullptr;
2411 *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2412 PyRefType::Owned,
static_cast<PyObject *
>(module_pyobj)));
2425 if (!word || !word[0])
2428 llvm::StringRef word_sr(word);
2432 if (word_sr.find(
'"') != llvm::StringRef::npos ||
2433 word_sr.find(
'\'') != llvm::StringRef::npos)
2437 command_stream.
Printf(
"keyword.iskeyword('%s')", word);
2452 : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2453 m_old_asynch(debugger_sp->GetAsyncExecution()) {
2462 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2466 const char *impl_function, llvm::StringRef args,
2470 if (!impl_function) {
2478 if (!debugger_sp.get()) {
2483 bool ret_val =
false;
2493 std::string args_str = args.str();
2496 cmd_retobj, exe_ctx_ref_sp);
2513 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2521 if (!debugger_sp.get()) {
2526 bool ret_val =
false;
2536 std::string args_str = args.str();
2538 static_cast<PyObject *
>(impl_obj_sp->GetValue()), debugger_sp,
2539 args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
2556 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2564 if (!debugger_sp.get()) {
2569 bool ret_val =
false;
2581 for (
const Args::ArgEntry &entry : args) {
2582 args_arr_sp->AddStringItem(entry.ref());
2584 StructuredDataImpl args_impl(args_arr_sp);
2587 static_cast<PyObject *
>(impl_obj_sp->GetValue()), debugger_sp,
2588 args_impl, cmd_retobj, exe_ctx_ref_sp);
2600std::optional<std::string>
2603 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2604 return std::nullopt;
2608 if (!debugger_sp.get())
2609 return std::nullopt;
2611 std::optional<std::string> ret_val;
2620 std::string command;
2623 static_cast<PyObject *
>(impl_obj_sp->GetValue()), command);
2631 size_t args_pos,
size_t char_in_arg) {
2633 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2634 return completion_dict_sp;
2640 completion_dict_sp =
2642 static_cast<PyObject *
>(impl_obj_sp->GetValue()), args, args_pos,
2645 return completion_dict_sp;
2651 size_t char_in_arg) {
2653 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2654 return completion_dict_sp;
2662 static_cast<PyObject *
>(impl_obj_sp->GetValue()), long_option,
2665 return completion_dict_sp;
2672 std::string &dest) {
2675 if (!item || !*item)
2678 std::string command(item);
2679 command +=
".__doc__";
2683 char *result_ptr =
nullptr;
2689 dest.assign(result_ptr);
2694 str_stream <<
"Function " << item
2695 <<
" was not found. Containing module might be missing.";
2711 (PyObject *)cmd_obj_sp->GetValue());
2713 if (!implementor.IsAllocated())
2716 llvm::Expected<PythonObject> expected_py_return =
2717 implementor.CallMethod(
"get_short_help");
2719 if (!expected_py_return) {
2720 llvm::consumeError(expected_py_return.takeError());
2724 PythonObject py_return = std::move(expected_py_return.get());
2728 llvm::StringRef return_data(py_string.GetString());
2729 dest.assign(return_data.data(), return_data.size());
2738 uint32_t result = 0;
2742 static char callee_name[] =
"get_flags";
2748 (PyObject *)cmd_obj_sp->GetValue());
2754 PyObject_GetAttrString(implementor.
get(), callee_name));
2756 if (PyErr_Occurred())
2762 if (PyCallable_Check(pmeth.
get()) == 0) {
2763 if (PyErr_Occurred())
2768 if (PyErr_Occurred())
2775 if (PyErr_Occurred()) {
2792 static char callee_name[] =
"get_options_definition";
2798 (PyObject *)cmd_obj_sp->GetValue());
2804 PyObject_GetAttrString(implementor.
get(), callee_name));
2806 if (PyErr_Occurred())
2812 if (PyCallable_Check(pmeth.
get()) == 0) {
2813 if (PyErr_Occurred())
2818 if (PyErr_Occurred())
2825 if (PyErr_Occurred()) {
2840 static char callee_name[] =
"get_args_definition";
2845 PythonObject implementor(PyRefType::Borrowed,
2846 (PyObject *)cmd_obj_sp->GetValue());
2851 PythonObject pmeth(PyRefType::Owned,
2852 PyObject_GetAttrString(implementor.
get(), callee_name));
2854 if (PyErr_Occurred())
2860 if (PyCallable_Check(pmeth.
get()) == 0) {
2861 if (PyErr_Occurred())
2866 if (PyErr_Occurred())
2873 if (PyErr_Occurred()) {
2886 static char callee_name[] =
"option_parsing_started";
2891 PythonObject implementor(PyRefType::Borrowed,
2892 (PyObject *)cmd_obj_sp->GetValue());
2897 PythonObject pmeth(PyRefType::Owned,
2898 PyObject_GetAttrString(implementor.
get(), callee_name));
2900 if (PyErr_Occurred())
2906 if (PyCallable_Check(pmeth.
get()) == 0) {
2907 if (PyErr_Occurred())
2912 if (PyErr_Occurred())
2920 if (PyErr_Occurred()) {
2929 llvm::StringRef long_option, llvm::StringRef value) {
2934 static char callee_name[] =
"set_option_value";
2939 PythonObject implementor(PyRefType::Borrowed,
2940 (PyObject *)cmd_obj_sp->GetValue());
2945 PythonObject pmeth(PyRefType::Owned,
2946 PyObject_GetAttrString(implementor.
get(), callee_name));
2948 if (PyErr_Occurred())
2954 if (PyCallable_Check(pmeth.
get()) == 0) {
2955 if (PyErr_Occurred())
2960 if (PyErr_Occurred())
2965 exe_ctx_ref_sp = std::make_shared<ExecutionContextRef>(exe_ctx);
2969 implementor.
CallMethod(callee_name, ctx_ref_obj,
2970 long_option.str().c_str(), value.str().c_str())));
2973 if (PyErr_Occurred()) {
2991 (PyObject *)cmd_obj_sp->GetValue());
2996 llvm::Expected<PythonObject> expected_py_return =
2999 if (!expected_py_return) {
3000 llvm::consumeError(expected_py_return.takeError());
3004 PythonObject py_return = std::move(expected_py_return.get());
3006 bool got_string =
false;
3008 PythonString str(PyRefType::Borrowed, py_return.
get());
3009 llvm::StringRef str_data(str.GetString());
3010 dest.assign(str_data.data(), str_data.size());
3017std::unique_ptr<ScriptInterpreterLocker>
3019 std::unique_ptr<ScriptInterpreterLocker> py_lock(
new Locker(
3032 InitializePythonRAII initialize_guard;
3048 if (
FileSpec file_spec = HostInfo::GetShlibDir())
3052 "lldb.embedded_interpreter; from "
3053 "lldb.embedded_interpreter import run_python_interpreter; "
3054 "from lldb.embedded_interpreter import run_one_line");
3056#if LLDB_USE_PYTHON_SET_INTERRUPT
3060 RestoreSignalHandlerScope save_sigint(SIGINT);
3068 " def signal_handler(sig, frame):\n"
3069 " raise KeyboardInterrupt()\n"
3070 " signal.signal(signal.SIGINT, signal_handler);\n"
3071 "lldb_setup_sigint_handler();\n"
3072 "del lldb_setup_sigint_handler\n");
3078 std::string statement;
3080 statement.assign(
"sys.path.insert(0,\"");
3081 statement.append(path);
3082 statement.append(
"\")");
3084 statement.assign(
"sys.path.append(\"");
3085 statement.append(path);
3086 statement.append(
"\")");
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
#define LLDB_LOGF(log,...)
#define LLDB_LOGV(log,...)
ScriptInterpreterPythonImpl::Locker Locker
#define LLDB_PLUGIN_DEFINE(PluginName)
PyObject * PyInit__lldb(void)
static std::string GenerateUniqueName(const char *base_name_wanted, uint32_t &functions_counter, const void *name_token=nullptr)
static ScriptInterpreterPythonImpl * GetPythonInterpreter(Debugger &debugger)
static const char python_exe_relative_path[]
uint64_t replace_all(std::string &str, const std::string &oldStr, const std::string &newStr)
static const char GetInterpreterInfoScript[]
#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.
bool GetInteractive() const
void void AppendError(llvm::StringRef in_string)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
lldb::ReturnStatus GetStatus() const
void AppendErrorWithFormatv(const char *format, Args &&...args)
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.
const lldb::StackFrameSP & GetFrameSP() const
Get accessor to get the frame shared pointer.
Target * GetTargetPtr() const
Returns a pointer to the target object.
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.
Status ResolveSymbolicLink(const FileSpec &src, FileSpec &dst)
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
bool IsValid() const override
IsValid.
virtual Status Flush()
Flush the current stream.
lldb::LockableStreamFileSP GetErrorStreamFileSP()
lldb::LockableStreamFileSP GetOutputStreamFileSP()
bool GetInitSession() const
void PutCString(const char *cstr)
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
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
static llvm::Expected< std::unique_ptr< ScriptInterpreterIORedirect > > Create(bool enable_io, Debugger &debugger, CommandReturnObject *result)
Create an IO redirect.
ScriptInterpreterLocker()=default
bool DoInitSession(uint16_t on_entry_flags, lldb::FileSP in, lldb::FileSP out, lldb::FileSP err)
Locker(ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry=AcquireLock|InitSession, uint16_t on_leave=FreeLock|TearDownSession, lldb::FileSP in=nullptr, lldb::FileSP out=nullptr, lldb::FileSP err=nullptr)
PyGILState_STATE m_GILState
ScriptInterpreterPythonImpl * m_python_interpreter
ScriptedCommandSynchronicity m_synch_wanted
SynchronicityHandler(lldb::DebuggerSP, ScriptedCommandSynchronicity)
lldb::DebuggerSP m_debugger_sp
bool GenerateTypeScriptFunction(StringList &input, std::string &output, const void *name_token=nullptr) override
Status GenerateFunction(const char *signature, const StringList &input, bool is_callback) override
bool GenerateScriptAliasFunction(StringList &input, std::string &output) override
lldb_private::Status ExecuteMultipleLines(const char *in_string, const ExecuteScriptOptions &options=ExecuteScriptOptions()) override
bool IsReservedWord(const char *word) override
bool ShouldHide(const StructuredData::ObjectSP &implementor, lldb::StackFrameSP frame_sp) override
python::PythonObject m_run_one_line_function
python::PythonObject m_saved_stderr
bool GenerateWatchpointCommandCallbackData(StringList &input, std::string &output, bool is_callback) override
friend class IOHandlerPythonInterpreter
bool Interrupt() override
ScriptInterpreterPythonImpl(Debugger &debugger)
StructuredData::DictionarySP HandleOptionArgumentCompletionForScriptedCommand(StructuredData::GenericSP impl_obj_sp, llvm::StringRef &long_options, size_t char_in_arg) override
bool RunScriptBasedParsedCommand(StructuredData::GenericSP impl_obj_sp, Args &args, ScriptedCommandSynchronicity synchronicity, lldb_private::CommandReturnObject &cmd_retobj, Status &error, const lldb_private::ExecutionContext &exe_ctx) override
void OptionParsingStartedForCommandObject(StructuredData::GenericSP cmd_obj_sp) override
bool GetLongHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp, std::string &dest) override
lldb::ScriptedStopHookInterfaceSP CreateScriptedStopHookInterface() override
Status SetBreakpointCommandCallbackFunction(BreakpointOptions &bp_options, const char *function_name, StructuredData::ObjectSP extra_args_sp) override
Set a script function as the callback for the breakpoint.
lldb::ScriptedThreadInterfaceSP CreateScriptedThreadInterface() override
static bool BreakpointCallbackFunction(void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
std::string m_dictionary_name
StructuredData::DictionarySP GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target, const char *setting_name, lldb_private::Status &error) override
void CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options, CommandReturnObject &result) override
StructuredData::DictionarySP HandleArgumentCompletionForScriptedCommand(StructuredData::GenericSP impl_obj_sp, std::vector< llvm::StringRef > &args, size_t args_pos, size_t char_in_arg) override
bool RunScriptBasedCommand(const char *impl_function, llvm::StringRef args, ScriptedCommandSynchronicity synchronicity, lldb_private::CommandReturnObject &cmd_retobj, Status &error, const lldb_private::ExecutionContext &exe_ctx) override
python::PythonModule & GetMainModule()
lldb::ScriptedFrameProviderInterfaceSP CreateScriptedFrameProviderInterface() override
std::optional< std::string > GetRepeatCommandForScriptedCommand(StructuredData::GenericSP impl_obj_sp, Args &args) override
python::PythonObject m_saved_stdin
Status SetBreakpointCommandCallback(BreakpointOptions &bp_options, const char *callback_body, bool is_callback) override
Set the callback body text into the callback for the breakpoint.
PyThreadState * GetThreadState()
StructuredData::ObjectSP GetArgumentsForCommandObject(StructuredData::GenericSP cmd_obj_sp) override
bool EnterSession(uint16_t on_entry_flags, lldb::FileSP in, lldb::FileSP out, lldb::FileSP err)
void SetWatchpointCommandCallback(WatchpointOptions *wp_options, const char *user_input, bool is_callback) override
Set a one-liner as the callback for the watchpoint.
lldb::ValueObjectSP GetSyntheticValue(const StructuredData::ObjectSP &implementor) override
std::unique_ptr< ScriptInterpreterLocker > AcquireInterpreterLock() override
void CollectDataForBreakpointCommandCallback(std::vector< std::reference_wrapper< BreakpointOptions > > &bp_options_vec, CommandReturnObject &result) override
python::PythonDictionary m_session_dict
uint32_t IsExecutingPython()
bool UpdateSynthProviderInstance(const StructuredData::ObjectSP &implementor) override
static void AddToSysPath(AddLocation location, std::string path)
python::PythonDictionary & GetSessionDictionary()
bool MightHaveChildrenSynthProviderInstance(const StructuredData::ObjectSP &implementor) override
bool LoadScriptingModule(const char *filename, const LoadScriptOptions &options, lldb_private::Status &error, StructuredData::ObjectSP *module_sp=nullptr, FileSpec extra_search_dir={}, lldb::TargetSP loaded_into_target_sp={}) override
StructuredData::GenericSP CreateFrameRecognizer(const char *class_name) override
ConstString GetSyntheticTypeName(const StructuredData::ObjectSP &implementor) override
Status GenerateBreakpointCommandCallbackData(StringList &input, std::string &output, bool has_extra_args, bool is_callback) override
PyThreadState * m_command_thread_state
lldb::OperatingSystemInterfaceSP CreateOperatingSystemInterface() override
bool SetOptionValueForCommandObject(StructuredData::GenericSP cmd_obj_sp, ExecutionContext *exe_ctx, llvm::StringRef long_option, llvm::StringRef value) override
python::PythonObject m_saved_stdout
llvm::Expected< uint32_t > GetIndexOfChildWithName(const StructuredData::ObjectSP &implementor, const char *child_name) override
bool FormatterCallbackFunction(const char *function_name, lldb::TypeImplSP type_impl_sp) override
void ExecuteInterpreterLoop() override
Status ExportFunctionDefinitionToInterpreter(StringList &function_def) override
StructuredData::ObjectSP CreateSyntheticScriptedProvider(const char *class_name, lldb::ValueObjectSP valobj) override
bool ExecuteOneLine(llvm::StringRef command, CommandReturnObject *result, const ExecuteScriptOptions &options=ExecuteScriptOptions()) override
bool GetDocumentationForItem(const char *item, std::string &dest) override
In Python, a special attribute doc contains the docstring for an object (function,...
uint32_t GetFlagsForCommandObject(StructuredData::GenericSP cmd_obj_sp) override
void IOHandlerInputComplete(IOHandler &io_handler, std::string &data) override
Called when a line or lines have been retrieved.
void IOHandlerActivated(IOHandler &io_handler, bool interactive) override
bool GetScriptedSummary(const char *function_name, lldb::ValueObjectSP valobj, StructuredData::ObjectSP &callee_wrapper_sp, const TypeSummaryOptions &options, std::string &retval) override
lldb::ScriptedFrameInterfaceSP CreateScriptedFrameInterface() override
lldb::ScriptedProcessInterfaceUP CreateScriptedProcessInterface() override
StructuredData::GenericSP CreateScriptCommandObject(const char *class_name) override
bool m_pty_secondary_is_open
python::PythonDictionary m_sys_module_dict
size_t CalculateNumChildren(const StructuredData::ObjectSP &implementor, uint32_t max) override
bool ExecuteOneLineWithReturn(llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type, void *ret_value, const ExecuteScriptOptions &options=ExecuteScriptOptions()) override
lldb::ScriptedBreakpointInterfaceSP CreateScriptedBreakpointInterface() override
bool RunScriptFormatKeyword(const char *impl_function, Process *process, std::string &output, Status &error) override
python::PythonDictionary & GetSysModuleDictionary()
bool SetStdHandle(lldb::FileSP file, const char *py_name, python::PythonObject &save_file, const char *mode)
bool GetEmbeddedInterpreterModuleObjects()
lldb::ValueObjectSP GetChildAtIndex(const StructuredData::ObjectSP &implementor, uint32_t idx) override
bool GenerateTypeSynthClass(StringList &input, std::string &output, const void *name_token=nullptr) override
StructuredData::ObjectSP CreateStructuredDataFromScriptObject(ScriptObject obj) override
StructuredData::ObjectSP GetOptionsForCommandObject(StructuredData::GenericSP cmd_obj_sp) override
StructuredData::ObjectSP LoadPluginModule(const FileSpec &file_spec, lldb_private::Status &error) override
bool GetShortHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp, std::string &dest) override
python::PythonModule m_main_module
llvm::Expected< unsigned > GetMaxPositionalArgumentsForCallable(const llvm::StringRef &callable_name) override
python::PythonObject m_run_one_line_str_global
static bool WatchpointCallbackFunction(void *baton, StoppointCallbackContext *context, lldb::user_id_t watch_id)
~ScriptInterpreterPythonImpl() override
static lldb::ScriptInterpreterSP CreateInstance(Debugger &debugger)
lldb::ValueObjectListSP GetRecognizedArguments(const StructuredData::ObjectSP &implementor, lldb::StackFrameSP frame_sp) override
lldb::ScriptedThreadPlanInterfaceSP CreateScriptedThreadPlanInterface() override
ActiveIOHandler m_active_io_handler
Abstract interface for the Python script interpreter.
static void ComputePythonDir(llvm::SmallVectorImpl< char > &path)
static llvm::StringRef GetPluginNameStatic()
static void ComputePythonDirForApple(llvm::SmallVectorImpl< char > &path)
ScriptInterpreterPython(Debugger &debugger)
static llvm::StringRef GetPluginDescriptionStatic()
StructuredData::DictionarySP GetInterpreterInfo() override
static FileSpec GetPythonDir()
static void SharedLibraryDirectoryHelper(FileSpec &this_file)
@ eScriptReturnTypeOpaqueObject
@ eScriptReturnTypeCharStrOrNone
const void * GetPointer() const
This base class provides an interface to stack frames.
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
static Status FromErrorString(const char *str)
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
bool Success() const
Test for success condition.
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
ExecutionContextRef exe_ctx_ref
void Flush() override
Flush the stream.
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
lldb::BreakpointSP GetBreakpointByID(lldb::break_id_t break_id)
Debugger & GetDebugger() const
WatchpointList & GetWatchpointList()
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.
StructuredData::DictionarySP CreateStructuredDictionary() const
PythonObject GetItemForKey(const PythonObject &key) const
void SetItemForKey(const PythonObject &key, const PythonObject &value)
static llvm::Expected< PythonFile > FromFile(File &file, const char *mode=nullptr)
static PythonModule MainModule()
PythonDictionary GetDictionary() const
static llvm::Expected< PythonModule > Import(const llvm::Twine &name)
PythonObject ResolveName(llvm::StringRef name) const
StructuredData::ObjectSP CreateStructuredObject() const
static PythonObject ResolveNameWithDictionary(llvm::StringRef name, const PythonDictionary &dict)
llvm::Expected< PythonObject > GetAttribute(const llvm::Twine &name) const
llvm::Expected< PythonObject > CallMethod(const char *name, const T &... t) const
static bool Check(PyObject *py_obj)
static PyObject * LLDBSwigPython_GetRecognizedArguments(PyObject *implementor, const lldb::StackFrameSP &frame_sp)
static bool LLDBSWIGPythonRunScriptKeywordValue(const char *python_function_name, const char *session_dictionary_name, const lldb::ValueObjectSP &value, std::string &output)
static bool LLDBSwigPythonCallParsedCommandObject(PyObject *implementor, lldb::DebuggerSP debugger, StructuredDataImpl &args_impl, lldb_private::CommandReturnObject &cmd_retobj, lldb::ExecutionContextRefSP exe_ctx_ref_sp)
static bool LLDBSwigPythonCallTypeScript(const char *python_function_name, const void *session_dictionary, const lldb::ValueObjectSP &valobj_sp, void **pyfunct_wrapper, const lldb::TypeSummaryOptionsSP &options_sp, std::string &retval)
static void * LLDBSWIGPython_GetDynamicSetting(void *module, const char *setting, const lldb::TargetSP &target_sp)
static lldb::ValueObjectSP LLDBSWIGPython_GetValueObjectSPFromSBValue(void *data)
static std::optional< std::string > LLDBSWIGPythonRunScriptKeywordThread(const char *python_function_name, const char *session_dictionary_name, lldb::ThreadSP thread)
static StructuredData::DictionarySP LLDBSwigPythonHandleArgumentCompletionForScriptedCommand(PyObject *implementor, std::vector< llvm::StringRef > &args_impl, size_t args_pos, size_t pos_in_arg)
static bool LLDBSwigPythonCallCommand(const char *python_function_name, const char *session_dictionary_name, lldb::DebuggerSP debugger, const char *args, lldb_private::CommandReturnObject &cmd_retobj, lldb::ExecutionContextRefSP exe_ctx_ref_sp)
static PyObject * LLDBSwigPython_GetValueSynthProviderInstance(PyObject *implementor)
static bool LLDBSwigPython_UpdateSynthProviderInstance(PyObject *implementor)
static StructuredData::DictionarySP LLDBSwigPythonHandleOptionArgumentCompletionForScriptedCommand(PyObject *implementor, llvm::StringRef &long_option, size_t pos_in_arg)
static bool LLDBSWIGPythonRunScriptKeywordTarget(const char *python_function_name, const char *session_dictionary_name, const lldb::TargetSP &target, std::string &output)
static uint32_t LLDBSwigPython_GetIndexOfChildWithName(PyObject *implementor, const char *child_name)
static std::optional< std::string > LLDBSwigPythonGetRepeatCommandForScriptedCommand(PyObject *implementor, std::string &command)
static std::optional< std::string > LLDBSWIGPythonRunScriptKeywordFrame(const char *python_function_name, const char *session_dictionary_name, lldb::StackFrameSP frame)
static PyObject * LLDBSwigPython_GetChildAtIndex(PyObject *implementor, uint32_t idx)
static bool LLDBSWIGPythonRunScriptKeywordProcess(const char *python_function_name, const char *session_dictionary_name, const lldb::ProcessSP &process, std::string &output)
static bool LLDBSwigPythonFormatterCallbackFunction(const char *python_function_name, const char *session_dictionary_name, lldb::TypeImplSP type_impl_sp)
static bool LLDBSwigPythonCallModuleInit(const char *python_module_name, const char *session_dictionary_name, lldb::DebuggerSP debugger)
static python::PythonObject LLDBSwigPythonCreateSyntheticProvider(const char *python_class_name, const char *session_dictionary_name, const lldb::ValueObjectSP &valobj_sp)
static bool LLDBSwigPythonWatchpointCallbackFunction(const char *python_function_name, const char *session_dictionary_name, const lldb::StackFrameSP &sb_frame, const lldb::WatchpointSP &sb_wp)
static python::PythonObject LLDBSWIGPython_CreateFrameRecognizer(const char *python_class_name, const char *session_dictionary_name)
static size_t LLDBSwigPython_CalculateNumChildren(PyObject *implementor, uint32_t max)
static PythonObject ToSWIGWrapper(std::unique_ptr< lldb::SBValue > value_sb)
static bool LLDBSwigPythonCallCommandObject(PyObject *implementor, lldb::DebuggerSP debugger, const char *args, lldb_private::CommandReturnObject &cmd_retobj, lldb::ExecutionContextRefSP exe_ctx_ref_sp)
static bool LLDBSwigPython_MightHaveChildrenSynthProviderInstance(PyObject *implementor)
static bool LLDBSwigPythonCallModuleNewTarget(const char *python_module_name, const char *session_dictionary_name, lldb::TargetSP target)
static python::PythonObject LLDBSwigPythonCreateCommandObject(const char *python_class_name, const char *session_dictionary_name, lldb::DebuggerSP debugger_sp)
static bool LLDBSwigPython_ShouldHide(PyObject *implementor, const lldb::StackFrameSP &frame_sp)
static llvm::Expected< bool > LLDBSwigPythonBreakpointCallbackFunction(const char *python_function_name, const char *session_dictionary_name, const lldb::StackFrameSP &sb_frame, const lldb::BreakpointLocationSP &sb_bp_loc, const lldb_private::StructuredDataImpl &args_impl)
llvm::Expected< T > As(llvm::Expected< PythonObject > &&obj)
T unwrapOrSetPythonException(llvm::Expected< T > expected)
T unwrapIgnoringErrors(llvm::Expected< T > expected)
llvm::Expected< PythonObject > runStringMultiLine(const llvm::Twine &string, const PythonDictionary &globals, const PythonDictionary &locals)
int RunSimpleString(const char *str)
llvm::Expected< long long > As< long long >(llvm::Expected< PythonObject > &&obj)
void * LLDBSWIGPython_CastPyObjectToSBValue(PyObject *data)
llvm::Expected< bool > As< bool >(llvm::Expected< PythonObject > &&obj)
llvm::Expected< PythonObject > runStringOneLine(const llvm::Twine &string, const PythonDictionary &globals, const PythonDictionary &locals)
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
@ eScriptedCommandSynchronicityAsynchronous
@ eScriptedCommandSynchronicitySynchronous
@ eScriptedCommandSynchronicityCurrentValue
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::ScriptedBreakpointInterface > ScriptedBreakpointInterfaceSP
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::ScriptedFrameProviderInterface > ScriptedFrameProviderInterfaceSP
std::shared_ptr< lldb_private::LockableStreamFile > LockableStreamFileSP
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::ScriptedFrameInterface > ScriptedFrameInterfaceSP
std::shared_ptr< lldb_private::ExecutionContextRef > ExecutionContextRefSP
lldb::user_id_t GetID() const
Get accessor for the user ID.
std::string script_source