9#include "lldb/Host/Config.h"
46#include "llvm/ADT/STLExtras.h"
47#include "llvm/ADT/StringRef.h"
48#include "llvm/Support/Error.h"
49#include "llvm/Support/FileSystem.h"
50#include "llvm/Support/FormatAdapters.h"
67extern "C" PyObject *PyInit__lldb(
void);
69#define LLDBSwigPyInit PyInit__lldb
73#define LLDB_USE_PYTHON_SET_INTERRUPT 0
75#define LLDB_USE_PYTHON_SET_INTERRUPT 1
78static ScriptInterpreterPythonImpl *GetPythonInterpreter(
Debugger &debugger) {
81 return static_cast<ScriptInterpreterPythonImpl *
>(script_interpreter);
92struct InitializePythonRAII {
94 InitializePythonRAII() {
97 if (!Py_IsInitialized()) {
98#ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
101 PyImport_AppendInittab(
"readline", initlldb_readline);
105 PyImport_AppendInittab(
"_lldb", LLDBSwigPyInit);
108#if LLDB_EMBED_PYTHON_HOME
110 PyConfig_InitPythonConfig(&config);
112 static std::string g_python_home = []() -> std::string {
113 if (llvm::sys::path::is_absolute(LLDB_PYTHON_HOME))
114 return LLDB_PYTHON_HOME;
116 FileSpec spec = HostInfo::GetShlibDir();
119 spec.AppendPathComponent(LLDB_PYTHON_HOME);
120 return spec.GetPath();
122 if (!g_python_home.empty()) {
123 PyConfig_SetBytesString(&config, &config.home, g_python_home.c_str());
126 config.install_signal_handlers = 0;
127 Py_InitializeFromConfig(&config);
128 PyConfig_Clear(&config);
134 PyGILState_STATE gil_state = PyGILState_Ensure();
135 if (gil_state != PyGILState_UNLOCKED)
138 m_was_already_initialized =
true;
139 m_gil_state = gil_state;
141 "Ensured PyGILState. Previous state = {0}",
142 m_gil_state == PyGILState_UNLOCKED ?
"unlocked" :
"locked");
145 ~InitializePythonRAII() {
146 if (m_was_already_initialized) {
148 "Releasing PyGILState. Returning to state = {0}",
149 m_gil_state == PyGILState_UNLOCKED ?
"unlocked" :
"locked");
150 PyGILState_Release(m_gil_state);
158 PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
159 bool m_was_already_initialized =
false;
162#if LLDB_USE_PYTHON_SET_INTERRUPT
165struct RestoreSignalHandlerScope {
167 struct sigaction m_prev_handler;
169 RestoreSignalHandlerScope(
int signal_code) : m_signal_code(signal_code) {
171 std::memset(&m_prev_handler, 0,
sizeof(m_prev_handler));
173 struct sigaction *new_handler =
nullptr;
174 int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler);
175 lldbassert(signal_err == 0 &&
"sigaction failed to read handler");
177 ~RestoreSignalHandlerScope() {
178 int signal_err = ::sigaction(m_signal_code, &m_prev_handler,
nullptr);
179 lldbassert(signal_err == 0 &&
"sigaction failed to restore old handler");
185void ScriptInterpreterPython::ComputePythonDirForApple(
187 auto style = llvm::sys::path::Style::posix;
189 llvm::StringRef path_ref(path.begin(), path.size());
190 auto rbegin = llvm::sys::path::rbegin(path_ref, style);
191 auto rend = llvm::sys::path::rend(path_ref);
192 auto framework = std::find(rbegin, rend,
"LLDB.framework");
193 if (framework == rend) {
194 ComputePythonDir(path);
197 path.resize(framework - rend);
198 llvm::sys::path::append(path, style,
"LLDB.framework",
"Resources",
"Python");
201void ScriptInterpreterPython::ComputePythonDir(
206 llvm::sys::path::remove_filename(path);
207 llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
212 std::replace(path.begin(), path.end(),
'\\',
'/');
216FileSpec ScriptInterpreterPython::GetPythonDir() {
218 FileSpec spec = HostInfo::GetShlibDir();
221 llvm::SmallString<64> path;
224#if defined(__APPLE__)
225 ComputePythonDirForApple(path);
227 ComputePythonDir(path);
229 spec.SetDirectory(path);
235static const char GetInterpreterInfoScript[] = R
"(
239def main(lldb_python_dir, python_exe_relative_path):
241 "lldb-pythonpath": lldb_python_dir,
242 "language": "python",
243 "prefix": sys.prefix,
244 "executable": os.path.join(sys.prefix, python_exe_relative_path)
249static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH;
253 FileSpec python_dir_spec = GetPythonDir();
254 if (!python_dir_spec)
256 PythonScript get_info(GetInterpreterInfoScript);
257 auto info_json = unwrapIgnoringErrors(
258 As<PythonDictionary>(get_info(PythonString(python_dir_spec.GetPath()),
259 PythonString(python_exe_relative_path))));
262 return info_json.CreateStructuredDictionary();
265void ScriptInterpreterPython::SharedLibraryDirectoryHelper(
273 if (this_file.GetFileNameExtension() ==
".pyd") {
274 this_file.RemoveLastPathComponent();
275 this_file.RemoveLastPathComponent();
276 llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
277 for (
auto it = llvm::sys::path::begin(libdir),
278 end = llvm::sys::path::end(libdir);
280 this_file.RemoveLastPathComponent();
281 this_file.AppendPathComponent(
"bin");
282 this_file.AppendPathComponent(
"liblldb.dll");
291llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() {
292 return "Embedded Python interpreter";
295void ScriptInterpreterPython::Initialize() {
296 static llvm::once_flag g_once_flag;
297 llvm::call_once(g_once_flag, []() {
299 GetPluginDescriptionStatic(),
301 ScriptInterpreterPythonImpl::CreateInstance);
302 ScriptInterpreterPythonImpl::Initialize();
306void ScriptInterpreterPython::Terminate() {}
308ScriptInterpreterPythonImpl::Locker::Locker(
309 ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
312 m_teardown_session((on_leave & TearDownSession) == TearDownSession),
313 m_python_interpreter(py_interpreter) {
315 if ((on_entry & InitSession) == InitSession) {
316 if (!DoInitSession(on_entry, in, out, err)) {
318 m_teardown_session =
false;
323bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
324 m_GILState = PyGILState_Ensure();
326 m_GILState == PyGILState_UNLOCKED ?
"unlocked" :
"locked");
333 m_python_interpreter->SetThreadState(PyThreadState_Get());
334 m_python_interpreter->IncrementLockCount();
338bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
341 if (!m_python_interpreter)
343 return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
346bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
348 "Releasing PyGILState. Returning to state = {0}",
349 m_GILState == PyGILState_UNLOCKED ?
"unlocked" :
"locked");
350 PyGILState_Release(m_GILState);
351 m_python_interpreter->DecrementLockCount();
355bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
356 if (!m_python_interpreter)
358 m_python_interpreter->LeaveSession();
362ScriptInterpreterPythonImpl::Locker::~Locker() {
363 if (m_teardown_session)
368ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(
Debugger &debugger)
369 : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
370 m_saved_stderr(), m_main_module(),
371 m_session_dict(PyInitialValue::
Invalid),
372 m_sys_module_dict(PyInitialValue::
Invalid), m_run_one_line_function(),
373 m_run_one_line_str_global(),
374 m_dictionary_name(m_debugger.GetInstanceName()),
376 m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
377 m_command_thread_state(nullptr) {
379 m_dictionary_name.append(
"_dict");
381 run_string.
Printf(
"%s = dict()", m_dictionary_name.c_str());
383 Locker locker(
this, Locker::AcquireLock, Locker::FreeAcquiredLock);
384 RunSimpleString(run_string.
GetData());
388 "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
389 m_dictionary_name.c_str());
390 RunSimpleString(run_string.
GetData());
396 "run_one_line (%s, 'from importlib import reload as reload_module')",
397 m_dictionary_name.c_str());
398 RunSimpleString(run_string.
GetData());
406 "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp')",
407 m_dictionary_name.c_str());
408 RunSimpleString(run_string.
GetData());
411 run_string.
Printf(
"run_one_line (%s, 'import lldb.embedded_interpreter; from "
412 "lldb.embedded_interpreter import run_python_interpreter; "
413 "from lldb.embedded_interpreter import run_one_line')",
414 m_dictionary_name.c_str());
415 RunSimpleString(run_string.
GetData());
418 run_string.
Printf(
"run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
420 m_dictionary_name.c_str(), m_debugger.GetID());
421 RunSimpleString(run_string.
GetData());
424ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
430 auto gil_state = PyGILState_Ensure();
431 m_session_dict.Reset();
432 PyGILState_Release(gil_state);
435void ScriptInterpreterPythonImpl::IOHandlerActivated(
IOHandler &io_handler,
437 const char *instructions =
nullptr;
439 switch (m_active_io_handler) {
443 instructions = R
"(Enter your Python command(s). Type 'DONE' to end.
444def function (frame, bp_loc, internal_dict):
445 """frame: the lldb.SBFrame for the location at which you stopped
446 bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
447 internal_dict: an LLDB support object not to be used"""
451 instructions =
"Enter your Python command(s). Type 'DONE' to end.\n";
455 if (instructions && interactive) {
459 locked_stream.
Flush();
464void ScriptInterpreterPythonImpl::IOHandlerInputComplete(
IOHandler &io_handler,
467 bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
469 switch (m_active_io_handler) {
473 std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
474 (std::vector<std::reference_wrapper<BreakpointOptions>> *)
478 auto data_up = std::make_unique<CommandDataPython>();
481 data_up->user_source.SplitIntoLines(data);
483 if (GenerateBreakpointCommandCallbackData(data_up->user_source,
484 data_up->script_source,
488 auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
490 bp_options.SetCallback(
491 ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
492 }
else if (!batch_mode) {
495 locked_stream.
Printf(
"Warning: No command attached to breakpoint.\n");
504 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
505 data_up->user_source.SplitIntoLines(data);
507 if (GenerateWatchpointCommandCallbackData(data_up->user_source,
508 data_up->script_source,
511 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
513 ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
514 }
else if (!batch_mode) {
517 locked_stream.
Printf(
"Warning: No command attached to breakpoint.\n");
526ScriptInterpreterPythonImpl::CreateInstance(
Debugger &debugger) {
527 return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
530void ScriptInterpreterPythonImpl::LeaveSession() {
533 log->
PutCString(
"ScriptInterpreterPythonImpl::LeaveSession()");
536 RunSimpleString(
"lldb.debugger = None; lldb.target = None; lldb.process "
537 "= None; lldb.thread = None; lldb.frame = None");
544 if (PyThreadState_GetDict()) {
545 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
546 if (sys_module_dict.IsValid()) {
547 if (m_saved_stdin.IsValid()) {
548 sys_module_dict.SetItemForKey(PythonString(
"stdin"), m_saved_stdin);
549 m_saved_stdin.Reset();
551 if (m_saved_stdout.IsValid()) {
552 sys_module_dict.SetItemForKey(PythonString(
"stdout"), m_saved_stdout);
553 m_saved_stdout.Reset();
555 if (m_saved_stderr.IsValid()) {
556 sys_module_dict.SetItemForKey(PythonString(
"stderr"), m_saved_stderr);
557 m_saved_stderr.Reset();
562 m_session_is_active =
false;
565bool ScriptInterpreterPythonImpl::SetStdHandle(
FileSP file_sp,
567 PythonObject &save_file,
569 if (!file_sp || !*file_sp) {
573 File &file = *file_sp;
578 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
580 auto new_file = PythonFile::FromFile(file, mode);
582 llvm::consumeError(new_file.takeError());
586 save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
588 sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
592bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
598 if (m_session_is_active) {
601 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
602 ") session is already active, returning without doing anything",
609 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
")",
612 m_session_is_active =
true;
616 if (on_entry_flags & Locker::InitGlobals) {
617 run_string.
Printf(
"run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
618 m_dictionary_name.c_str(), m_debugger.GetID());
620 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64
")",
622 run_string.
PutCString(
"; lldb.target = lldb.debugger.GetSelectedTarget()");
623 run_string.
PutCString(
"; lldb.process = lldb.target.GetProcess()");
624 run_string.
PutCString(
"; lldb.thread = lldb.process.GetSelectedThread ()");
625 run_string.
PutCString(
"; lldb.frame = lldb.thread.GetSelectedFrame ()");
630 run_string.
Printf(
"run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
631 m_dictionary_name.c_str(), m_debugger.GetID());
633 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64
")",
638 RunSimpleString(run_string.
GetData());
641 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
642 if (sys_module_dict.IsValid()) {
645 if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
646 m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
649 if (on_entry_flags & Locker::NoSTDIN) {
650 m_saved_stdin.Reset();
652 if (!SetStdHandle(in_sp,
"stdin", m_saved_stdin,
"r")) {
654 SetStdHandle(top_in_sp,
"stdin", m_saved_stdin,
"r");
658 if (!SetStdHandle(out_sp,
"stdout", m_saved_stdout,
"w")) {
660 SetStdHandle(top_out_sp->GetUnlockedFileSP(),
"stdout", m_saved_stdout,
664 if (!SetStdHandle(err_sp,
"stderr", m_saved_stderr,
"w")) {
666 SetStdHandle(top_err_sp->GetUnlockedFileSP(),
"stderr", m_saved_stderr,
671 if (PyErr_Occurred())
677PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
678 if (!m_main_module.IsValid())
679 m_main_module = unwrapIgnoringErrors(PythonModule::Import(
"__main__"));
680 return m_main_module;
683PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
684 if (m_session_dict.IsValid())
685 return m_session_dict;
687 PythonObject &main_module = GetMainModule();
688 if (!main_module.IsValid())
689 return m_session_dict;
691 PythonDictionary main_dict(PyRefType::Borrowed,
692 PyModule_GetDict(main_module.get()));
693 if (!main_dict.IsValid())
694 return m_session_dict;
696 m_session_dict = unwrapIgnoringErrors(
697 As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
698 return m_session_dict;
701PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
702 if (m_sys_module_dict.IsValid())
703 return m_sys_module_dict;
704 PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import(
"sys"));
705 m_sys_module_dict = sys_module.GetDictionary();
706 return m_sys_module_dict;
709llvm::Expected<unsigned>
710ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
711 const llvm::StringRef &callable_name) {
712 if (callable_name.empty()) {
713 return llvm::createStringError(llvm::inconvertibleErrorCode(),
714 "called with empty callable name.");
717 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
718 auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
720 auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
721 callable_name, dict);
722 if (!pfunc.IsAllocated()) {
723 return llvm::createStringError(llvm::inconvertibleErrorCode(),
724 "can't find callable: %s",
725 callable_name.str().c_str());
727 llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
729 return arg_info.takeError();
730 return arg_info.get().max_positional_args;
733static std::string GenerateUniqueName(
const char *base_name_wanted,
734 uint32_t &functions_counter,
735 const void *name_token =
nullptr) {
738 if (!base_name_wanted)
739 return std::string();
742 sstr.
Printf(
"%s_%d", base_name_wanted, functions_counter++);
744 sstr.
Printf(
"%s_%p", base_name_wanted, name_token);
749bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
750 if (m_run_one_line_function.IsValid())
753 PythonObject module(PyRefType::Borrowed,
754 PyImport_AddModule(
"lldb.embedded_interpreter"));
755 if (!module.IsValid())
758 PythonDictionary module_dict(PyRefType::Borrowed,
759 PyModule_GetDict(module.get()));
760 if (!module_dict.IsValid())
763 m_run_one_line_function =
764 module_dict.GetItemForKey(PythonString(
"run_one_line"));
765 m_run_one_line_str_global =
766 module_dict.GetItemForKey(PythonString(
"g_run_one_line_str"));
767 return m_run_one_line_function.IsValid();
770bool ScriptInterpreterPythonImpl::ExecuteOneLine(
773 std::string command_str = command.str();
775 if (!m_valid_session)
778 if (!command.empty()) {
785 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
788 if (!io_redirect_or_error) {
791 "failed to redirect I/O: {0}\n",
792 llvm::fmt_consume(io_redirect_or_error.takeError()));
794 llvm::consumeError(io_redirect_or_error.takeError());
800 bool success =
false;
812 Locker::AcquireLock | Locker::InitSession |
815 Locker::FreeAcquiredLock | Locker::TearDownSession,
820 PythonDictionary &session_dict = GetSessionDictionary();
821 if (session_dict.IsValid()) {
822 if (GetEmbeddedInterpreterModuleObjects()) {
823 if (PyCallable_Check(m_run_one_line_function.get())) {
826 Py_BuildValue(
"(Os)", session_dict.get(), command_str.c_str()));
827 if (pargs.IsValid()) {
828 PythonObject return_value(
830 PyObject_CallObject(m_run_one_line_function.get(),
832 if (return_value.IsValid())
852 "python failed attempting to evaluate '%s'\n", command_str.c_str());
858 result->
AppendError(
"empty command passed to python\n");
862void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
876 IOHandlerSP io_handler_sp(
new IOHandlerPythonInterpreter(debugger,
this));
882bool ScriptInterpreterPythonImpl::Interrupt() {
883#if LLDB_USE_PYTHON_SET_INTERRUPT
887 if (!IsExecutingPython())
891 PyErr_SetInterrupt();
901 if (IsExecutingPython()) {
902 PyThreadState *state = PyThreadState_Get();
904 state = GetThreadState();
906 long tid = PyThread_get_thread_ident();
907 PyThreadState_Swap(state);
908 int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
910 "ScriptInterpreterPythonImpl::Interrupt() sending "
911 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
917 "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
923bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
927 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
931 if (!io_redirect_or_error) {
932 llvm::consumeError(io_redirect_or_error.takeError());
939 Locker::AcquireLock | Locker::InitSession |
942 Locker::FreeAcquiredLock | Locker::TearDownSession,
946 PythonModule &main_module = GetMainModule();
947 PythonDictionary globals = main_module.GetDictionary();
949 PythonDictionary locals = GetSessionDictionary();
950 if (!locals.IsValid())
951 locals = unwrapIgnoringErrors(
952 As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
953 if (!locals.IsValid())
956 Expected<PythonObject> maybe_py_return =
957 runStringOneLine(in_string, globals, locals);
959 if (!maybe_py_return) {
960 llvm::handleAllErrors(
961 maybe_py_return.takeError(),
962 [&](PythonException &E) {
964 if (options.GetMaskoutErrors()) {
965 if (E.Matches(PyExc_SyntaxError)) {
971 [](
const llvm::ErrorInfoBase &E) {});
975 PythonObject py_return = std::move(maybe_py_return.get());
976 assert(py_return.IsValid());
978 switch (return_type) {
979 case eScriptReturnTypeCharPtr:
981 const char format[3] =
"s#";
982 return PyArg_Parse(py_return.get(), format, (
char **)ret_value);
984 case eScriptReturnTypeCharStrOrNone:
987 const char format[3] =
"z";
988 return PyArg_Parse(py_return.get(), format, (
char **)ret_value);
990 case eScriptReturnTypeBool: {
991 const char format[2] =
"b";
992 return PyArg_Parse(py_return.get(), format, (
bool *)ret_value);
994 case eScriptReturnTypeShortInt: {
995 const char format[2] =
"h";
996 return PyArg_Parse(py_return.get(), format, (
short *)ret_value);
998 case eScriptReturnTypeShortIntUnsigned: {
999 const char format[2] =
"H";
1000 return PyArg_Parse(py_return.get(), format, (
unsigned short *)ret_value);
1002 case eScriptReturnTypeInt: {
1003 const char format[2] =
"i";
1004 return PyArg_Parse(py_return.get(), format, (
int *)ret_value);
1006 case eScriptReturnTypeIntUnsigned: {
1007 const char format[2] =
"I";
1008 return PyArg_Parse(py_return.get(), format, (
unsigned int *)ret_value);
1010 case eScriptReturnTypeLongInt: {
1011 const char format[2] =
"l";
1012 return PyArg_Parse(py_return.get(), format, (
long *)ret_value);
1014 case eScriptReturnTypeLongIntUnsigned: {
1015 const char format[2] =
"k";
1016 return PyArg_Parse(py_return.get(), format, (
unsigned long *)ret_value);
1018 case eScriptReturnTypeLongLong: {
1019 const char format[2] =
"L";
1020 return PyArg_Parse(py_return.get(), format, (
long long *)ret_value);
1022 case eScriptReturnTypeLongLongUnsigned: {
1023 const char format[2] =
"K";
1024 return PyArg_Parse(py_return.get(), format,
1025 (
unsigned long long *)ret_value);
1027 case eScriptReturnTypeFloat: {
1028 const char format[2] =
"f";
1029 return PyArg_Parse(py_return.get(), format, (
float *)ret_value);
1031 case eScriptReturnTypeDouble: {
1032 const char format[2] =
"d";
1033 return PyArg_Parse(py_return.get(), format, (
double *)ret_value);
1035 case eScriptReturnTypeChar: {
1036 const char format[2] =
"c";
1037 return PyArg_Parse(py_return.get(), format, (
char *)ret_value);
1039 case eScriptReturnTypeOpaqueObject: {
1040 *((PyObject **)ret_value) = py_return.release();
1044 llvm_unreachable(
"Fully covered switch!");
1047Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1050 if (in_string ==
nullptr)
1053 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1057 if (!io_redirect_or_error)
1063 Locker::AcquireLock | Locker::InitSession |
1066 Locker::FreeAcquiredLock | Locker::TearDownSession,
1070 PythonModule &main_module = GetMainModule();
1071 PythonDictionary globals = main_module.GetDictionary();
1073 PythonDictionary locals = GetSessionDictionary();
1074 if (!locals.IsValid())
1075 locals = unwrapIgnoringErrors(
1076 As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1077 if (!locals.IsValid())
1080 Expected<PythonObject> return_value =
1081 runStringMultiLine(in_string, globals, locals);
1083 if (!return_value) {
1085 llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
1086 llvm::Error error = llvm::createStringError(
1087 llvm::inconvertibleErrorCode(), E.ReadBacktrace());
1088 if (!options.GetMaskoutErrors())
1098void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1099 std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1102 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1103 " ", *
this, &bp_options_vec);
1106void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1109 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1110 " ", *
this, wp_options);
1113Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1118 std::string function_signature = function_name;
1120 llvm::Expected<unsigned> maybe_args =
1121 GetMaxPositionalArgumentsForCallable(function_name);
1124 "could not get num args: %s",
1125 llvm::toString(maybe_args.takeError()).c_str());
1128 size_t max_args = *maybe_args;
1130 bool uses_extra_args =
false;
1131 if (max_args >= 4) {
1132 uses_extra_args =
true;
1133 function_signature +=
"(frame, bp_loc, extra_args, internal_dict)";
1134 }
else if (max_args >= 3) {
1135 if (extra_args_sp) {
1137 "cannot pass extra_args to a three argument callback");
1140 uses_extra_args =
false;
1141 function_signature +=
"(frame, bp_loc, internal_dict)";
1144 "function, %s can only take %zu",
1145 function_name, max_args);
1149 SetBreakpointCommandCallback(bp_options, function_signature.c_str(),
1150 extra_args_sp, uses_extra_args,
1155Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1157 std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
1159 error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1160 cmd_data_up->script_source,
1167 std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1169 ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1173Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1176 return SetBreakpointCommandCallback(bp_options, command_body_text, {},
1177 false, is_callback);
1181Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1185 auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1191 data_up->user_source.SplitIntoLines(command_body_text);
1192 Status error = GenerateBreakpointCommandCallbackData(
1193 data_up->user_source, data_up->script_source, uses_extra_args,
1195 if (
error.Success()) {
1197 std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1199 ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1206void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1208 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
1215 data_up->user_source.AppendString(user_input);
1216 data_up->script_source.assign(user_input);
1218 if (GenerateWatchpointCommandCallbackData(
1219 data_up->user_source, data_up->script_source, is_callback)) {
1221 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
1223 ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
1227Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1230 std::string function_def_string(function_def.
CopyList());
1232 function_def_string.c_str());
1239Status ScriptInterpreterPythonImpl::GenerateFunction(
const char *signature,
1243 int num_lines = input.
GetSize();
1244 if (num_lines == 0) {
1249 if (!signature || *signature == 0) {
1258 " global_dict = globals()");
1260 " new_keys = internal_dict.keys()");
1263 " old_keys = global_dict.keys()");
1265 " global_dict.update(internal_dict)");
1272 if (num_lines == 1) {
1278 "ScriptInterpreterPythonImpl::GenerateFunction(is_callback="
1279 "true) = ERROR: python function is multiline.");
1283 " __return_val = None");
1285 " def __user_code():");
1289 for (
int i = 0; i < num_lines; ++i) {
1295 " __return_val = __user_code()");
1299 " for key in new_keys:");
1302 " if key in old_keys:");
1305 " internal_dict[key] = global_dict[key]");
1307 " elif key in global_dict:");
1310 " del global_dict[key]");
1313 " return __return_val");
1316 error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
1321bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1322 StringList &user_input, std::string &output,
const void *name_token) {
1323 static uint32_t num_created_functions = 0;
1328 if (user_input.
GetSize() == 0)
1334 std::string auto_generated_function_name(
1335 GenerateUniqueName(
"lldb_autogen_python_type_print_func",
1336 num_created_functions, name_token));
1337 sstr.
Printf(
"def %s (valobj, internal_dict):",
1338 auto_generated_function_name.c_str());
1340 if (!GenerateFunction(sstr.
GetData(), user_input,
false)
1345 output.assign(auto_generated_function_name);
1349bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1350 StringList &user_input, std::string &output) {
1351 static uint32_t num_created_functions = 0;
1356 if (user_input.
GetSize() == 0)
1359 std::string auto_generated_function_name(GenerateUniqueName(
1360 "lldb_autogen_python_cmd_alias_func", num_created_functions));
1362 sstr.
Printf(
"def %s (debugger, args, exe_ctx, result, internal_dict):",
1363 auto_generated_function_name.c_str());
1365 if (!GenerateFunction(sstr.
GetData(), user_input,
false)
1370 output.assign(auto_generated_function_name);
1374bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1375 StringList &user_input, std::string &output,
const void *name_token) {
1376 static uint32_t num_created_classes = 0;
1378 int num_lines = user_input.
GetSize();
1382 if (user_input.
GetSize() == 0)
1387 std::string auto_generated_class_name(GenerateUniqueName(
1388 "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1394 sstr.
Printf(
"class %s:", auto_generated_class_name.c_str());
1400 for (
int i = 0; i < num_lines; ++i) {
1409 if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).
Success())
1414 output.assign(auto_generated_class_name);
1419ScriptInterpreterPythonImpl::CreateFrameRecognizer(
const char *class_name) {
1420 if (class_name ==
nullptr || class_name[0] ==
'\0')
1423 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1424 PythonObject ret_val = SWIGBridge::LLDBSWIGPython_CreateFrameRecognizer(
1425 class_name, m_dictionary_name.c_str());
1428 new StructuredPythonObject(std::move(ret_val)));
1434 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1436 if (!os_plugin_object_sp)
1443 PythonObject implementor(PyRefType::Borrowed,
1444 (PyObject *)generic->GetValue());
1446 if (!implementor.IsAllocated())
1449 PythonObject py_return(PyRefType::Owned,
1450 SWIGBridge::LLDBSwigPython_GetRecognizedArguments(
1451 implementor.get(), frame_sp));
1454 if (PyErr_Occurred()) {
1458 if (py_return.get()) {
1459 PythonList result_list(PyRefType::Borrowed, py_return.get());
1461 for (
size_t i = 0; i < result_list.GetSize(); i++) {
1462 PyObject *item = result_list.GetItemAtIndex(i).get();
1464 (
lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
1466 SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
1468 result->Append(valobj_sp);
1475bool ScriptInterpreterPythonImpl::ShouldHide(
1478 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1480 if (!os_plugin_object_sp)
1487 PythonObject implementor(PyRefType::Borrowed,
1488 (PyObject *)generic->GetValue());
1490 if (!implementor.IsAllocated())
1494 SWIGBridge::LLDBSwigPython_ShouldHide(implementor.get(), frame_sp);
1497 if (PyErr_Occurred()) {
1505ScriptInterpreterPythonImpl::CreateScriptedProcessInterface() {
1506 return std::make_unique<ScriptedProcessPythonInterface>(*
this);
1510ScriptInterpreterPythonImpl::CreateScriptedStopHookInterface() {
1511 return std::make_shared<ScriptedStopHookPythonInterface>(*
this);
1515ScriptInterpreterPythonImpl::CreateScriptedBreakpointInterface() {
1516 return std::make_shared<ScriptedBreakpointPythonInterface>(*
this);
1520ScriptInterpreterPythonImpl::CreateScriptedThreadInterface() {
1521 return std::make_shared<ScriptedThreadPythonInterface>(*
this);
1525ScriptInterpreterPythonImpl::CreateScriptedFrameInterface() {
1526 return std::make_shared<ScriptedFramePythonInterface>(*
this);
1530ScriptInterpreterPythonImpl::CreateScriptedFrameProviderInterface() {
1531 return std::make_shared<ScriptedFrameProviderPythonInterface>(*
this);
1535ScriptInterpreterPythonImpl::CreateScriptedThreadPlanInterface() {
1536 return std::make_shared<ScriptedThreadPlanPythonInterface>(*
this);
1540ScriptInterpreterPythonImpl::CreateOperatingSystemInterface() {
1541 return std::make_shared<OperatingSystemPythonInterface>(*
this);
1545ScriptInterpreterPythonImpl::CreateStructuredDataFromScriptObject(
1547 void *ptr =
const_cast<void *
>(obj.
GetPointer());
1548 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1549 PythonObject py_obj(PyRefType::Borrowed,
static_cast<PyObject *
>(ptr));
1550 if (!py_obj.IsValid() || py_obj.IsNone())
1552 return py_obj.CreateStructuredObject();
1556ScriptInterpreterPythonImpl::LoadPluginModule(
const FileSpec &file_spec,
1567 if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1577 if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
1583 Locker py_lock(
this,
1584 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1585 TargetSP target_sp(target->shared_from_this());
1587 auto setting = (PyObject *)SWIGBridge::LLDBSWIGPython_GetDynamicSetting(
1588 generic->GetValue(), setting_name, target_sp);
1593 PythonDictionary py_dict =
1594 unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
1599 return py_dict.CreateStructuredDictionary();
1603ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
1605 if (class_name ==
nullptr || class_name[0] ==
'\0')
1612 Target *target = exe_ctx.GetTargetPtr();
1618 ScriptInterpreterPythonImpl *python_interpreter =
1619 GetPythonInterpreter(debugger);
1621 if (!python_interpreter)
1624 Locker py_lock(
this,
1625 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1626 PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateSyntheticProvider(
1627 class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
1630 new StructuredPythonObject(std::move(ret_val)));
1634ScriptInterpreterPythonImpl::CreateScriptCommandObject(
const char *class_name) {
1635 DebuggerSP debugger_sp(m_debugger.shared_from_this());
1637 if (class_name ==
nullptr || class_name[0] ==
'\0')
1640 if (!debugger_sp.get())
1643 Locker py_lock(
this,
1644 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1645 PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateCommandObject(
1646 class_name, m_dictionary_name.c_str(), debugger_sp);
1648 if (ret_val.IsValid())
1650 new StructuredPythonObject(std::move(ret_val)));
1655bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1656 const char *oneliner, std::string &output,
const void *name_token) {
1659 return GenerateTypeScriptFunction(input, output, name_token);
1662bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1663 const char *oneliner, std::string &output,
const void *name_token) {
1666 return GenerateTypeSynthClass(input, output, name_token);
1669Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
1670 StringList &user_input, std::string &output,
bool has_extra_args,
1672 static uint32_t num_created_functions = 0;
1676 if (user_input.
GetSize() == 0) {
1681 std::string auto_generated_function_name(GenerateUniqueName(
1682 "lldb_autogen_python_bp_callback_func_", num_created_functions));
1684 sstr.
Printf(
"def %s (frame, bp_loc, extra_args, internal_dict):",
1685 auto_generated_function_name.c_str());
1687 sstr.
Printf(
"def %s (frame, bp_loc, internal_dict):",
1688 auto_generated_function_name.c_str());
1690 error = GenerateFunction(sstr.
GetData(), user_input, is_callback);
1691 if (!
error.Success())
1695 output.assign(auto_generated_function_name);
1699bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
1700 StringList &user_input, std::string &output,
bool is_callback) {
1701 static uint32_t num_created_functions = 0;
1705 if (user_input.
GetSize() == 0)
1708 std::string auto_generated_function_name(GenerateUniqueName(
1709 "lldb_autogen_python_wp_callback_func_", num_created_functions));
1710 sstr.
Printf(
"def %s (frame, wp, internal_dict):",
1711 auto_generated_function_name.c_str());
1713 if (!GenerateFunction(sstr.
GetData(), user_input, is_callback).Success())
1717 output.assign(auto_generated_function_name);
1721bool ScriptInterpreterPythonImpl::GetScriptedSummary(
1728 if (!valobj.get()) {
1729 retval.assign(
"<no object>");
1733 void *old_callee =
nullptr;
1735 if (callee_wrapper_sp) {
1736 generic = callee_wrapper_sp->GetAsGeneric();
1738 old_callee =
generic->GetValue();
1740 void *new_callee = old_callee;
1743 if (python_function_name && *python_function_name) {
1745 Locker py_lock(
this, Locker::AcquireLock | Locker::InitSession |
1751 Timer scoped_timer(func_cat,
"LLDBSwigPythonCallTypeScript");
1752 ret_val = SWIGBridge::LLDBSwigPythonCallTypeScript(
1753 python_function_name, GetSessionDictionary().get(), valobj,
1754 &new_callee, options_sp, retval);
1758 retval.assign(
"<no function name>");
1762 if (new_callee && old_callee != new_callee) {
1763 Locker py_lock(
this,
1764 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1765 callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
1766 PythonObject(PyRefType::Borrowed,
static_cast<PyObject *
>(new_callee)));
1772bool ScriptInterpreterPythonImpl::FormatterCallbackFunction(
1773 const char *python_function_name,
TypeImplSP type_impl_sp) {
1774 Locker py_lock(
this,
1775 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1776 return SWIGBridge::LLDBSwigPythonFormatterCallbackFunction(
1777 python_function_name, m_dictionary_name.c_str(), type_impl_sp);
1780bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
1783 CommandDataPython *bp_option_data = (CommandDataPython *)baton;
1784 const char *python_function_name = bp_option_data->script_source.c_str();
1790 Target *target = exe_ctx.GetTargetPtr();
1796 ScriptInterpreterPythonImpl *python_interpreter =
1797 GetPythonInterpreter(debugger);
1799 if (!python_interpreter)
1802 if (python_function_name && python_function_name[0]) {
1803 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
1805 if (breakpoint_sp) {
1807 breakpoint_sp->FindLocationByID(break_loc_id));
1809 if (stop_frame_sp && bp_loc_sp) {
1810 bool ret_val =
true;
1812 Locker py_lock(python_interpreter, Locker::AcquireLock |
1813 Locker::InitSession |
1815 Expected<bool> maybe_ret_val =
1816 SWIGBridge::LLDBSwigPythonBreakpointCallbackFunction(
1817 python_function_name,
1818 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
1819 bp_loc_sp, bp_option_data->m_extra_args);
1821 if (!maybe_ret_val) {
1823 llvm::handleAllErrors(
1824 maybe_ret_val.takeError(),
1825 [&](PythonException &E) {
1826 *debugger.GetAsyncErrorStream() << E.ReadBacktrace();
1828 [&](
const llvm::ErrorInfoBase &E) {
1829 *debugger.GetAsyncErrorStream() << E.message();
1833 ret_val = maybe_ret_val.get();
1845bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
1849 const char *python_function_name = wp_option_data->
script_source.c_str();
1855 Target *target = exe_ctx.GetTargetPtr();
1861 ScriptInterpreterPythonImpl *python_interpreter =
1862 GetPythonInterpreter(debugger);
1864 if (!python_interpreter)
1867 if (python_function_name && python_function_name[0]) {
1868 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
1871 if (stop_frame_sp && wp_sp) {
1872 bool ret_val =
true;
1874 Locker py_lock(python_interpreter, Locker::AcquireLock |
1875 Locker::InitSession |
1877 ret_val = SWIGBridge::LLDBSwigPythonWatchpointCallbackFunction(
1878 python_function_name,
1879 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
1891size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
1893 if (!implementor_sp)
1898 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
1905 Locker py_lock(
this,
1906 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1907 ret_val = SWIGBridge::LLDBSwigPython_CalculateNumChildren(implementor, max);
1915 if (!implementor_sp)
1921 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
1927 Locker py_lock(
this,
1928 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1929 PyObject *child_ptr =
1930 SWIGBridge::LLDBSwigPython_GetChildAtIndex(implementor, idx);
1931 if (child_ptr !=
nullptr && child_ptr != Py_None) {
1933 (
lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
1934 if (sb_value_ptr ==
nullptr)
1935 Py_XDECREF(child_ptr);
1937 ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
1940 Py_XDECREF(child_ptr);
1947llvm::Expected<uint32_t> ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
1949 if (!implementor_sp)
1950 return llvm::createStringError(
"Type has no child named '%s'", child_name);
1954 return llvm::createStringError(
"Type has no child named '%s'", child_name);
1955 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
1957 return llvm::createStringError(
"Type has no child named '%s'", child_name);
1962 Locker py_lock(
this,
1963 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1964 ret_val = SWIGBridge::LLDBSwigPython_GetIndexOfChildWithName(implementor,
1969 return llvm::createStringError(
"Type has no child named '%s'", child_name);
1973bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
1975 bool ret_val =
false;
1977 if (!implementor_sp)
1983 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
1988 Locker py_lock(
this,
1989 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1991 SWIGBridge::LLDBSwigPython_UpdateSynthProviderInstance(implementor);
1997bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
1999 bool ret_val =
false;
2001 if (!implementor_sp)
2007 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2012 Locker py_lock(
this,
2013 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2014 ret_val = SWIGBridge::LLDBSwigPython_MightHaveChildrenSynthProviderInstance(
2025 if (!implementor_sp)
2031 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2036 Locker py_lock(
this,
2037 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2038 PyObject *child_ptr =
2039 SWIGBridge::LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2040 if (child_ptr !=
nullptr && child_ptr != Py_None) {
2042 (
lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2043 if (sb_value_ptr ==
nullptr)
2044 Py_XDECREF(child_ptr);
2046 ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
2049 Py_XDECREF(child_ptr);
2056ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2058 Locker py_lock(
this,
2059 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2061 if (!implementor_sp)
2068 PythonObject implementor(PyRefType::Borrowed,
2069 (PyObject *)generic->GetValue());
2070 if (!implementor.IsAllocated())
2073 llvm::Expected<PythonObject> expected_py_return =
2074 implementor.CallMethod(
"get_type_name");
2076 if (!expected_py_return) {
2077 llvm::consumeError(expected_py_return.takeError());
2081 PythonObject py_return = std::move(expected_py_return.get());
2082 if (!py_return.IsAllocated() || !PythonString::Check(py_return.get()))
2085 PythonString type_name(PyRefType::Borrowed, py_return.get());
2089bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2090 const char *impl_function,
Process *process, std::string &output,
2097 if (!impl_function || !impl_function[0]) {
2103 Locker py_lock(
this,
2104 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2105 ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordProcess(
2106 impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
2114bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2115 const char *impl_function,
Thread *thread, std::string &output,
2121 if (!impl_function || !impl_function[0]) {
2126 Locker py_lock(
this,
2127 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2128 if (std::optional<std::string> result =
2129 SWIGBridge::LLDBSWIGPythonRunScriptKeywordThread(
2130 impl_function, m_dictionary_name.c_str(),
2131 thread->shared_from_this())) {
2132 output = std::move(*result);
2139bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2140 const char *impl_function,
Target *target, std::string &output,
2147 if (!impl_function || !impl_function[0]) {
2153 TargetSP target_sp(target->shared_from_this());
2154 Locker py_lock(
this,
2155 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2156 ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordTarget(
2157 impl_function, m_dictionary_name.c_str(), target_sp, output);
2164bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2165 const char *impl_function,
StackFrame *frame, std::string &output,
2171 if (!impl_function || !impl_function[0]) {
2176 Locker py_lock(
this,
2177 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2178 if (std::optional<std::string> result =
2179 SWIGBridge::LLDBSWIGPythonRunScriptKeywordFrame(
2180 impl_function, m_dictionary_name.c_str(),
2181 frame->shared_from_this())) {
2182 output = std::move(*result);
2189bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2190 const char *impl_function,
ValueObject *value, std::string &output,
2197 if (!impl_function || !impl_function[0]) {
2203 Locker py_lock(
this,
2204 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2205 ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordValue(
2206 impl_function, m_dictionary_name.c_str(), value->
GetSP(), output);
2213uint64_t replace_all(std::string &str,
const std::string &oldStr,
2214 const std::string &newStr) {
2216 uint64_t matches = 0;
2217 while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2219 str.replace(pos, oldStr.length(), newStr);
2220 pos += newStr.length();
2225bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2229 namespace fs = llvm::sys::fs;
2230 namespace path = llvm::sys::path;
2236 if (!pathname || !pathname[0]) {
2241 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2245 if (!io_redirect_or_error) {
2253 Locker py_lock(
this,
2254 Locker::AcquireLock |
2257 Locker::FreeAcquiredLock |
2262 auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2263 if (directory.empty()) {
2264 return llvm::createStringError(
"invalid directory name");
2267 replace_all(directory,
"\\",
"\\\\");
2268 replace_all(directory,
"'",
"\\'");
2272 command_stream.
Printf(
"if not (sys.path.__contains__('%s')):\n "
2273 "sys.path.insert(1,'%s');\n\n",
2274 directory.c_str(), directory.c_str());
2275 bool syspath_retval =
2276 ExecuteMultipleLines(command_stream.
GetData(), exc_options).Success();
2277 if (!syspath_retval)
2278 return llvm::createStringError(
"Python sys.path handling failed");
2280 return llvm::Error::success();
2283 std::string module_name(pathname);
2284 bool possible_package =
false;
2286 if (extra_search_dir) {
2287 if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2296 std::error_code ec = status(module_file.GetPath(), st);
2298 if (ec || st.type() == fs::file_type::status_error ||
2299 st.type() == fs::file_type::type_unknown ||
2300 st.type() == fs::file_type::file_not_found) {
2303 if (strchr(pathname,
'\\') || strchr(pathname,
'/')) {
2309 possible_package =
true;
2310 }
else if (is_directory(st) || is_regular_file(st)) {
2311 if (module_file.GetDirectory().IsEmpty()) {
2313 "invalid directory name '{0}'", pathname);
2317 ExtendSysPath(module_file.GetDirectory().GetCString())) {
2321 module_name = module_file.GetFilename().GetCString();
2324 "no known way to import this module specification");
2330 llvm::StringRef extension = llvm::sys::path::extension(module_name);
2331 if (!extension.empty()) {
2332 if (extension ==
".py")
2333 module_name.resize(module_name.length() - 3);
2334 else if (extension ==
".pyc")
2335 module_name.resize(module_name.length() - 4);
2338 if (!possible_package && module_name.find(
'.') != llvm::StringRef::npos) {
2340 "Python does not allow dots in module names: %s", module_name.c_str());
2344 if (module_name.find(
'-') != llvm::StringRef::npos) {
2346 "Python discourages dashes in module names: %s", module_name.c_str());
2352 command_stream.
Clear();
2353 command_stream.
Printf(
"sys.modules.__contains__('%s')", module_name.c_str());
2354 bool does_contain =
false;
2357 const bool does_contain_executed = ExecuteOneLineWithReturn(
2359 ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain,
2362 const bool was_imported_globally = does_contain_executed && does_contain;
2363 const bool was_imported_locally =
2364 GetSessionDictionary()
2365 .GetItemForKey(PythonString(module_name))
2369 command_stream.
Clear();
2371 if (was_imported_globally || was_imported_locally) {
2372 if (!was_imported_locally)
2373 command_stream.
Printf(
"import %s ; reload_module(%s)",
2374 module_name.c_str(), module_name.c_str());
2376 command_stream.
Printf(
"reload_module(%s)", module_name.c_str());
2378 command_stream.
Printf(
"import %s", module_name.c_str());
2380 error = ExecuteMultipleLines(command_stream.
GetData(), exc_options);
2386 if (!SWIGBridge::LLDBSwigPythonCallModuleInit(
2387 module_name.c_str(), m_dictionary_name.c_str(),
2388 m_debugger.shared_from_this())) {
2395 command_stream.
Clear();
2396 command_stream.
Printf(
"%s", module_name.c_str());
2397 void *module_pyobj =
nullptr;
2398 if (ExecuteOneLineWithReturn(
2403 *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2404 PyRefType::Owned,
static_cast<PyObject *
>(module_pyobj)));
2410 return SWIGBridge::LLDBSwigPythonCallModuleNewTarget(
2411 module_name.c_str(), m_dictionary_name.c_str(), target_sp);
2416bool ScriptInterpreterPythonImpl::IsReservedWord(
const char *word) {
2417 if (!word || !word[0])
2420 llvm::StringRef word_sr(word);
2424 if (word_sr.find(
'"') != llvm::StringRef::npos ||
2425 word_sr.find(
'\'') != llvm::StringRef::npos)
2429 command_stream.
Printf(
"keyword.iskeyword('%s')", word);
2435 if (ExecuteOneLineWithReturn(command_stream.
GetData(),
2442ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2444 : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2445 m_old_asynch(debugger_sp->GetAsyncExecution()) {
2447 m_debugger_sp->SetAsyncExecution(
false);
2449 m_debugger_sp->SetAsyncExecution(
true);
2452ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
2454 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2457bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2458 const char *impl_function, llvm::StringRef args,
2459 ScriptedCommandSynchronicity synchronicity,
2462 if (!impl_function) {
2470 if (!debugger_sp.get()) {
2475 bool ret_val =
false;
2478 Locker py_lock(
this,
2479 Locker::AcquireLock | Locker::InitSession |
2481 Locker::FreeLock | Locker::TearDownSession);
2483 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2485 std::string args_str = args.str();
2486 ret_val = SWIGBridge::LLDBSwigPythonCallCommand(
2487 impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2488 cmd_retobj, exe_ctx_ref_sp);
2500bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2502 ScriptedCommandSynchronicity synchronicity,
2505 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2513 if (!debugger_sp.get()) {
2518 bool ret_val =
false;
2521 Locker py_lock(
this,
2522 Locker::AcquireLock | Locker::InitSession |
2524 Locker::FreeLock | Locker::TearDownSession);
2526 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2528 std::string args_str = args.str();
2529 ret_val = SWIGBridge::LLDBSwigPythonCallCommandObject(
2530 static_cast<PyObject *
>(impl_obj_sp->GetValue()), debugger_sp,
2531 args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
2543bool ScriptInterpreterPythonImpl::RunScriptBasedParsedCommand(
2545 ScriptedCommandSynchronicity synchronicity,
2548 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2556 if (!debugger_sp.get()) {
2561 bool ret_val =
false;
2564 Locker py_lock(
this,
2565 Locker::AcquireLock | Locker::InitSession |
2567 Locker::FreeLock | Locker::TearDownSession);
2569 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2574 args_arr_sp->AddStringItem(entry.ref());
2578 ret_val = SWIGBridge::LLDBSwigPythonCallParsedCommandObject(
2579 static_cast<PyObject *
>(impl_obj_sp->GetValue()), debugger_sp,
2580 args_impl, cmd_retobj, exe_ctx_ref_sp);
2592std::optional<std::string>
2593ScriptInterpreterPythonImpl::GetRepeatCommandForScriptedCommand(
2595 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2596 return std::nullopt;
2600 if (!debugger_sp.get())
2601 return std::nullopt;
2603 std::optional<std::string> ret_val;
2606 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN,
2612 std::string command;
2613 args.GetQuotedCommandString(command);
2614 ret_val = SWIGBridge::LLDBSwigPythonGetRepeatCommandForScriptedCommand(
2615 static_cast<PyObject *
>(impl_obj_sp->GetValue()), command);
2621ScriptInterpreterPythonImpl::HandleArgumentCompletionForScriptedCommand(
2623 size_t args_pos,
size_t char_in_arg) {
2625 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2626 return completion_dict_sp;
2629 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN,
2632 completion_dict_sp =
2633 SWIGBridge::LLDBSwigPythonHandleArgumentCompletionForScriptedCommand(
2634 static_cast<PyObject *
>(impl_obj_sp->GetValue()), args, args_pos,
2637 return completion_dict_sp;
2641ScriptInterpreterPythonImpl::HandleOptionArgumentCompletionForScriptedCommand(
2643 size_t char_in_arg) {
2645 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2646 return completion_dict_sp;
2649 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN,
2652 completion_dict_sp = SWIGBridge::
2653 LLDBSwigPythonHandleOptionArgumentCompletionForScriptedCommand(
2654 static_cast<PyObject *
>(impl_obj_sp->GetValue()), long_option,
2657 return completion_dict_sp;
2663bool ScriptInterpreterPythonImpl::GetDocumentationForItem(
const char *item,
2664 std::string &dest) {
2667 if (!item || !*item)
2670 std::string command(item);
2671 command +=
".__doc__";
2675 char *result_ptr =
nullptr;
2677 if (ExecuteOneLineWithReturn(
2681 dest.assign(result_ptr);
2686 str_stream <<
"Function " << item
2687 <<
" was not found. Containing module might be missing.";
2688 dest = std::string(str_stream.
GetString());
2693bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
2697 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2702 PythonObject implementor(PyRefType::Borrowed,
2703 (PyObject *)cmd_obj_sp->GetValue());
2705 if (!implementor.IsAllocated())
2708 llvm::Expected<PythonObject> expected_py_return =
2709 implementor.CallMethod(
"get_short_help");
2711 if (!expected_py_return) {
2712 llvm::consumeError(expected_py_return.takeError());
2716 PythonObject py_return = std::move(expected_py_return.get());
2718 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2719 PythonString py_string(PyRefType::Borrowed, py_return.get());
2720 llvm::StringRef return_data(py_string.GetString());
2721 dest.assign(return_data.data(), return_data.size());
2728uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
2730 uint32_t result = 0;
2732 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2734 static char callee_name[] =
"get_flags";
2739 PythonObject implementor(PyRefType::Borrowed,
2740 (PyObject *)cmd_obj_sp->GetValue());
2742 if (!implementor.IsAllocated())
2745 PythonObject pmeth(PyRefType::Owned,
2746 PyObject_GetAttrString(implementor.get(), callee_name));
2748 if (PyErr_Occurred())
2751 if (!pmeth.IsAllocated())
2754 if (PyCallable_Check(pmeth.get()) == 0) {
2755 if (PyErr_Occurred())
2760 if (PyErr_Occurred())
2763 long long py_return = unwrapOrSetPythonException(
2764 As<long long>(implementor.CallMethod(callee_name)));
2767 if (PyErr_Occurred()) {
2778ScriptInterpreterPythonImpl::GetOptionsForCommandObject(
2782 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2784 static char callee_name[] =
"get_options_definition";
2789 PythonObject implementor(PyRefType::Borrowed,
2790 (PyObject *)cmd_obj_sp->GetValue());
2792 if (!implementor.IsAllocated())
2795 PythonObject pmeth(PyRefType::Owned,
2796 PyObject_GetAttrString(implementor.get(), callee_name));
2798 if (PyErr_Occurred())
2801 if (!pmeth.IsAllocated())
2804 if (PyCallable_Check(pmeth.get()) == 0) {
2805 if (PyErr_Occurred())
2810 if (PyErr_Occurred())
2813 PythonDictionary py_return = unwrapOrSetPythonException(
2814 As<PythonDictionary>(implementor.CallMethod(callee_name)));
2817 if (PyErr_Occurred()) {
2822 return py_return.CreateStructuredObject();
2826ScriptInterpreterPythonImpl::GetArgumentsForCommandObject(
2830 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2832 static char callee_name[] =
"get_args_definition";
2837 PythonObject implementor(PyRefType::Borrowed,
2838 (PyObject *)cmd_obj_sp->GetValue());
2840 if (!implementor.IsAllocated())
2843 PythonObject pmeth(PyRefType::Owned,
2844 PyObject_GetAttrString(implementor.get(), callee_name));
2846 if (PyErr_Occurred())
2849 if (!pmeth.IsAllocated())
2852 if (PyCallable_Check(pmeth.get()) == 0) {
2853 if (PyErr_Occurred())
2858 if (PyErr_Occurred())
2861 PythonList py_return = unwrapOrSetPythonException(
2862 As<PythonList>(implementor.CallMethod(callee_name)));
2865 if (PyErr_Occurred()) {
2870 return py_return.CreateStructuredObject();
2873void ScriptInterpreterPythonImpl::OptionParsingStartedForCommandObject(
2876 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2878 static char callee_name[] =
"option_parsing_started";
2883 PythonObject implementor(PyRefType::Borrowed,
2884 (PyObject *)cmd_obj_sp->GetValue());
2886 if (!implementor.IsAllocated())
2889 PythonObject pmeth(PyRefType::Owned,
2890 PyObject_GetAttrString(implementor.get(), callee_name));
2892 if (PyErr_Occurred())
2895 if (!pmeth.IsAllocated())
2898 if (PyCallable_Check(pmeth.get()) == 0) {
2899 if (PyErr_Occurred())
2904 if (PyErr_Occurred())
2909 unwrapOrSetPythonException(As<bool>(implementor.CallMethod(callee_name)));
2912 if (PyErr_Occurred()) {
2919bool ScriptInterpreterPythonImpl::SetOptionValueForCommandObject(
2921 llvm::StringRef long_option, llvm::StringRef value) {
2924 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2926 static char callee_name[] =
"set_option_value";
2931 PythonObject implementor(PyRefType::Borrowed,
2932 (PyObject *)cmd_obj_sp->GetValue());
2934 if (!implementor.IsAllocated())
2937 PythonObject pmeth(PyRefType::Owned,
2938 PyObject_GetAttrString(implementor.get(), callee_name));
2940 if (PyErr_Occurred())
2943 if (!pmeth.IsAllocated())
2946 if (PyCallable_Check(pmeth.get()) == 0) {
2947 if (PyErr_Occurred())
2952 if (PyErr_Occurred())
2957 exe_ctx_ref_sp = std::make_shared<ExecutionContextRef>(exe_ctx);
2958 PythonObject ctx_ref_obj = SWIGBridge::ToSWIGWrapper(exe_ctx_ref_sp);
2960 bool py_return = unwrapOrSetPythonException(As<bool>(
2961 implementor.CallMethod(callee_name, ctx_ref_obj,
2962 long_option.str().c_str(), value.str().c_str())));
2965 if (PyErr_Occurred()) {
2973bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
2977 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2982 PythonObject implementor(PyRefType::Borrowed,
2983 (PyObject *)cmd_obj_sp->GetValue());
2985 if (!implementor.IsAllocated())
2988 llvm::Expected<PythonObject> expected_py_return =
2989 implementor.CallMethod(
"get_long_help");
2991 if (!expected_py_return) {
2992 llvm::consumeError(expected_py_return.takeError());
2996 PythonObject py_return = std::move(expected_py_return.get());
2998 bool got_string =
false;
2999 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3000 PythonString str(PyRefType::Borrowed, py_return.get());
3001 llvm::StringRef str_data(str.GetString());
3002 dest.assign(str_data.data(), str_data.size());
3009std::unique_ptr<ScriptInterpreterLocker>
3010ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3011 std::unique_ptr<ScriptInterpreterLocker> py_lock(
new Locker(
3012 this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3013 Locker::FreeLock | Locker::TearDownSession));
3017void ScriptInterpreterPythonImpl::Initialize() {
3024 InitializePythonRAII initialize_guard;
3031 RunSimpleString(
"import sys");
3032 AddToSysPath(AddLocation::End,
".");
3038 if (
FileSpec file_spec = GetPythonDir())
3039 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(
false));
3040 if (
FileSpec file_spec = HostInfo::GetShlibDir())
3041 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(
false));
3043 RunSimpleString(
"sys.dont_write_bytecode = 1; import "
3044 "lldb.embedded_interpreter; from "
3045 "lldb.embedded_interpreter import run_python_interpreter; "
3046 "from lldb.embedded_interpreter import run_one_line");
3048#if LLDB_USE_PYTHON_SET_INTERRUPT
3052 RestoreSignalHandlerScope save_sigint(SIGINT);
3058 RunSimpleString(
"def lldb_setup_sigint_handler():\n"
3060 " def signal_handler(sig, frame):\n"
3061 " raise KeyboardInterrupt()\n"
3062 " signal.signal(signal.SIGINT, signal_handler);\n"
3063 "lldb_setup_sigint_handler();\n"
3064 "del lldb_setup_sigint_handler\n");
3068void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3070 std::string statement;
3071 if (location == AddLocation::Beginning) {
3072 statement.assign(
"sys.path.insert(0,\"");
3073 statement.append(path);
3074 statement.append(
"\")");
3076 statement.assign(
"sys.path.append(\"");
3077 statement.append(path);
3078 statement.append(
"\")");
3080 RunSimpleString(statement.c_str());
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,...)
#define LLDB_PLUGIN_DEFINE(PluginName)
#define LLDB_SCOPED_TIMER()
"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 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.
static FileSystem & Instance()
bool IsValid() const override
IsValid.
virtual Status Flush()
Flush the current stream.
lldb::LockableStreamFileSP GetErrorStreamFileSP()
lldb::LockableStreamFileSP GetOutputStreamFileSP()
bool GetInitSession() const
LoadScriptOptions & SetInitSession(bool b)
LoadScriptOptions & SetSilent(bool b)
void PutCString(const char *cstr)
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, 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.
@ 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.
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()
A timer class that simplifies common timing metrics.
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.
@ 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::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
std::string script_source