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 this_file.RemoveLastPathComponent();
277 llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
278 for (
auto it = llvm::sys::path::begin(libdir),
279 end = llvm::sys::path::end(libdir);
281 this_file.RemoveLastPathComponent();
282 this_file.AppendPathComponent(
"bin");
283 this_file.AppendPathComponent(
"liblldb.dll");
292llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() {
293 return "Embedded Python interpreter";
296void ScriptInterpreterPython::Initialize() {
297 static llvm::once_flag g_once_flag;
298 llvm::call_once(g_once_flag, []() {
300 GetPluginDescriptionStatic(),
302 ScriptInterpreterPythonImpl::CreateInstance);
303 ScriptInterpreterPythonImpl::Initialize();
307void ScriptInterpreterPython::Terminate() {}
309ScriptInterpreterPythonImpl::Locker::Locker(
310 ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
313 m_teardown_session((on_leave & TearDownSession) == TearDownSession),
314 m_python_interpreter(py_interpreter) {
316 if ((on_entry & InitSession) == InitSession) {
317 if (!DoInitSession(on_entry, in, out, err)) {
319 m_teardown_session =
false;
324bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
325 m_GILState = PyGILState_Ensure();
327 m_GILState == PyGILState_UNLOCKED ?
"unlocked" :
"locked");
334 m_python_interpreter->SetThreadState(PyThreadState_Get());
335 m_python_interpreter->IncrementLockCount();
339bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
342 if (!m_python_interpreter)
344 return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
347bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
349 "Releasing PyGILState. Returning to state = {0}",
350 m_GILState == PyGILState_UNLOCKED ?
"unlocked" :
"locked");
351 PyGILState_Release(m_GILState);
352 m_python_interpreter->DecrementLockCount();
356bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
357 if (!m_python_interpreter)
359 m_python_interpreter->LeaveSession();
363ScriptInterpreterPythonImpl::Locker::~Locker() {
364 if (m_teardown_session)
369ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(
Debugger &debugger)
370 : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
371 m_saved_stderr(), m_main_module(),
372 m_session_dict(PyInitialValue::
Invalid),
373 m_sys_module_dict(PyInitialValue::
Invalid), m_run_one_line_function(),
374 m_run_one_line_str_global(),
375 m_dictionary_name(m_debugger.GetInstanceName()),
377 m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
378 m_command_thread_state(nullptr) {
380 m_dictionary_name.append(
"_dict");
382 run_string.
Printf(
"%s = dict()", m_dictionary_name.c_str());
384 Locker locker(
this, Locker::AcquireLock, Locker::FreeAcquiredLock);
385 RunSimpleString(run_string.
GetData());
389 "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
390 m_dictionary_name.c_str());
391 RunSimpleString(run_string.
GetData());
397 "run_one_line (%s, 'from importlib import reload as reload_module')",
398 m_dictionary_name.c_str());
399 RunSimpleString(run_string.
GetData());
407 "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp')",
408 m_dictionary_name.c_str());
409 RunSimpleString(run_string.
GetData());
412 run_string.
Printf(
"run_one_line (%s, 'import lldb.embedded_interpreter; from "
413 "lldb.embedded_interpreter import run_python_interpreter; "
414 "from lldb.embedded_interpreter import run_one_line')",
415 m_dictionary_name.c_str());
416 RunSimpleString(run_string.
GetData());
419 run_string.
Printf(
"run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
421 m_dictionary_name.c_str(), m_debugger.GetID());
422 RunSimpleString(run_string.
GetData());
425ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
431 auto gil_state = PyGILState_Ensure();
432 m_session_dict.Reset();
433 PyGILState_Release(gil_state);
436void ScriptInterpreterPythonImpl::IOHandlerActivated(
IOHandler &io_handler,
438 const char *instructions =
nullptr;
440 switch (m_active_io_handler) {
444 instructions = R
"(Enter your Python command(s). Type 'DONE' to end.
445def function (frame, bp_loc, internal_dict):
446 """frame: the lldb.SBFrame for the location at which you stopped
447 bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
448 internal_dict: an LLDB support object not to be used"""
452 instructions =
"Enter your Python command(s). Type 'DONE' to end.\n";
456 if (instructions && interactive) {
460 locked_stream.
Flush();
465void ScriptInterpreterPythonImpl::IOHandlerInputComplete(
IOHandler &io_handler,
468 bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
470 switch (m_active_io_handler) {
474 std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
475 (std::vector<std::reference_wrapper<BreakpointOptions>> *)
479 auto data_up = std::make_unique<CommandDataPython>();
482 data_up->user_source.SplitIntoLines(data);
484 if (GenerateBreakpointCommandCallbackData(data_up->user_source,
485 data_up->script_source,
489 auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
491 bp_options.SetCallback(
492 ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
493 }
else if (!batch_mode) {
496 locked_stream.
Printf(
"Warning: No command attached to breakpoint.\n");
505 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
506 data_up->user_source.SplitIntoLines(data);
508 if (GenerateWatchpointCommandCallbackData(data_up->user_source,
509 data_up->script_source,
512 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
514 ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
515 }
else if (!batch_mode) {
518 locked_stream.
Printf(
"Warning: No command attached to breakpoint.\n");
527ScriptInterpreterPythonImpl::CreateInstance(
Debugger &debugger) {
528 return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
531void ScriptInterpreterPythonImpl::LeaveSession() {
534 log->
PutCString(
"ScriptInterpreterPythonImpl::LeaveSession()");
537 RunSimpleString(
"lldb.debugger = None; lldb.target = None; lldb.process "
538 "= None; lldb.thread = None; lldb.frame = None");
545 if (PyThreadState_GetDict()) {
546 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
547 if (sys_module_dict.IsValid()) {
548 if (m_saved_stdin.IsValid()) {
549 sys_module_dict.SetItemForKey(PythonString(
"stdin"), m_saved_stdin);
550 m_saved_stdin.Reset();
552 if (m_saved_stdout.IsValid()) {
553 sys_module_dict.SetItemForKey(PythonString(
"stdout"), m_saved_stdout);
554 m_saved_stdout.Reset();
556 if (m_saved_stderr.IsValid()) {
557 sys_module_dict.SetItemForKey(PythonString(
"stderr"), m_saved_stderr);
558 m_saved_stderr.Reset();
563 m_session_is_active =
false;
566bool ScriptInterpreterPythonImpl::SetStdHandle(
FileSP file_sp,
568 PythonObject &save_file,
570 if (!file_sp || !*file_sp) {
574 File &file = *file_sp;
579 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
581 auto new_file = PythonFile::FromFile(file, mode);
583 llvm::consumeError(new_file.takeError());
587 save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
589 sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
593bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
599 if (m_session_is_active) {
602 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
603 ") session is already active, returning without doing anything",
610 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
")",
613 m_session_is_active =
true;
617 if (on_entry_flags & Locker::InitGlobals) {
618 run_string.
Printf(
"run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
619 m_dictionary_name.c_str(), m_debugger.GetID());
621 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64
")",
623 run_string.
PutCString(
"; lldb.target = lldb.debugger.GetSelectedTarget()");
624 run_string.
PutCString(
"; lldb.process = lldb.target.GetProcess()");
625 run_string.
PutCString(
"; lldb.thread = lldb.process.GetSelectedThread ()");
626 run_string.
PutCString(
"; lldb.frame = lldb.thread.GetSelectedFrame ()");
631 run_string.
Printf(
"run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
632 m_dictionary_name.c_str(), m_debugger.GetID());
634 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64
")",
639 RunSimpleString(run_string.
GetData());
642 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
643 if (sys_module_dict.IsValid()) {
646 if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
647 m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
650 if (on_entry_flags & Locker::NoSTDIN) {
651 m_saved_stdin.Reset();
653 if (!SetStdHandle(in_sp,
"stdin", m_saved_stdin,
"r")) {
655 SetStdHandle(top_in_sp,
"stdin", m_saved_stdin,
"r");
659 if (!SetStdHandle(out_sp,
"stdout", m_saved_stdout,
"w")) {
661 SetStdHandle(top_out_sp->GetUnlockedFileSP(),
"stdout", m_saved_stdout,
665 if (!SetStdHandle(err_sp,
"stderr", m_saved_stderr,
"w")) {
667 SetStdHandle(top_err_sp->GetUnlockedFileSP(),
"stderr", m_saved_stderr,
672 if (PyErr_Occurred())
678PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
679 if (!m_main_module.IsValid())
680 m_main_module = unwrapIgnoringErrors(PythonModule::Import(
"__main__"));
681 return m_main_module;
684PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
685 if (m_session_dict.IsValid())
686 return m_session_dict;
688 PythonObject &main_module = GetMainModule();
689 if (!main_module.IsValid())
690 return m_session_dict;
692 PythonDictionary main_dict(PyRefType::Borrowed,
693 PyModule_GetDict(main_module.get()));
694 if (!main_dict.IsValid())
695 return m_session_dict;
697 m_session_dict = unwrapIgnoringErrors(
698 As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
699 return m_session_dict;
702PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
703 if (m_sys_module_dict.IsValid())
704 return m_sys_module_dict;
705 PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import(
"sys"));
706 m_sys_module_dict = sys_module.GetDictionary();
707 return m_sys_module_dict;
710llvm::Expected<unsigned>
711ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
712 const llvm::StringRef &callable_name) {
713 if (callable_name.empty()) {
714 return llvm::createStringError(llvm::inconvertibleErrorCode(),
715 "called with empty callable name.");
718 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
719 auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
721 auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
722 callable_name, dict);
723 if (!pfunc.IsAllocated()) {
724 return llvm::createStringError(llvm::inconvertibleErrorCode(),
725 "can't find callable: %s",
726 callable_name.str().c_str());
728 llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
730 return arg_info.takeError();
731 return arg_info.get().max_positional_args;
734static std::string GenerateUniqueName(
const char *base_name_wanted,
735 uint32_t &functions_counter,
736 const void *name_token =
nullptr) {
739 if (!base_name_wanted)
740 return std::string();
743 sstr.
Printf(
"%s_%d", base_name_wanted, functions_counter++);
745 sstr.
Printf(
"%s_%p", base_name_wanted, name_token);
750bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
751 if (m_run_one_line_function.IsValid())
754 PythonObject module(PyRefType::Borrowed,
755 PyImport_AddModule(
"lldb.embedded_interpreter"));
756 if (!module.IsValid())
759 PythonDictionary module_dict(PyRefType::Borrowed,
760 PyModule_GetDict(module.get()));
761 if (!module_dict.IsValid())
764 m_run_one_line_function =
765 module_dict.GetItemForKey(PythonString(
"run_one_line"));
766 m_run_one_line_str_global =
767 module_dict.GetItemForKey(PythonString(
"g_run_one_line_str"));
768 return m_run_one_line_function.IsValid();
771bool ScriptInterpreterPythonImpl::ExecuteOneLine(
774 std::string command_str = command.str();
776 if (!m_valid_session)
779 if (!command.empty()) {
786 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
789 if (!io_redirect_or_error) {
792 "failed to redirect I/O: {0}\n",
793 llvm::fmt_consume(io_redirect_or_error.takeError()));
795 llvm::consumeError(io_redirect_or_error.takeError());
801 bool success =
false;
813 Locker::AcquireLock | Locker::InitSession |
816 Locker::FreeAcquiredLock | Locker::TearDownSession,
821 PythonDictionary &session_dict = GetSessionDictionary();
822 if (session_dict.IsValid()) {
823 if (GetEmbeddedInterpreterModuleObjects()) {
824 if (PyCallable_Check(m_run_one_line_function.get())) {
827 Py_BuildValue(
"(Os)", session_dict.get(), command_str.c_str()));
828 if (pargs.IsValid()) {
829 PythonObject return_value(
831 PyObject_CallObject(m_run_one_line_function.get(),
833 if (return_value.IsValid())
853 "python failed attempting to evaluate '%s'\n", command_str.c_str());
859 result->
AppendError(
"empty command passed to python\n");
863void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
877 IOHandlerSP io_handler_sp(
new IOHandlerPythonInterpreter(debugger,
this));
883bool ScriptInterpreterPythonImpl::Interrupt() {
884#if LLDB_USE_PYTHON_SET_INTERRUPT
888 if (!IsExecutingPython())
892 PyErr_SetInterrupt();
902 if (IsExecutingPython()) {
903 PyThreadState *state = PyThreadState_Get();
905 state = GetThreadState();
907 long tid = PyThread_get_thread_ident();
908 PyThreadState_Swap(state);
909 int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
911 "ScriptInterpreterPythonImpl::Interrupt() sending "
912 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
918 "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
924bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
928 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
932 if (!io_redirect_or_error) {
933 llvm::consumeError(io_redirect_or_error.takeError());
940 Locker::AcquireLock | Locker::InitSession |
943 Locker::FreeAcquiredLock | Locker::TearDownSession,
947 PythonModule &main_module = GetMainModule();
948 PythonDictionary globals = main_module.GetDictionary();
950 PythonDictionary locals = GetSessionDictionary();
951 if (!locals.IsValid())
952 locals = unwrapIgnoringErrors(
953 As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
954 if (!locals.IsValid())
957 Expected<PythonObject> maybe_py_return =
958 runStringOneLine(in_string, globals, locals);
960 if (!maybe_py_return) {
961 llvm::handleAllErrors(
962 maybe_py_return.takeError(),
963 [&](PythonException &E) {
965 if (options.GetMaskoutErrors()) {
966 if (E.Matches(PyExc_SyntaxError)) {
972 [](
const llvm::ErrorInfoBase &E) {});
976 PythonObject py_return = std::move(maybe_py_return.get());
977 assert(py_return.IsValid());
979 switch (return_type) {
980 case eScriptReturnTypeCharPtr:
982 const char format[3] =
"s#";
983 return PyArg_Parse(py_return.get(), format, (
char **)ret_value);
985 case eScriptReturnTypeCharStrOrNone:
988 const char format[3] =
"z";
989 return PyArg_Parse(py_return.get(), format, (
char **)ret_value);
991 case eScriptReturnTypeBool: {
992 const char format[2] =
"b";
993 return PyArg_Parse(py_return.get(), format, (
bool *)ret_value);
995 case eScriptReturnTypeShortInt: {
996 const char format[2] =
"h";
997 return PyArg_Parse(py_return.get(), format, (
short *)ret_value);
999 case eScriptReturnTypeShortIntUnsigned: {
1000 const char format[2] =
"H";
1001 return PyArg_Parse(py_return.get(), format, (
unsigned short *)ret_value);
1003 case eScriptReturnTypeInt: {
1004 const char format[2] =
"i";
1005 return PyArg_Parse(py_return.get(), format, (
int *)ret_value);
1007 case eScriptReturnTypeIntUnsigned: {
1008 const char format[2] =
"I";
1009 return PyArg_Parse(py_return.get(), format, (
unsigned int *)ret_value);
1011 case eScriptReturnTypeLongInt: {
1012 const char format[2] =
"l";
1013 return PyArg_Parse(py_return.get(), format, (
long *)ret_value);
1015 case eScriptReturnTypeLongIntUnsigned: {
1016 const char format[2] =
"k";
1017 return PyArg_Parse(py_return.get(), format, (
unsigned long *)ret_value);
1019 case eScriptReturnTypeLongLong: {
1020 const char format[2] =
"L";
1021 return PyArg_Parse(py_return.get(), format, (
long long *)ret_value);
1023 case eScriptReturnTypeLongLongUnsigned: {
1024 const char format[2] =
"K";
1025 return PyArg_Parse(py_return.get(), format,
1026 (
unsigned long long *)ret_value);
1028 case eScriptReturnTypeFloat: {
1029 const char format[2] =
"f";
1030 return PyArg_Parse(py_return.get(), format, (
float *)ret_value);
1032 case eScriptReturnTypeDouble: {
1033 const char format[2] =
"d";
1034 return PyArg_Parse(py_return.get(), format, (
double *)ret_value);
1036 case eScriptReturnTypeChar: {
1037 const char format[2] =
"c";
1038 return PyArg_Parse(py_return.get(), format, (
char *)ret_value);
1040 case eScriptReturnTypeOpaqueObject: {
1041 *((PyObject **)ret_value) = py_return.release();
1045 llvm_unreachable(
"Fully covered switch!");
1048Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1051 if (in_string ==
nullptr)
1054 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1058 if (!io_redirect_or_error)
1064 Locker::AcquireLock | Locker::InitSession |
1067 Locker::FreeAcquiredLock | Locker::TearDownSession,
1071 PythonModule &main_module = GetMainModule();
1072 PythonDictionary globals = main_module.GetDictionary();
1074 PythonDictionary locals = GetSessionDictionary();
1075 if (!locals.IsValid())
1076 locals = unwrapIgnoringErrors(
1077 As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1078 if (!locals.IsValid())
1081 Expected<PythonObject> return_value =
1082 runStringMultiLine(in_string, globals, locals);
1084 if (!return_value) {
1086 llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
1087 llvm::Error error = llvm::createStringError(
1088 llvm::inconvertibleErrorCode(), E.ReadBacktrace());
1089 if (!options.GetMaskoutErrors())
1099void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1100 std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1103 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1104 " ", *
this, &bp_options_vec);
1107void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1110 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1111 " ", *
this, wp_options);
1114Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1119 std::string function_signature = function_name;
1121 llvm::Expected<unsigned> maybe_args =
1122 GetMaxPositionalArgumentsForCallable(function_name);
1125 "could not get num args: %s",
1126 llvm::toString(maybe_args.takeError()).c_str());
1129 size_t max_args = *maybe_args;
1131 bool uses_extra_args =
false;
1132 if (max_args >= 4) {
1133 uses_extra_args =
true;
1134 function_signature +=
"(frame, bp_loc, extra_args, internal_dict)";
1135 }
else if (max_args >= 3) {
1136 if (extra_args_sp) {
1138 "cannot pass extra_args to a three argument callback");
1141 uses_extra_args =
false;
1142 function_signature +=
"(frame, bp_loc, internal_dict)";
1145 "function, %s can only take %zu",
1146 function_name, max_args);
1150 SetBreakpointCommandCallback(bp_options, function_signature.c_str(),
1151 extra_args_sp, uses_extra_args,
1156Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1158 std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
1160 error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1161 cmd_data_up->script_source,
1168 std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1170 ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1174Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1177 return SetBreakpointCommandCallback(bp_options, command_body_text, {},
1178 false, is_callback);
1182Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1186 auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1192 data_up->user_source.SplitIntoLines(command_body_text);
1193 Status error = GenerateBreakpointCommandCallbackData(
1194 data_up->user_source, data_up->script_source, uses_extra_args,
1196 if (
error.Success()) {
1198 std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1200 ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1207void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1209 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
1216 data_up->user_source.AppendString(user_input);
1217 data_up->script_source.assign(user_input);
1219 if (GenerateWatchpointCommandCallbackData(
1220 data_up->user_source, data_up->script_source, is_callback)) {
1222 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
1224 ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
1228Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1231 std::string function_def_string(function_def.
CopyList());
1233 function_def_string.c_str());
1240Status ScriptInterpreterPythonImpl::GenerateFunction(
const char *signature,
1244 int num_lines = input.
GetSize();
1245 if (num_lines == 0) {
1250 if (!signature || *signature == 0) {
1259 " global_dict = globals()");
1261 " new_keys = internal_dict.keys()");
1264 " old_keys = global_dict.keys()");
1266 " global_dict.update(internal_dict)");
1273 if (num_lines == 1) {
1279 "ScriptInterpreterPythonImpl::GenerateFunction(is_callback="
1280 "true) = ERROR: python function is multiline.");
1284 " __return_val = None");
1286 " def __user_code():");
1290 for (
int i = 0; i < num_lines; ++i) {
1296 " __return_val = __user_code()");
1300 " for key in new_keys:");
1303 " if key in old_keys:");
1306 " internal_dict[key] = global_dict[key]");
1308 " elif key in global_dict:");
1311 " del global_dict[key]");
1314 " return __return_val");
1317 error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
1322bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1323 StringList &user_input, std::string &output,
const void *name_token) {
1324 static uint32_t num_created_functions = 0;
1329 if (user_input.
GetSize() == 0)
1335 std::string auto_generated_function_name(
1336 GenerateUniqueName(
"lldb_autogen_python_type_print_func",
1337 num_created_functions, name_token));
1338 sstr.
Printf(
"def %s (valobj, internal_dict):",
1339 auto_generated_function_name.c_str());
1341 if (!GenerateFunction(sstr.
GetData(), user_input,
false)
1346 output.assign(auto_generated_function_name);
1350bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1351 StringList &user_input, std::string &output) {
1352 static uint32_t num_created_functions = 0;
1357 if (user_input.
GetSize() == 0)
1360 std::string auto_generated_function_name(GenerateUniqueName(
1361 "lldb_autogen_python_cmd_alias_func", num_created_functions));
1363 sstr.
Printf(
"def %s (debugger, args, exe_ctx, result, internal_dict):",
1364 auto_generated_function_name.c_str());
1366 if (!GenerateFunction(sstr.
GetData(), user_input,
false)
1371 output.assign(auto_generated_function_name);
1375bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1376 StringList &user_input, std::string &output,
const void *name_token) {
1377 static uint32_t num_created_classes = 0;
1379 int num_lines = user_input.
GetSize();
1383 if (user_input.
GetSize() == 0)
1388 std::string auto_generated_class_name(GenerateUniqueName(
1389 "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1395 sstr.
Printf(
"class %s:", auto_generated_class_name.c_str());
1401 for (
int i = 0; i < num_lines; ++i) {
1410 if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).
Success())
1415 output.assign(auto_generated_class_name);
1420ScriptInterpreterPythonImpl::CreateFrameRecognizer(
const char *class_name) {
1421 if (class_name ==
nullptr || class_name[0] ==
'\0')
1424 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1425 PythonObject ret_val = SWIGBridge::LLDBSWIGPython_CreateFrameRecognizer(
1426 class_name, m_dictionary_name.c_str());
1429 new StructuredPythonObject(std::move(ret_val)));
1435 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1437 if (!os_plugin_object_sp)
1444 PythonObject implementor(PyRefType::Borrowed,
1445 (PyObject *)generic->GetValue());
1447 if (!implementor.IsAllocated())
1450 PythonObject py_return(PyRefType::Owned,
1451 SWIGBridge::LLDBSwigPython_GetRecognizedArguments(
1452 implementor.get(), frame_sp));
1455 if (PyErr_Occurred()) {
1459 if (py_return.get()) {
1460 PythonList result_list(PyRefType::Borrowed, py_return.get());
1462 for (
size_t i = 0; i < result_list.GetSize(); i++) {
1463 PyObject *item = result_list.GetItemAtIndex(i).get();
1465 (
lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
1467 SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
1469 result->Append(valobj_sp);
1476bool ScriptInterpreterPythonImpl::ShouldHide(
1479 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1481 if (!os_plugin_object_sp)
1488 PythonObject implementor(PyRefType::Borrowed,
1489 (PyObject *)generic->GetValue());
1491 if (!implementor.IsAllocated())
1495 SWIGBridge::LLDBSwigPython_ShouldHide(implementor.get(), frame_sp);
1498 if (PyErr_Occurred()) {
1506ScriptInterpreterPythonImpl::CreateScriptedProcessInterface() {
1507 return std::make_unique<ScriptedProcessPythonInterface>(*
this);
1511ScriptInterpreterPythonImpl::CreateScriptedStopHookInterface() {
1512 return std::make_shared<ScriptedStopHookPythonInterface>(*
this);
1516ScriptInterpreterPythonImpl::CreateScriptedBreakpointInterface() {
1517 return std::make_shared<ScriptedBreakpointPythonInterface>(*
this);
1521ScriptInterpreterPythonImpl::CreateScriptedThreadInterface() {
1522 return std::make_shared<ScriptedThreadPythonInterface>(*
this);
1526ScriptInterpreterPythonImpl::CreateScriptedFrameInterface() {
1527 return std::make_shared<ScriptedFramePythonInterface>(*
this);
1531ScriptInterpreterPythonImpl::CreateScriptedFrameProviderInterface() {
1532 return std::make_shared<ScriptedFrameProviderPythonInterface>(*
this);
1536ScriptInterpreterPythonImpl::CreateScriptedThreadPlanInterface() {
1537 return std::make_shared<ScriptedThreadPlanPythonInterface>(*
this);
1541ScriptInterpreterPythonImpl::CreateOperatingSystemInterface() {
1542 return std::make_shared<OperatingSystemPythonInterface>(*
this);
1546ScriptInterpreterPythonImpl::CreateStructuredDataFromScriptObject(
1548 void *ptr =
const_cast<void *
>(obj.
GetPointer());
1549 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1550 PythonObject py_obj(PyRefType::Borrowed,
static_cast<PyObject *
>(ptr));
1551 if (!py_obj.IsValid() || py_obj.IsNone())
1553 return py_obj.CreateStructuredObject();
1557ScriptInterpreterPythonImpl::LoadPluginModule(
const FileSpec &file_spec,
1568 if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1578 if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
1584 Locker py_lock(
this,
1585 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1586 TargetSP target_sp(target->shared_from_this());
1588 auto setting = (PyObject *)SWIGBridge::LLDBSWIGPython_GetDynamicSetting(
1589 generic->GetValue(), setting_name, target_sp);
1594 PythonDictionary py_dict =
1595 unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
1600 return py_dict.CreateStructuredDictionary();
1604ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
1606 if (class_name ==
nullptr || class_name[0] ==
'\0')
1613 Target *target = exe_ctx.GetTargetPtr();
1619 ScriptInterpreterPythonImpl *python_interpreter =
1620 GetPythonInterpreter(debugger);
1622 if (!python_interpreter)
1625 Locker py_lock(
this,
1626 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1627 PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateSyntheticProvider(
1628 class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
1631 new StructuredPythonObject(std::move(ret_val)));
1635ScriptInterpreterPythonImpl::CreateScriptCommandObject(
const char *class_name) {
1636 DebuggerSP debugger_sp(m_debugger.shared_from_this());
1638 if (class_name ==
nullptr || class_name[0] ==
'\0')
1641 if (!debugger_sp.get())
1644 Locker py_lock(
this,
1645 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1646 PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateCommandObject(
1647 class_name, m_dictionary_name.c_str(), debugger_sp);
1649 if (ret_val.IsValid())
1651 new StructuredPythonObject(std::move(ret_val)));
1656bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1657 const char *oneliner, std::string &output,
const void *name_token) {
1660 return GenerateTypeScriptFunction(input, output, name_token);
1663bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1664 const char *oneliner, std::string &output,
const void *name_token) {
1667 return GenerateTypeSynthClass(input, output, name_token);
1670Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
1671 StringList &user_input, std::string &output,
bool has_extra_args,
1673 static uint32_t num_created_functions = 0;
1677 if (user_input.
GetSize() == 0) {
1682 std::string auto_generated_function_name(GenerateUniqueName(
1683 "lldb_autogen_python_bp_callback_func_", num_created_functions));
1685 sstr.
Printf(
"def %s (frame, bp_loc, extra_args, internal_dict):",
1686 auto_generated_function_name.c_str());
1688 sstr.
Printf(
"def %s (frame, bp_loc, internal_dict):",
1689 auto_generated_function_name.c_str());
1691 error = GenerateFunction(sstr.
GetData(), user_input, is_callback);
1692 if (!
error.Success())
1696 output.assign(auto_generated_function_name);
1700bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
1701 StringList &user_input, std::string &output,
bool is_callback) {
1702 static uint32_t num_created_functions = 0;
1706 if (user_input.
GetSize() == 0)
1709 std::string auto_generated_function_name(GenerateUniqueName(
1710 "lldb_autogen_python_wp_callback_func_", num_created_functions));
1711 sstr.
Printf(
"def %s (frame, wp, internal_dict):",
1712 auto_generated_function_name.c_str());
1714 if (!GenerateFunction(sstr.
GetData(), user_input, is_callback).Success())
1718 output.assign(auto_generated_function_name);
1722bool ScriptInterpreterPythonImpl::GetScriptedSummary(
1729 if (!valobj.get()) {
1730 retval.assign(
"<no object>");
1734 void *old_callee =
nullptr;
1736 if (callee_wrapper_sp) {
1737 generic = callee_wrapper_sp->GetAsGeneric();
1739 old_callee =
generic->GetValue();
1741 void *new_callee = old_callee;
1744 if (python_function_name && *python_function_name) {
1746 Locker py_lock(
this, Locker::AcquireLock | Locker::InitSession |
1752 Timer scoped_timer(func_cat,
"LLDBSwigPythonCallTypeScript");
1753 ret_val = SWIGBridge::LLDBSwigPythonCallTypeScript(
1754 python_function_name, GetSessionDictionary().get(), valobj,
1755 &new_callee, options_sp, retval);
1759 retval.assign(
"<no function name>");
1763 if (new_callee && old_callee != new_callee) {
1764 Locker py_lock(
this,
1765 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1766 callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
1767 PythonObject(PyRefType::Borrowed,
static_cast<PyObject *
>(new_callee)));
1773bool ScriptInterpreterPythonImpl::FormatterCallbackFunction(
1774 const char *python_function_name,
TypeImplSP type_impl_sp) {
1775 Locker py_lock(
this,
1776 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1777 return SWIGBridge::LLDBSwigPythonFormatterCallbackFunction(
1778 python_function_name, m_dictionary_name.c_str(), type_impl_sp);
1781bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
1784 CommandDataPython *bp_option_data = (CommandDataPython *)baton;
1785 const char *python_function_name = bp_option_data->script_source.c_str();
1791 Target *target = exe_ctx.GetTargetPtr();
1797 ScriptInterpreterPythonImpl *python_interpreter =
1798 GetPythonInterpreter(debugger);
1800 if (!python_interpreter)
1803 if (python_function_name && python_function_name[0]) {
1804 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
1806 if (breakpoint_sp) {
1808 breakpoint_sp->FindLocationByID(break_loc_id));
1810 if (stop_frame_sp && bp_loc_sp) {
1811 bool ret_val =
true;
1813 Locker py_lock(python_interpreter, Locker::AcquireLock |
1814 Locker::InitSession |
1816 Expected<bool> maybe_ret_val =
1817 SWIGBridge::LLDBSwigPythonBreakpointCallbackFunction(
1818 python_function_name,
1819 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
1820 bp_loc_sp, bp_option_data->m_extra_args);
1822 if (!maybe_ret_val) {
1824 llvm::handleAllErrors(
1825 maybe_ret_val.takeError(),
1826 [&](PythonException &E) {
1827 *debugger.GetAsyncErrorStream() << E.ReadBacktrace();
1829 [&](
const llvm::ErrorInfoBase &E) {
1830 *debugger.GetAsyncErrorStream() << E.message();
1834 ret_val = maybe_ret_val.get();
1846bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
1850 const char *python_function_name = wp_option_data->
script_source.c_str();
1856 Target *target = exe_ctx.GetTargetPtr();
1862 ScriptInterpreterPythonImpl *python_interpreter =
1863 GetPythonInterpreter(debugger);
1865 if (!python_interpreter)
1868 if (python_function_name && python_function_name[0]) {
1869 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
1872 if (stop_frame_sp && wp_sp) {
1873 bool ret_val =
true;
1875 Locker py_lock(python_interpreter, Locker::AcquireLock |
1876 Locker::InitSession |
1878 ret_val = SWIGBridge::LLDBSwigPythonWatchpointCallbackFunction(
1879 python_function_name,
1880 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
1892size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
1894 if (!implementor_sp)
1899 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
1906 Locker py_lock(
this,
1907 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1908 ret_val = SWIGBridge::LLDBSwigPython_CalculateNumChildren(implementor, max);
1916 if (!implementor_sp)
1922 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
1928 Locker py_lock(
this,
1929 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1930 PyObject *child_ptr =
1931 SWIGBridge::LLDBSwigPython_GetChildAtIndex(implementor, idx);
1932 if (child_ptr !=
nullptr && child_ptr != Py_None) {
1934 (
lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
1935 if (sb_value_ptr ==
nullptr)
1936 Py_XDECREF(child_ptr);
1938 ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
1941 Py_XDECREF(child_ptr);
1948llvm::Expected<uint32_t> ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
1950 if (!implementor_sp)
1951 return llvm::createStringError(
"Type has no child named '%s'", child_name);
1955 return llvm::createStringError(
"Type has no child named '%s'", child_name);
1956 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
1958 return llvm::createStringError(
"Type has no child named '%s'", child_name);
1963 Locker py_lock(
this,
1964 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1965 ret_val = SWIGBridge::LLDBSwigPython_GetIndexOfChildWithName(implementor,
1970 return llvm::createStringError(
"Type has no child named '%s'", child_name);
1974bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
1976 bool ret_val =
false;
1978 if (!implementor_sp)
1984 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
1989 Locker py_lock(
this,
1990 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1992 SWIGBridge::LLDBSwigPython_UpdateSynthProviderInstance(implementor);
1998bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2000 bool ret_val =
false;
2002 if (!implementor_sp)
2008 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2013 Locker py_lock(
this,
2014 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2015 ret_val = SWIGBridge::LLDBSwigPython_MightHaveChildrenSynthProviderInstance(
2026 if (!implementor_sp)
2032 auto *implementor =
static_cast<PyObject *
>(
generic->GetValue());
2037 Locker py_lock(
this,
2038 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2039 PyObject *child_ptr =
2040 SWIGBridge::LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2041 if (child_ptr !=
nullptr && child_ptr != Py_None) {
2043 (
lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2044 if (sb_value_ptr ==
nullptr)
2045 Py_XDECREF(child_ptr);
2047 ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
2050 Py_XDECREF(child_ptr);
2057ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2059 Locker py_lock(
this,
2060 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2062 if (!implementor_sp)
2069 PythonObject implementor(PyRefType::Borrowed,
2070 (PyObject *)generic->GetValue());
2071 if (!implementor.IsAllocated())
2074 llvm::Expected<PythonObject> expected_py_return =
2075 implementor.CallMethod(
"get_type_name");
2077 if (!expected_py_return) {
2078 llvm::consumeError(expected_py_return.takeError());
2082 PythonObject py_return = std::move(expected_py_return.get());
2083 if (!py_return.IsAllocated() || !PythonString::Check(py_return.get()))
2086 PythonString type_name(PyRefType::Borrowed, py_return.get());
2090bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2091 const char *impl_function,
Process *process, std::string &output,
2098 if (!impl_function || !impl_function[0]) {
2104 Locker py_lock(
this,
2105 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2106 ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordProcess(
2107 impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
2115bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2116 const char *impl_function,
Thread *thread, std::string &output,
2122 if (!impl_function || !impl_function[0]) {
2127 Locker py_lock(
this,
2128 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2129 if (std::optional<std::string> result =
2130 SWIGBridge::LLDBSWIGPythonRunScriptKeywordThread(
2131 impl_function, m_dictionary_name.c_str(),
2132 thread->shared_from_this())) {
2133 output = std::move(*result);
2140bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2141 const char *impl_function,
Target *target, std::string &output,
2148 if (!impl_function || !impl_function[0]) {
2154 TargetSP target_sp(target->shared_from_this());
2155 Locker py_lock(
this,
2156 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2157 ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordTarget(
2158 impl_function, m_dictionary_name.c_str(), target_sp, output);
2165bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2166 const char *impl_function,
StackFrame *frame, std::string &output,
2172 if (!impl_function || !impl_function[0]) {
2177 Locker py_lock(
this,
2178 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2179 if (std::optional<std::string> result =
2180 SWIGBridge::LLDBSWIGPythonRunScriptKeywordFrame(
2181 impl_function, m_dictionary_name.c_str(),
2182 frame->shared_from_this())) {
2183 output = std::move(*result);
2190bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2191 const char *impl_function,
ValueObject *value, std::string &output,
2198 if (!impl_function || !impl_function[0]) {
2204 Locker py_lock(
this,
2205 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2206 ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordValue(
2207 impl_function, m_dictionary_name.c_str(), value->
GetSP(), output);
2214uint64_t replace_all(std::string &str,
const std::string &oldStr,
2215 const std::string &newStr) {
2217 uint64_t matches = 0;
2218 while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2220 str.replace(pos, oldStr.length(), newStr);
2221 pos += newStr.length();
2226bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2230 namespace fs = llvm::sys::fs;
2231 namespace path = llvm::sys::path;
2237 if (!pathname || !pathname[0]) {
2242 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2246 if (!io_redirect_or_error) {
2254 Locker py_lock(
this,
2255 Locker::AcquireLock |
2258 Locker::FreeAcquiredLock |
2263 auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2264 if (directory.empty()) {
2265 return llvm::createStringError(
"invalid directory name");
2268 replace_all(directory,
"\\",
"\\\\");
2269 replace_all(directory,
"'",
"\\'");
2273 command_stream.
Printf(
"if not (sys.path.__contains__('%s')):\n "
2274 "sys.path.insert(1,'%s');\n\n",
2275 directory.c_str(), directory.c_str());
2276 bool syspath_retval =
2277 ExecuteMultipleLines(command_stream.
GetData(), exc_options).Success();
2278 if (!syspath_retval)
2279 return llvm::createStringError(
"Python sys.path handling failed");
2281 return llvm::Error::success();
2284 std::string module_name(pathname);
2285 bool possible_package =
false;
2287 if (extra_search_dir) {
2288 if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2297 std::error_code ec = status(module_file.GetPath(), st);
2299 if (ec || st.type() == fs::file_type::status_error ||
2300 st.type() == fs::file_type::type_unknown ||
2301 st.type() == fs::file_type::file_not_found) {
2304 if (strchr(pathname,
'\\') || strchr(pathname,
'/')) {
2310 possible_package =
true;
2311 }
else if (is_directory(st) || is_regular_file(st)) {
2312 if (module_file.GetDirectory().IsEmpty()) {
2314 "invalid directory name '{0}'", pathname);
2318 ExtendSysPath(module_file.GetDirectory().GetCString())) {
2322 module_name = module_file.GetFilename().GetCString();
2325 "no known way to import this module specification");
2331 llvm::StringRef extension = llvm::sys::path::extension(module_name);
2332 if (!extension.empty()) {
2333 if (extension ==
".py")
2334 module_name.resize(module_name.length() - 3);
2335 else if (extension ==
".pyc")
2336 module_name.resize(module_name.length() - 4);
2339 if (!possible_package && module_name.find(
'.') != llvm::StringRef::npos) {
2341 "Python does not allow dots in module names: %s", module_name.c_str());
2345 if (module_name.find(
'-') != llvm::StringRef::npos) {
2347 "Python discourages dashes in module names: %s", module_name.c_str());
2353 command_stream.
Clear();
2354 command_stream.
Printf(
"sys.modules.__contains__('%s')", module_name.c_str());
2355 bool does_contain =
false;
2358 const bool does_contain_executed = ExecuteOneLineWithReturn(
2360 ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain,
2363 const bool was_imported_globally = does_contain_executed && does_contain;
2364 const bool was_imported_locally =
2365 GetSessionDictionary()
2366 .GetItemForKey(PythonString(module_name))
2370 command_stream.
Clear();
2372 if (was_imported_globally || was_imported_locally) {
2373 if (!was_imported_locally)
2374 command_stream.
Printf(
"import %s ; reload_module(%s)",
2375 module_name.c_str(), module_name.c_str());
2377 command_stream.
Printf(
"reload_module(%s)", module_name.c_str());
2379 command_stream.
Printf(
"import %s", module_name.c_str());
2381 error = ExecuteMultipleLines(command_stream.
GetData(), exc_options);
2387 if (!SWIGBridge::LLDBSwigPythonCallModuleInit(
2388 module_name.c_str(), m_dictionary_name.c_str(),
2389 m_debugger.shared_from_this())) {
2396 command_stream.
Clear();
2397 command_stream.
Printf(
"%s", module_name.c_str());
2398 void *module_pyobj =
nullptr;
2399 if (ExecuteOneLineWithReturn(
2404 *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2405 PyRefType::Owned,
static_cast<PyObject *
>(module_pyobj)));
2411 return SWIGBridge::LLDBSwigPythonCallModuleNewTarget(
2412 module_name.c_str(), m_dictionary_name.c_str(), target_sp);
2417bool ScriptInterpreterPythonImpl::IsReservedWord(
const char *word) {
2418 if (!word || !word[0])
2421 llvm::StringRef word_sr(word);
2425 if (word_sr.find(
'"') != llvm::StringRef::npos ||
2426 word_sr.find(
'\'') != llvm::StringRef::npos)
2430 command_stream.
Printf(
"keyword.iskeyword('%s')", word);
2436 if (ExecuteOneLineWithReturn(command_stream.
GetData(),
2443ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2445 : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2446 m_old_asynch(debugger_sp->GetAsyncExecution()) {
2448 m_debugger_sp->SetAsyncExecution(
false);
2450 m_debugger_sp->SetAsyncExecution(
true);
2453ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
2455 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2458bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2459 const char *impl_function, llvm::StringRef args,
2460 ScriptedCommandSynchronicity synchronicity,
2463 if (!impl_function) {
2471 if (!debugger_sp.get()) {
2476 bool ret_val =
false;
2479 Locker py_lock(
this,
2480 Locker::AcquireLock | Locker::InitSession |
2482 Locker::FreeLock | Locker::TearDownSession);
2484 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2486 std::string args_str = args.str();
2487 ret_val = SWIGBridge::LLDBSwigPythonCallCommand(
2488 impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2489 cmd_retobj, exe_ctx_ref_sp);
2501bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2503 ScriptedCommandSynchronicity synchronicity,
2506 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2514 if (!debugger_sp.get()) {
2519 bool ret_val =
false;
2522 Locker py_lock(
this,
2523 Locker::AcquireLock | Locker::InitSession |
2525 Locker::FreeLock | Locker::TearDownSession);
2527 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2529 std::string args_str = args.str();
2530 ret_val = SWIGBridge::LLDBSwigPythonCallCommandObject(
2531 static_cast<PyObject *
>(impl_obj_sp->GetValue()), debugger_sp,
2532 args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
2544bool ScriptInterpreterPythonImpl::RunScriptBasedParsedCommand(
2546 ScriptedCommandSynchronicity synchronicity,
2549 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2557 if (!debugger_sp.get()) {
2562 bool ret_val =
false;
2565 Locker py_lock(
this,
2566 Locker::AcquireLock | Locker::InitSession |
2568 Locker::FreeLock | Locker::TearDownSession);
2570 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2575 args_arr_sp->AddStringItem(entry.ref());
2579 ret_val = SWIGBridge::LLDBSwigPythonCallParsedCommandObject(
2580 static_cast<PyObject *
>(impl_obj_sp->GetValue()), debugger_sp,
2581 args_impl, cmd_retobj, exe_ctx_ref_sp);
2593std::optional<std::string>
2594ScriptInterpreterPythonImpl::GetRepeatCommandForScriptedCommand(
2596 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2597 return std::nullopt;
2601 if (!debugger_sp.get())
2602 return std::nullopt;
2604 std::optional<std::string> ret_val;
2607 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN,
2613 std::string command;
2614 args.GetQuotedCommandString(command);
2615 ret_val = SWIGBridge::LLDBSwigPythonGetRepeatCommandForScriptedCommand(
2616 static_cast<PyObject *
>(impl_obj_sp->GetValue()), command);
2622ScriptInterpreterPythonImpl::HandleArgumentCompletionForScriptedCommand(
2624 size_t args_pos,
size_t char_in_arg) {
2626 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2627 return completion_dict_sp;
2630 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN,
2633 completion_dict_sp =
2634 SWIGBridge::LLDBSwigPythonHandleArgumentCompletionForScriptedCommand(
2635 static_cast<PyObject *
>(impl_obj_sp->GetValue()), args, args_pos,
2638 return completion_dict_sp;
2642ScriptInterpreterPythonImpl::HandleOptionArgumentCompletionForScriptedCommand(
2644 size_t char_in_arg) {
2646 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2647 return completion_dict_sp;
2650 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN,
2653 completion_dict_sp = SWIGBridge::
2654 LLDBSwigPythonHandleOptionArgumentCompletionForScriptedCommand(
2655 static_cast<PyObject *
>(impl_obj_sp->GetValue()), long_option,
2658 return completion_dict_sp;
2664bool ScriptInterpreterPythonImpl::GetDocumentationForItem(
const char *item,
2665 std::string &dest) {
2668 if (!item || !*item)
2671 std::string command(item);
2672 command +=
".__doc__";
2676 char *result_ptr =
nullptr;
2678 if (ExecuteOneLineWithReturn(
2682 dest.assign(result_ptr);
2687 str_stream <<
"Function " << item
2688 <<
" was not found. Containing module might be missing.";
2689 dest = std::string(str_stream.
GetString());
2694bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
2698 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2703 PythonObject implementor(PyRefType::Borrowed,
2704 (PyObject *)cmd_obj_sp->GetValue());
2706 if (!implementor.IsAllocated())
2709 llvm::Expected<PythonObject> expected_py_return =
2710 implementor.CallMethod(
"get_short_help");
2712 if (!expected_py_return) {
2713 llvm::consumeError(expected_py_return.takeError());
2717 PythonObject py_return = std::move(expected_py_return.get());
2719 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2720 PythonString py_string(PyRefType::Borrowed, py_return.get());
2721 llvm::StringRef return_data(py_string.GetString());
2722 dest.assign(return_data.data(), return_data.size());
2729uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
2731 uint32_t result = 0;
2733 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2735 static char callee_name[] =
"get_flags";
2740 PythonObject implementor(PyRefType::Borrowed,
2741 (PyObject *)cmd_obj_sp->GetValue());
2743 if (!implementor.IsAllocated())
2746 PythonObject pmeth(PyRefType::Owned,
2747 PyObject_GetAttrString(implementor.get(), callee_name));
2749 if (PyErr_Occurred())
2752 if (!pmeth.IsAllocated())
2755 if (PyCallable_Check(pmeth.get()) == 0) {
2756 if (PyErr_Occurred())
2761 if (PyErr_Occurred())
2764 long long py_return = unwrapOrSetPythonException(
2765 As<long long>(implementor.CallMethod(callee_name)));
2768 if (PyErr_Occurred()) {
2779ScriptInterpreterPythonImpl::GetOptionsForCommandObject(
2783 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2785 static char callee_name[] =
"get_options_definition";
2790 PythonObject implementor(PyRefType::Borrowed,
2791 (PyObject *)cmd_obj_sp->GetValue());
2793 if (!implementor.IsAllocated())
2796 PythonObject pmeth(PyRefType::Owned,
2797 PyObject_GetAttrString(implementor.get(), callee_name));
2799 if (PyErr_Occurred())
2802 if (!pmeth.IsAllocated())
2805 if (PyCallable_Check(pmeth.get()) == 0) {
2806 if (PyErr_Occurred())
2811 if (PyErr_Occurred())
2814 PythonDictionary py_return = unwrapOrSetPythonException(
2815 As<PythonDictionary>(implementor.CallMethod(callee_name)));
2818 if (PyErr_Occurred()) {
2823 return py_return.CreateStructuredObject();
2827ScriptInterpreterPythonImpl::GetArgumentsForCommandObject(
2831 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2833 static char callee_name[] =
"get_args_definition";
2838 PythonObject implementor(PyRefType::Borrowed,
2839 (PyObject *)cmd_obj_sp->GetValue());
2841 if (!implementor.IsAllocated())
2844 PythonObject pmeth(PyRefType::Owned,
2845 PyObject_GetAttrString(implementor.get(), callee_name));
2847 if (PyErr_Occurred())
2850 if (!pmeth.IsAllocated())
2853 if (PyCallable_Check(pmeth.get()) == 0) {
2854 if (PyErr_Occurred())
2859 if (PyErr_Occurred())
2862 PythonList py_return = unwrapOrSetPythonException(
2863 As<PythonList>(implementor.CallMethod(callee_name)));
2866 if (PyErr_Occurred()) {
2871 return py_return.CreateStructuredObject();
2874void ScriptInterpreterPythonImpl::OptionParsingStartedForCommandObject(
2877 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2879 static char callee_name[] =
"option_parsing_started";
2884 PythonObject implementor(PyRefType::Borrowed,
2885 (PyObject *)cmd_obj_sp->GetValue());
2887 if (!implementor.IsAllocated())
2890 PythonObject pmeth(PyRefType::Owned,
2891 PyObject_GetAttrString(implementor.get(), callee_name));
2893 if (PyErr_Occurred())
2896 if (!pmeth.IsAllocated())
2899 if (PyCallable_Check(pmeth.get()) == 0) {
2900 if (PyErr_Occurred())
2905 if (PyErr_Occurred())
2910 unwrapOrSetPythonException(As<bool>(implementor.CallMethod(callee_name)));
2913 if (PyErr_Occurred()) {
2920bool ScriptInterpreterPythonImpl::SetOptionValueForCommandObject(
2922 llvm::StringRef long_option, llvm::StringRef value) {
2925 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2927 static char callee_name[] =
"set_option_value";
2932 PythonObject implementor(PyRefType::Borrowed,
2933 (PyObject *)cmd_obj_sp->GetValue());
2935 if (!implementor.IsAllocated())
2938 PythonObject pmeth(PyRefType::Owned,
2939 PyObject_GetAttrString(implementor.get(), callee_name));
2941 if (PyErr_Occurred())
2944 if (!pmeth.IsAllocated())
2947 if (PyCallable_Check(pmeth.get()) == 0) {
2948 if (PyErr_Occurred())
2953 if (PyErr_Occurred())
2958 exe_ctx_ref_sp = std::make_shared<ExecutionContextRef>(exe_ctx);
2959 PythonObject ctx_ref_obj = SWIGBridge::ToSWIGWrapper(exe_ctx_ref_sp);
2961 bool py_return = unwrapOrSetPythonException(As<bool>(
2962 implementor.CallMethod(callee_name, ctx_ref_obj,
2963 long_option.str().c_str(), value.str().c_str())));
2966 if (PyErr_Occurred()) {
2974bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
2978 Locker py_lock(
this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2983 PythonObject implementor(PyRefType::Borrowed,
2984 (PyObject *)cmd_obj_sp->GetValue());
2986 if (!implementor.IsAllocated())
2989 llvm::Expected<PythonObject> expected_py_return =
2990 implementor.CallMethod(
"get_long_help");
2992 if (!expected_py_return) {
2993 llvm::consumeError(expected_py_return.takeError());
2997 PythonObject py_return = std::move(expected_py_return.get());
2999 bool got_string =
false;
3000 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3001 PythonString str(PyRefType::Borrowed, py_return.get());
3002 llvm::StringRef str_data(str.GetString());
3003 dest.assign(str_data.data(), str_data.size());
3010std::unique_ptr<ScriptInterpreterLocker>
3011ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3012 std::unique_ptr<ScriptInterpreterLocker> py_lock(
new Locker(
3013 this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3014 Locker::FreeLock | Locker::TearDownSession));
3018void ScriptInterpreterPythonImpl::Initialize() {
3025 InitializePythonRAII initialize_guard;
3032 RunSimpleString(
"import sys");
3033 AddToSysPath(AddLocation::End,
".");
3039 if (
FileSpec file_spec = GetPythonDir())
3040 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(
false));
3041 if (
FileSpec file_spec = HostInfo::GetShlibDir())
3042 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(
false));
3044 RunSimpleString(
"sys.dont_write_bytecode = 1; import "
3045 "lldb.embedded_interpreter; from "
3046 "lldb.embedded_interpreter import run_python_interpreter; "
3047 "from lldb.embedded_interpreter import run_one_line");
3049#if LLDB_USE_PYTHON_SET_INTERRUPT
3053 RestoreSignalHandlerScope save_sigint(SIGINT);
3059 RunSimpleString(
"def lldb_setup_sigint_handler():\n"
3061 " def signal_handler(sig, frame):\n"
3062 " raise KeyboardInterrupt()\n"
3063 " signal.signal(signal.SIGINT, signal_handler);\n"
3064 "lldb_setup_sigint_handler();\n"
3065 "del lldb_setup_sigint_handler\n");
3069void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3071 std::string statement;
3072 if (location == AddLocation::Beginning) {
3073 statement.assign(
"sys.path.insert(0,\"");
3074 statement.append(path);
3075 statement.append(
"\")");
3077 statement.assign(
"sys.path.append(\"");
3078 statement.append(path);
3079 statement.append(
"\")");
3081 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