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::CreateScriptedThreadPlanInterface() {
1531 return std::make_shared<ScriptedThreadPlanPythonInterface>(*
this);
1535ScriptInterpreterPythonImpl::CreateOperatingSystemInterface() {
1536 return std::make_shared<OperatingSystemPythonInterface>(*
this);
1540ScriptInterpreterPythonImpl::CreateStructuredDataFromScriptObject(
1542 void *ptr =
const_cast<void *
>(obj.
GetPointer());
1543 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1544 PythonObject py_obj(PyRefType::Borrowed,
static_cast<PyObject *
>(ptr));
1545 if (!py_obj.IsValid() || py_obj.IsNone())
1547 return py_obj.CreateStructuredObject();
1551ScriptInterpreterPythonImpl::LoadPluginModule(
const FileSpec &file_spec,
1562 if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1572 if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
1578 Locker py_lock(
this,
1579 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1580 TargetSP target_sp(target->shared_from_this());
1582 auto setting = (PyObject *)SWIGBridge::LLDBSWIGPython_GetDynamicSetting(
1583 generic->GetValue(), setting_name, target_sp);
1588 PythonDictionary py_dict =
1589 unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
1594 return py_dict.CreateStructuredDictionary();
1598ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
1600 if (class_name ==
nullptr || class_name[0] ==
'\0')
1607 Target *target = exe_ctx.GetTargetPtr();
1613 ScriptInterpreterPythonImpl *python_interpreter =
1614 GetPythonInterpreter(debugger);
1616 if (!python_interpreter)
1619 Locker py_lock(
this,
1620 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1621 PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateSyntheticProvider(
1622 class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
1625 new StructuredPythonObject(std::move(ret_val)));
1629ScriptInterpreterPythonImpl::CreateScriptCommandObject(
const char *class_name) {
1630 DebuggerSP debugger_sp(m_debugger.shared_from_this());
1632 if (class_name ==
nullptr || class_name[0] ==
'\0')
1635 if (!debugger_sp.get())
1638 Locker py_lock(
this,
1639 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1640 PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateCommandObject(
1641 class_name, m_dictionary_name.c_str(), debugger_sp);
1643 if (ret_val.IsValid())
1645 new StructuredPythonObject(std::move(ret_val)));
1650bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1651 const char *oneliner, std::string &output,
const void *name_token) {
1654 return GenerateTypeScriptFunction(input, output, name_token);
1657bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1658 const char *oneliner, std::string &output,
const void *name_token) {
1661 return GenerateTypeSynthClass(input, output, name_token);
1664Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
1665 StringList &user_input, std::string &output,
bool has_extra_args,
1667 static uint32_t num_created_functions = 0;
1671 if (user_input.
GetSize() == 0) {
1676 std::string auto_generated_function_name(GenerateUniqueName(
1677 "lldb_autogen_python_bp_callback_func_", num_created_functions));
1679 sstr.
Printf(
"def %s (frame, bp_loc, extra_args, internal_dict):",
1680 auto_generated_function_name.c_str());
1682 sstr.
Printf(
"def %s (frame, bp_loc, internal_dict):",
1683 auto_generated_function_name.c_str());
1685 error = GenerateFunction(sstr.
GetData(), user_input, is_callback);
1686 if (!
error.Success())
1690 output.assign(auto_generated_function_name);
1694bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
1695 StringList &user_input, std::string &output,
bool is_callback) {
1696 static uint32_t num_created_functions = 0;
1700 if (user_input.
GetSize() == 0)
1703 std::string auto_generated_function_name(GenerateUniqueName(
1704 "lldb_autogen_python_wp_callback_func_", num_created_functions));
1705 sstr.
Printf(
"def %s (frame, wp, internal_dict):",
1706 auto_generated_function_name.c_str());
1708 if (!GenerateFunction(sstr.
GetData(), user_input, is_callback).Success())
1712 output.assign(auto_generated_function_name);
1716bool ScriptInterpreterPythonImpl::GetScriptedSummary(
1723 if (!valobj.get()) {
1724 retval.assign(
"<no object>");
1728 void *old_callee =
nullptr;
1730 if (callee_wrapper_sp) {
1731 generic = callee_wrapper_sp->GetAsGeneric();
1733 old_callee =
generic->GetValue();
1735 void *new_callee = old_callee;
1738 if (python_function_name && *python_function_name) {
1740 Locker py_lock(
this, Locker::AcquireLock | Locker::InitSession |
1746 Timer scoped_timer(func_cat,
"LLDBSwigPythonCallTypeScript");
1747 ret_val = SWIGBridge::LLDBSwigPythonCallTypeScript(
1748 python_function_name, GetSessionDictionary().get(), valobj,
1749 &new_callee, options_sp, retval);
1753 retval.assign(
"<no function name>");
1757 if (new_callee && old_callee != new_callee) {
1758 Locker py_lock(
this,
1759 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1760 callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
1761 PythonObject(PyRefType::Borrowed,
static_cast<PyObject *
>(new_callee)));
1767bool ScriptInterpreterPythonImpl::FormatterCallbackFunction(
1768 const char *python_function_name,
TypeImplSP type_impl_sp) {
1769 Locker py_lock(
this,
1770 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1771 return SWIGBridge::LLDBSwigPythonFormatterCallbackFunction(
1772 python_function_name, m_dictionary_name.c_str(), type_impl_sp);
1775bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
1778 CommandDataPython *bp_option_data = (CommandDataPython *)baton;
1779 const char *python_function_name = bp_option_data->script_source.c_str();
1785 Target *target = exe_ctx.GetTargetPtr();
1791 ScriptInterpreterPythonImpl *python_interpreter =
1792 GetPythonInterpreter(debugger);
1794 if (!python_interpreter)
1797 if (python_function_name && python_function_name[0]) {
1798 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
1800 if (breakpoint_sp) {
1802 breakpoint_sp->FindLocationByID(break_loc_id));
1804 if (stop_frame_sp && bp_loc_sp) {
1805 bool ret_val =
true;
1807 Locker py_lock(python_interpreter, Locker::AcquireLock |
1808 Locker::InitSession |
1810 Expected<bool> maybe_ret_val =
1811 SWIGBridge::LLDBSwigPythonBreakpointCallbackFunction(
1812 python_function_name,
1813 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
1814 bp_loc_sp, bp_option_data->m_extra_args);
1816 if (!maybe_ret_val) {
1818 llvm::handleAllErrors(
1819 maybe_ret_val.takeError(),
1820 [&](PythonException &E) {
1821 *debugger.GetAsyncErrorStream() << E.ReadBacktrace();
1823 [&](
const llvm::ErrorInfoBase &E) {
1824 *debugger.GetAsyncErrorStream() << E.message();
1828 ret_val = maybe_ret_val.get();
1840bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
1844 const char *python_function_name = wp_option_data->
script_source.c_str();
1850 Target *target = exe_ctx.GetTargetPtr();
1856 ScriptInterpreterPythonImpl *python_interpreter =
1857 GetPythonInterpreter(debugger);
1859 if (!python_interpreter)
1862 if (python_function_name && python_function_name[0]) {
1863 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
1866 if (stop_frame_sp && wp_sp) {
1867 bool ret_val =
true;
1869 Locker py_lock(python_interpreter, Locker::AcquireLock |
1870 Locker::InitSession |
1872 ret_val = SWIGBridge::LLDBSwigPythonWatchpointCallbackFunction(
1873 python_function_name,
1874 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
1886size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
1888 if (!implementor_sp)
1893 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
1900 Locker py_lock(
this,
1901 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1902 ret_val = SWIGBridge::LLDBSwigPython_CalculateNumChildren(implementor, max);
1910 if (!implementor_sp)
1916 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
1922 Locker py_lock(
this,
1923 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1924 PyObject *child_ptr =
1925 SWIGBridge::LLDBSwigPython_GetChildAtIndex(implementor, idx);
1926 if (child_ptr !=
nullptr && child_ptr != Py_None) {
1928 (
lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
1929 if (sb_value_ptr ==
nullptr)
1930 Py_XDECREF(child_ptr);
1932 ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
1935 Py_XDECREF(child_ptr);
1942llvm::Expected<int> ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
1944 if (!implementor_sp)
1945 return llvm::createStringError(
"Type has no child named '%s'", child_name);
1949 return llvm::createStringError(
"Type has no child named '%s'", child_name);
1950 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
1952 return llvm::createStringError(
"Type has no child named '%s'", child_name);
1957 Locker py_lock(
this,
1958 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1959 ret_val = SWIGBridge::LLDBSwigPython_GetIndexOfChildWithName(implementor,
1964 return llvm::createStringError(
"Type has no child named '%s'", child_name);
1968bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
1970 bool ret_val =
false;
1972 if (!implementor_sp)
1978 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
1983 Locker py_lock(
this,
1984 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1986 SWIGBridge::LLDBSwigPython_UpdateSynthProviderInstance(implementor);
1992bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
1994 bool ret_val =
false;
1996 if (!implementor_sp)
2002 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2007 Locker py_lock(
this,
2008 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2009 ret_val = SWIGBridge::LLDBSwigPython_MightHaveChildrenSynthProviderInstance(
2020 if (!implementor_sp)
2026 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2031 Locker py_lock(
this,
2032 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2033 PyObject *child_ptr =
2034 SWIGBridge::LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2035 if (child_ptr !=
nullptr && child_ptr != Py_None) {
2037 (
lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2038 if (sb_value_ptr ==
nullptr)
2039 Py_XDECREF(child_ptr);
2041 ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
2044 Py_XDECREF(child_ptr);
2051ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2053 Locker py_lock(
this,
2054 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2056 if (!implementor_sp)
2063 PythonObject implementor(PyRefType::Borrowed,
2064 (PyObject *)generic->GetValue());
2065 if (!implementor.IsAllocated())
2068 llvm::Expected<PythonObject> expected_py_return =
2069 implementor.CallMethod(
"get_type_name");
2071 if (!expected_py_return) {
2072 llvm::consumeError(expected_py_return.takeError());
2076 PythonObject py_return = std::move(expected_py_return.get());
2077 if (!py_return.IsAllocated() || !PythonString::Check(py_return.get()))
2080 PythonString type_name(PyRefType::Borrowed, py_return.get());
2084bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2085 const char *impl_function,
Process *process, std::string &output,
2092 if (!impl_function || !impl_function[0]) {
2098 Locker py_lock(
this,
2099 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2100 ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordProcess(
2101 impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
2109bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2110 const char *impl_function,
Thread *thread, std::string &output,
2116 if (!impl_function || !impl_function[0]) {
2121 Locker py_lock(
this,
2122 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2123 if (std::optional<std::string> result =
2124 SWIGBridge::LLDBSWIGPythonRunScriptKeywordThread(
2125 impl_function, m_dictionary_name.c_str(),
2126 thread->shared_from_this())) {
2127 output = std::move(*result);
2134bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2135 const char *impl_function,
Target *target, std::string &output,
2142 if (!impl_function || !impl_function[0]) {
2148 TargetSP target_sp(target->shared_from_this());
2149 Locker py_lock(
this,
2150 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2151 ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordTarget(
2152 impl_function, m_dictionary_name.c_str(), target_sp, output);
2159bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2160 const char *impl_function,
StackFrame *frame, std::string &output,
2166 if (!impl_function || !impl_function[0]) {
2171 Locker py_lock(
this,
2172 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2173 if (std::optional<std::string> result =
2174 SWIGBridge::LLDBSWIGPythonRunScriptKeywordFrame(
2175 impl_function, m_dictionary_name.c_str(),
2176 frame->shared_from_this())) {
2177 output = std::move(*result);
2184bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2185 const char *impl_function,
ValueObject *value, std::string &output,
2192 if (!impl_function || !impl_function[0]) {
2198 Locker py_lock(
this,
2199 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2200 ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordValue(
2201 impl_function, m_dictionary_name.c_str(), value->
GetSP(), output);
2208uint64_t replace_all(std::string &str,
const std::string &oldStr,
2209 const std::string &newStr) {
2211 uint64_t matches = 0;
2212 while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2214 str.replace(pos, oldStr.length(), newStr);
2215 pos += newStr.length();
2220bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2224 namespace fs = llvm::sys::fs;
2225 namespace path = llvm::sys::path;
2231 if (!pathname || !pathname[0]) {
2236 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2240 if (!io_redirect_or_error) {
2248 Locker py_lock(
this,
2249 Locker::AcquireLock |
2252 Locker::FreeAcquiredLock |
2257 auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2258 if (directory.empty()) {
2259 return llvm::createStringError(
"invalid directory name");
2262 replace_all(directory,
"\\",
"\\\\");
2263 replace_all(directory,
"'",
"\\'");
2267 command_stream.
Printf(
"if not (sys.path.__contains__('%s')):\n "
2268 "sys.path.insert(1,'%s');\n\n",
2269 directory.c_str(), directory.c_str());
2270 bool syspath_retval =
2271 ExecuteMultipleLines(command_stream.
GetData(), exc_options).Success();
2272 if (!syspath_retval)
2273 return llvm::createStringError(
"Python sys.path handling failed");
2275 return llvm::Error::success();
2278 std::string module_name(pathname);
2279 bool possible_package =
false;
2281 if (extra_search_dir) {
2282 if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2291 std::error_code ec = status(module_file.GetPath(), st);
2293 if (ec || st.type() == fs::file_type::status_error ||
2294 st.type() == fs::file_type::type_unknown ||
2295 st.type() == fs::file_type::file_not_found) {
2298 if (strchr(pathname,
'\\') || strchr(pathname,
'/')) {
2304 possible_package =
true;
2305 }
else if (is_directory(st) || is_regular_file(st)) {
2306 if (module_file.GetDirectory().IsEmpty()) {
2308 "invalid directory name '{0}'", pathname);
2312 ExtendSysPath(module_file.GetDirectory().GetCString())) {
2316 module_name = module_file.GetFilename().GetCString();
2319 "no known way to import this module specification");
2325 llvm::StringRef extension = llvm::sys::path::extension(module_name);
2326 if (!extension.empty()) {
2327 if (extension ==
".py")
2328 module_name.resize(module_name.length() - 3);
2329 else if (extension ==
".pyc")
2330 module_name.resize(module_name.length() - 4);
2333 if (!possible_package && module_name.find(
'.') != llvm::StringRef::npos) {
2335 "Python does not allow dots in module names: %s", module_name.c_str());
2339 if (module_name.find(
'-') != llvm::StringRef::npos) {
2341 "Python discourages dashes in module names: %s", module_name.c_str());
2347 command_stream.
Clear();
2348 command_stream.
Printf(
"sys.modules.__contains__('%s')", module_name.c_str());
2349 bool does_contain =
false;
2352 const bool does_contain_executed = ExecuteOneLineWithReturn(
2354 ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain,
2357 const bool was_imported_globally = does_contain_executed && does_contain;
2358 const bool was_imported_locally =
2359 GetSessionDictionary()
2360 .GetItemForKey(PythonString(module_name))
2364 command_stream.
Clear();
2366 if (was_imported_globally || was_imported_locally) {
2367 if (!was_imported_locally)
2368 command_stream.
Printf(
"import %s ; reload_module(%s)",
2369 module_name.c_str(), module_name.c_str());
2371 command_stream.
Printf(
"reload_module(%s)", module_name.c_str());
2373 command_stream.
Printf(
"import %s", module_name.c_str());
2375 error = ExecuteMultipleLines(command_stream.
GetData(), exc_options);
2381 if (!SWIGBridge::LLDBSwigPythonCallModuleInit(
2382 module_name.c_str(), m_dictionary_name.c_str(),
2383 m_debugger.shared_from_this())) {
2390 command_stream.
Clear();
2391 command_stream.
Printf(
"%s", module_name.c_str());
2392 void *module_pyobj =
nullptr;
2393 if (ExecuteOneLineWithReturn(
2398 *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2399 PyRefType::Owned,
static_cast<PyObject *
>(module_pyobj)));
2405 return SWIGBridge::LLDBSwigPythonCallModuleNewTarget(
2406 module_name.c_str(), m_dictionary_name.c_str(), target_sp);
2411bool ScriptInterpreterPythonImpl::IsReservedWord(
const char *word) {
2412 if (!word || !word[0])
2415 llvm::StringRef word_sr(word);
2419 if (word_sr.find(
'"') != llvm::StringRef::npos ||
2420 word_sr.find(
'\'') != llvm::StringRef::npos)
2424 command_stream.
Printf(
"keyword.iskeyword('%s')", word);
2430 if (ExecuteOneLineWithReturn(command_stream.
GetData(),
2437ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2439 : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2440 m_old_asynch(debugger_sp->GetAsyncExecution()) {
2442 m_debugger_sp->SetAsyncExecution(
false);
2444 m_debugger_sp->SetAsyncExecution(
true);
2447ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
2449 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2452bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2453 const char *impl_function, llvm::StringRef args,
2454 ScriptedCommandSynchronicity synchronicity,
2457 if (!impl_function) {
2465 if (!debugger_sp.get()) {
2470 bool ret_val =
false;
2473 Locker py_lock(
this,
2474 Locker::AcquireLock | Locker::InitSession |
2476 Locker::FreeLock | Locker::TearDownSession);
2478 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2480 std::string args_str = args.str();
2481 ret_val = SWIGBridge::LLDBSwigPythonCallCommand(
2482 impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2483 cmd_retobj, exe_ctx_ref_sp);
2495bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2497 ScriptedCommandSynchronicity synchronicity,
2500 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2508 if (!debugger_sp.get()) {
2513 bool ret_val =
false;
2516 Locker py_lock(
this,
2517 Locker::AcquireLock | Locker::InitSession |
2519 Locker::FreeLock | Locker::TearDownSession);
2521 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2523 std::string args_str = args.str();
2524 ret_val = SWIGBridge::LLDBSwigPythonCallCommandObject(
2525 static_cast<PyObject *
>(impl_obj_sp->GetValue()), debugger_sp,
2526 args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
2538bool ScriptInterpreterPythonImpl::RunScriptBasedParsedCommand(
2540 ScriptedCommandSynchronicity synchronicity,
2543 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2551 if (!debugger_sp.get()) {
2556 bool ret_val =
false;
2559 Locker py_lock(
this,
2560 Locker::AcquireLock | Locker::InitSession |
2562 Locker::FreeLock | Locker::TearDownSession);
2564 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2569 args_arr_sp->AddStringItem(entry.ref());
2573 ret_val = SWIGBridge::LLDBSwigPythonCallParsedCommandObject(
2574 static_cast<PyObject *
>(impl_obj_sp->GetValue()), debugger_sp,
2575 args_impl, cmd_retobj, exe_ctx_ref_sp);
2587std::optional<std::string>
2588ScriptInterpreterPythonImpl::GetRepeatCommandForScriptedCommand(
2590 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2591 return std::nullopt;
2595 if (!debugger_sp.get())
2596 return std::nullopt;
2598 std::optional<std::string> ret_val;
2601 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN,
2607 std::string command;
2608 args.GetQuotedCommandString(command);
2609 ret_val = SWIGBridge::LLDBSwigPythonGetRepeatCommandForScriptedCommand(
2610 static_cast<PyObject *
>(impl_obj_sp->GetValue()), command);
2616ScriptInterpreterPythonImpl::HandleArgumentCompletionForScriptedCommand(
2618 size_t args_pos,
size_t char_in_arg) {
2620 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2621 return completion_dict_sp;
2624 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN,
2627 completion_dict_sp =
2628 SWIGBridge::LLDBSwigPythonHandleArgumentCompletionForScriptedCommand(
2629 static_cast<PyObject *
>(impl_obj_sp->GetValue()), args, args_pos,
2632 return completion_dict_sp;
2636ScriptInterpreterPythonImpl::HandleOptionArgumentCompletionForScriptedCommand(
2638 size_t char_in_arg) {
2640 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2641 return completion_dict_sp;
2644 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN,
2647 completion_dict_sp = SWIGBridge::
2648 LLDBSwigPythonHandleOptionArgumentCompletionForScriptedCommand(
2649 static_cast<PyObject *
>(impl_obj_sp->GetValue()), long_option,
2652 return completion_dict_sp;
2658bool ScriptInterpreterPythonImpl::GetDocumentationForItem(
const char *item,
2659 std::string &dest) {
2662 if (!item || !*item)
2665 std::string command(item);
2666 command +=
".__doc__";
2670 char *result_ptr =
nullptr;
2672 if (ExecuteOneLineWithReturn(
2676 dest.assign(result_ptr);
2681 str_stream <<
"Function " << item
2682 <<
" was not found. Containing module might be missing.";
2683 dest = std::string(str_stream.
GetString());
2688bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
2692 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2697 PythonObject implementor(PyRefType::Borrowed,
2698 (PyObject *)cmd_obj_sp->GetValue());
2700 if (!implementor.IsAllocated())
2703 llvm::Expected<PythonObject> expected_py_return =
2704 implementor.CallMethod(
"get_short_help");
2706 if (!expected_py_return) {
2707 llvm::consumeError(expected_py_return.takeError());
2711 PythonObject py_return = std::move(expected_py_return.get());
2713 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2714 PythonString py_string(PyRefType::Borrowed, py_return.get());
2715 llvm::StringRef return_data(py_string.GetString());
2716 dest.assign(return_data.data(), return_data.size());
2723uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
2725 uint32_t result = 0;
2727 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2729 static char callee_name[] =
"get_flags";
2734 PythonObject implementor(PyRefType::Borrowed,
2735 (PyObject *)cmd_obj_sp->GetValue());
2737 if (!implementor.IsAllocated())
2740 PythonObject pmeth(PyRefType::Owned,
2741 PyObject_GetAttrString(implementor.get(), callee_name));
2743 if (PyErr_Occurred())
2746 if (!pmeth.IsAllocated())
2749 if (PyCallable_Check(pmeth.get()) == 0) {
2750 if (PyErr_Occurred())
2755 if (PyErr_Occurred())
2758 long long py_return = unwrapOrSetPythonException(
2759 As<long long>(implementor.CallMethod(callee_name)));
2762 if (PyErr_Occurred()) {
2773ScriptInterpreterPythonImpl::GetOptionsForCommandObject(
2777 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2779 static char callee_name[] =
"get_options_definition";
2784 PythonObject implementor(PyRefType::Borrowed,
2785 (PyObject *)cmd_obj_sp->GetValue());
2787 if (!implementor.IsAllocated())
2790 PythonObject pmeth(PyRefType::Owned,
2791 PyObject_GetAttrString(implementor.get(), callee_name));
2793 if (PyErr_Occurred())
2796 if (!pmeth.IsAllocated())
2799 if (PyCallable_Check(pmeth.get()) == 0) {
2800 if (PyErr_Occurred())
2805 if (PyErr_Occurred())
2808 PythonDictionary py_return = unwrapOrSetPythonException(
2809 As<PythonDictionary>(implementor.CallMethod(callee_name)));
2812 if (PyErr_Occurred()) {
2817 return py_return.CreateStructuredObject();
2821ScriptInterpreterPythonImpl::GetArgumentsForCommandObject(
2825 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2827 static char callee_name[] =
"get_args_definition";
2832 PythonObject implementor(PyRefType::Borrowed,
2833 (PyObject *)cmd_obj_sp->GetValue());
2835 if (!implementor.IsAllocated())
2838 PythonObject pmeth(PyRefType::Owned,
2839 PyObject_GetAttrString(implementor.get(), callee_name));
2841 if (PyErr_Occurred())
2844 if (!pmeth.IsAllocated())
2847 if (PyCallable_Check(pmeth.get()) == 0) {
2848 if (PyErr_Occurred())
2853 if (PyErr_Occurred())
2856 PythonList py_return = unwrapOrSetPythonException(
2857 As<PythonList>(implementor.CallMethod(callee_name)));
2860 if (PyErr_Occurred()) {
2865 return py_return.CreateStructuredObject();
2868void ScriptInterpreterPythonImpl::OptionParsingStartedForCommandObject(
2871 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2873 static char callee_name[] =
"option_parsing_started";
2878 PythonObject implementor(PyRefType::Borrowed,
2879 (PyObject *)cmd_obj_sp->GetValue());
2881 if (!implementor.IsAllocated())
2884 PythonObject pmeth(PyRefType::Owned,
2885 PyObject_GetAttrString(implementor.get(), callee_name));
2887 if (PyErr_Occurred())
2890 if (!pmeth.IsAllocated())
2893 if (PyCallable_Check(pmeth.get()) == 0) {
2894 if (PyErr_Occurred())
2899 if (PyErr_Occurred())
2904 unwrapOrSetPythonException(As<bool>(implementor.CallMethod(callee_name)));
2907 if (PyErr_Occurred()) {
2914bool ScriptInterpreterPythonImpl::SetOptionValueForCommandObject(
2916 llvm::StringRef long_option, llvm::StringRef value) {
2919 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2921 static char callee_name[] =
"set_option_value";
2926 PythonObject implementor(PyRefType::Borrowed,
2927 (PyObject *)cmd_obj_sp->GetValue());
2929 if (!implementor.IsAllocated())
2932 PythonObject pmeth(PyRefType::Owned,
2933 PyObject_GetAttrString(implementor.get(), callee_name));
2935 if (PyErr_Occurred())
2938 if (!pmeth.IsAllocated())
2941 if (PyCallable_Check(pmeth.get()) == 0) {
2942 if (PyErr_Occurred())
2947 if (PyErr_Occurred())
2952 exe_ctx_ref_sp = std::make_shared<ExecutionContextRef>(exe_ctx);
2953 PythonObject ctx_ref_obj = SWIGBridge::ToSWIGWrapper(exe_ctx_ref_sp);
2955 bool py_return = unwrapOrSetPythonException(As<bool>(
2956 implementor.CallMethod(callee_name, ctx_ref_obj,
2957 long_option.str().c_str(), value.str().c_str())));
2960 if (PyErr_Occurred()) {
2968bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
2972 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2977 PythonObject implementor(PyRefType::Borrowed,
2978 (PyObject *)cmd_obj_sp->GetValue());
2980 if (!implementor.IsAllocated())
2983 llvm::Expected<PythonObject> expected_py_return =
2984 implementor.CallMethod(
"get_long_help");
2986 if (!expected_py_return) {
2987 llvm::consumeError(expected_py_return.takeError());
2991 PythonObject py_return = std::move(expected_py_return.get());
2993 bool got_string =
false;
2994 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2995 PythonString str(PyRefType::Borrowed, py_return.get());
2996 llvm::StringRef str_data(str.GetString());
2997 dest.assign(str_data.data(), str_data.size());
3004std::unique_ptr<ScriptInterpreterLocker>
3005ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3006 std::unique_ptr<ScriptInterpreterLocker> py_lock(
new Locker(
3007 this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3008 Locker::FreeLock | Locker::TearDownSession));
3012void ScriptInterpreterPythonImpl::Initialize() {
3019 InitializePythonRAII initialize_guard;
3026 RunSimpleString(
"import sys");
3027 AddToSysPath(AddLocation::End,
".");
3033 if (
FileSpec file_spec = GetPythonDir())
3034 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(
false));
3035 if (
FileSpec file_spec = HostInfo::GetShlibDir())
3036 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(
false));
3038 RunSimpleString(
"sys.dont_write_bytecode = 1; import "
3039 "lldb.embedded_interpreter; from "
3040 "lldb.embedded_interpreter import run_python_interpreter; "
3041 "from lldb.embedded_interpreter import run_one_line");
3043#if LLDB_USE_PYTHON_SET_INTERRUPT
3047 RestoreSignalHandlerScope save_sigint(SIGINT);
3053 RunSimpleString(
"def lldb_setup_sigint_handler():\n"
3055 " def signal_handler(sig, frame):\n"
3056 " raise KeyboardInterrupt()\n"
3057 " signal.signal(signal.SIGINT, signal_handler);\n"
3058 "lldb_setup_sigint_handler();\n"
3059 "del lldb_setup_sigint_handler\n");
3063void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3065 std::string statement;
3066 if (location == AddLocation::Beginning) {
3067 statement.assign(
"sys.path.insert(0,\"");
3068 statement.append(path);
3069 statement.append(
"\")");
3071 statement.assign(
"sys.path.append(\"");
3072 statement.append(path);
3073 statement.append(
"\")");
3075 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::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