LLDB mainline
ScriptInterpreterPython.cpp
Go to the documentation of this file.
1//===-- ScriptInterpreterPython.cpp ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "lldb-python.h"
10
12#include "PythonDataObjects.h"
13#include "PythonReadline.h"
14#include "SWIGPythonBridge.h"
16
17#include "lldb/API/SBError.h"
19#include "lldb/API/SBFrame.h"
20#include "lldb/API/SBValue.h"
23#include "lldb/Core/Debugger.h"
27#include "lldb/Host/Config.h"
29#include "lldb/Host/HostInfo.h"
30#include "lldb/Host/Pipe.h"
34#include "lldb/Target/Thread.h"
38#include "lldb/Utility/Timer.h"
41#include "lldb/lldb-forward.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/StringRef.h"
44#include "llvm/Support/Error.h"
45#include "llvm/Support/ErrorExtras.h"
46#include "llvm/Support/FileSystem.h"
47#include "llvm/Support/FormatAdapters.h"
48
49#include <cstdio>
50#include <cstdlib>
51#include <memory>
52#include <optional>
53#include <stdlib.h>
54#include <string>
55
56using namespace lldb;
57using namespace lldb_private;
58using namespace lldb_private::python;
59using llvm::Expected;
60
62
63// Defined in the SWIG source file
64extern "C" PyObject *PyInit__lldb(void);
65
66#define LLDBSwigPyInit PyInit__lldb
67
68#if defined(_WIN32)
69// Don't mess with the signal handlers on Windows.
70#define LLDB_USE_PYTHON_SET_INTERRUPT 0
71#else
72#define LLDB_USE_PYTHON_SET_INTERRUPT 1
73#endif
74
76 ScriptInterpreter *script_interpreter =
78 return static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
79}
80
81namespace {
82
83// Initializing Python is not a straightforward process. We cannot control
84// what external code may have done before getting to this point in LLDB,
85// including potentially having already initialized Python, so we need to do a
86// lot of work to ensure that the existing state of the system is maintained
87// across our initialization. We do this by using an RAII pattern where we
88// save off initial state at the beginning, and restore it at the end
89struct InitializePythonRAII {
90public:
91 InitializePythonRAII() {
92 // The table of built-in modules can only be extended before Python is
93 // initialized.
94 if (!Py_IsInitialized()) {
95#ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
96 // Python's readline is incompatible with libedit being linked into lldb.
97 // Provide a patched version local to the embedded interpreter.
98 PyImport_AppendInittab("readline", initlldb_readline);
99#endif
100
101 // Register _lldb as a built-in module.
102 PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
103 }
104
105#if LLDB_EMBED_PYTHON_HOME
106 PyConfig config;
107 PyConfig_InitPythonConfig(&config);
108
109 static std::string g_python_home = []() -> std::string {
110 if (llvm::sys::path::is_absolute(LLDB_PYTHON_HOME))
111 return LLDB_PYTHON_HOME;
112
113 FileSpec spec = HostInfo::GetShlibDir();
114 if (!spec)
115 return {};
116 spec.AppendPathComponent(LLDB_PYTHON_HOME);
117 return spec.GetPath();
118 }();
119 if (!g_python_home.empty()) {
120 PyConfig_SetBytesString(&config, &config.home, g_python_home.c_str());
121 }
122
123 config.install_signal_handlers = 0;
124 Py_InitializeFromConfig(&config);
125 PyConfig_Clear(&config);
126#else
127 Py_InitializeEx(/*install_sigs=*/0);
128#endif
129
130 // The only case we should go further and acquire the GIL: it is unlocked.
131 PyGILState_STATE gil_state = PyGILState_Ensure();
132 if (gil_state != PyGILState_UNLOCKED)
133 return;
134
135 m_was_already_initialized = true;
136 m_gil_state = gil_state;
138 GetLog(LLDBLog::Script), "Ensured PyGILState. Previous state = {0}",
139 m_gil_state == PyGILState_UNLOCKED ? "unlocked" : "locked");
140 }
141
142 ~InitializePythonRAII() {
143 if (m_was_already_initialized) {
144 LLDB_LOG_VERBOSE(GetLog(LLDBLog::Script),
145 "Releasing PyGILState. Returning to state = {0}",
146 m_gil_state == PyGILState_UNLOCKED ? "unlocked"
147 : "locked");
148 PyGILState_Release(m_gil_state);
149 } else {
150 // We initialized the threads in this function, just unlock the GIL.
151 PyEval_SaveThread();
152 }
153 }
154
155private:
156 PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
157 bool m_was_already_initialized = false;
158};
159
160#if LLDB_USE_PYTHON_SET_INTERRUPT
161/// Saves the current signal handler for the specified signal and restores
162/// it at the end of the current scope.
163struct RestoreSignalHandlerScope {
164 /// The signal handler.
165 struct sigaction m_prev_handler;
166 int m_signal_code;
167 RestoreSignalHandlerScope(int signal_code) : m_signal_code(signal_code) {
168 // Initialize sigaction to their default state.
169 std::memset(&m_prev_handler, 0, sizeof(m_prev_handler));
170 // Don't install a new handler, just read back the old one.
171 struct sigaction *new_handler = nullptr;
172 int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler);
173 lldbassert(signal_err == 0 && "sigaction failed to read handler");
174 }
175 ~RestoreSignalHandlerScope() {
176 int signal_err = ::sigaction(m_signal_code, &m_prev_handler, nullptr);
177 lldbassert(signal_err == 0 && "sigaction failed to restore old handler");
178 }
179};
180#endif
181} // namespace
182
185 auto style = llvm::sys::path::Style::posix;
186
187 llvm::StringRef path_ref(path.begin(), path.size());
188 auto rbegin = llvm::sys::path::rbegin(path_ref, style);
189 auto rend = llvm::sys::path::rend(path_ref);
190 auto framework = std::find(rbegin, rend, "LLDB.framework");
191 if (framework == rend) {
192 ComputePythonDir(path);
193 return;
194 }
195 path.resize(framework - rend);
196 llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
197}
198
201 // Build the path by backing out of the lib dir, then building with whatever
202 // the real python interpreter uses. (e.g. lib for most, lib64 on RHEL
203 // x86_64, or bin on Windows).
204 llvm::sys::path::remove_filename(path);
205 llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
206
207#if defined(_WIN32)
208 // This will be injected directly through FileSpec.SetDirectory(),
209 // so we need to normalize manually.
210 std::replace(path.begin(), path.end(), '\\', '/');
211#endif
212}
213
215 static FileSpec g_spec = []() {
216 FileSpec spec = HostInfo::GetShlibDir();
217 if (!spec)
218 return FileSpec();
219 llvm::SmallString<64> path;
220 spec.GetPath(path);
221
222#if defined(__APPLE__)
224#else
225 ComputePythonDir(path);
226#endif
227 spec.SetDirectory(path);
228 return spec;
229 }();
230 return g_spec;
231}
232
233static const char GetInterpreterInfoScript[] = R"(
234import os
235import sys
236
237def main(lldb_python_dir, python_exe_relative_path):
238 info = {
239 "lldb-pythonpath": lldb_python_dir,
240 "language": "python",
241 "prefix": sys.prefix,
242 "executable": os.path.join(sys.prefix, python_exe_relative_path)
243 }
244 return info
245)";
246
247static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH;
248
250 GIL gil;
251 FileSpec python_dir_spec = GetPythonDir();
252 if (!python_dir_spec)
253 return nullptr;
255 auto info_json = unwrapIgnoringErrors(
256 As<PythonDictionary>(get_info(PythonString(python_dir_spec.GetPath()),
258 if (!info_json)
259 return nullptr;
260 return info_json.CreateStructuredDictionary();
261}
262
264 FileSpec &this_file) {
265 // When we're loaded from python, this_file will point to the file inside the
266 // python package directory. Replace it with the one in the lib directory.
267#ifdef _WIN32
268 // On windows, we need to manually back out of the python tree, and go into
269 // the bin directory. This is pretty much the inverse of what ComputePythonDir
270 // does.
271 if (this_file.GetFileNameExtension() == ".pyd") {
272 this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd
273 this_file.RemoveLastPathComponent(); // native
274 this_file.RemoveLastPathComponent(); // lldb
275 llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
276 for (auto it = llvm::sys::path::begin(libdir),
277 end = llvm::sys::path::end(libdir);
278 it != end; ++it)
279 this_file.RemoveLastPathComponent();
280 this_file.AppendPathComponent("bin");
281 this_file.AppendPathComponent("liblldb.dll");
282 }
283#else
284 // The python file is a symlink, so we can find the real library by resolving
285 // it. We can do this unconditionally.
286 FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
287#endif
288}
289
291 return "Embedded Python interpreter";
292}
293
295#if LLDB_ENABLE_MTE
296 // Python's allocator (pymalloc) is not aware of Memory Tagging Extension
297 // (MTE) and crashes.
298 // https://bugs.python.org/issue43593
299 setenv("PYTHONMALLOC", "malloc", /*overwrite=*/true);
300#endif
301
302 // When the plugin is a separate shared library, the SWIG wrapper lives in
303 // the plugin library, so the path helper that redirects lookups back to
304 // liblldb is unnecessary.
305#if !LLDB_ENABLE_DYNAMIC_SCRIPTINTERPRETERS
306 HostInfo::SetSharedLibraryDirectoryHelper(
308#endif
315}
316
321
323 ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
324 uint16_t on_leave, FileSP in, FileSP out, FileSP err)
327 m_python_interpreter(py_interpreter) {
329 if ((on_entry & InitSession) == InitSession) {
330 if (!DoInitSession(on_entry, in, out, err)) {
331 // Don't teardown the session if we didn't init it.
332 m_teardown_session = false;
333 }
334 }
335}
336
338 m_GILState = PyGILState_Ensure();
340 "Ensured PyGILState. Previous state = {0}",
341 m_GILState == PyGILState_UNLOCKED ? "unlocked" : "locked");
342
343 // we need to save the thread state when we first start the command because
344 // we might decide to interrupt it while some action is taking place outside
345 // of Python (e.g. printing to screen, waiting for the network, ...) in that
346 // case, _PyThreadState_Current will be NULL - and we would be unable to set
347 // the asynchronous exception - not a desirable situation
348 m_python_interpreter->SetThreadState(PyThreadState_Get());
349 m_python_interpreter->IncrementLockCount();
350 return true;
351}
352
354 FileSP in, FileSP out,
355 FileSP err) {
357 return false;
358 return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
359}
360
363 "Releasing PyGILState. Returning to state = {0}",
364 m_GILState == PyGILState_UNLOCKED ? "unlocked" : "locked");
365 PyGILState_Release(m_GILState);
366 m_python_interpreter->DecrementLockCount();
367 return true;
368}
369
372 return false;
373 m_python_interpreter->LeaveSession();
374 return true;
375}
376
382
389 m_dictionary_name(m_debugger.GetInstanceName()),
392 m_command_thread_state(nullptr) {
393
394 m_dictionary_name.append("_dict");
395 StreamString run_string;
396 run_string.Printf("%s = dict()", m_dictionary_name.c_str());
397
399 RunSimpleString(run_string.GetData());
400
401 run_string.Clear();
402 run_string.Printf(
403 "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
404 m_dictionary_name.c_str());
405 RunSimpleString(run_string.GetData());
406
407 // Reloading modules requires a different syntax in Python 2 and Python 3.
408 // This provides a consistent syntax no matter what version of Python.
409 run_string.Clear();
410 run_string.Printf(
411 "run_one_line (%s, 'from importlib import reload as reload_module')",
412 m_dictionary_name.c_str());
413 RunSimpleString(run_string.GetData());
414
415 // WARNING: temporary code that loads Cocoa formatters - this should be done
416 // on a per-platform basis rather than loading the whole set and letting the
417 // individual formatter classes exploit APIs to check whether they can/cannot
418 // do their task
419 run_string.Clear();
420 run_string.Printf(
421 "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp')",
422 m_dictionary_name.c_str());
423 RunSimpleString(run_string.GetData());
424 run_string.Clear();
425
426 run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
427 "lldb.embedded_interpreter import run_python_interpreter; "
428 "from lldb.embedded_interpreter import run_one_line')",
429 m_dictionary_name.c_str());
430 RunSimpleString(run_string.GetData());
431 run_string.Clear();
432
433 // Configure pydoc (built-in module) to use the "plain" pager. The default one
434 // doesn't play nice with the statusline.
435 run_string.Printf("run_one_line (%s, 'import pydoc; pydoc.pager = "
436 "pydoc.plainpager')",
437 m_dictionary_name.c_str());
438 RunSimpleString(run_string.GetData());
439 run_string.Clear();
440
441 run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
442 "')",
443 m_dictionary_name.c_str(), m_debugger.GetID());
444 RunSimpleString(run_string.GetData());
445}
446
448 // the session dictionary may hold objects with complex state which means
449 // that they may need to be torn down with some level of smarts and that, in
450 // turn, requires a valid thread state force Python to procure itself such a
451 // thread state, nuke the session dictionary and then release it for others
452 // to use and proceed with the rest of the shutdown
453 auto gil_state = PyGILState_Ensure();
454 m_session_dict.Reset();
455 PyGILState_Release(gil_state);
456}
457
459 bool interactive) {
460 const char *instructions = nullptr;
461
462 switch (m_active_io_handler) {
463 case eIOHandlerNone:
464 break;
466 instructions = R"(Enter your Python command(s). Type 'DONE' to end.
467def function (frame, bp_loc, internal_dict):
468 """frame: the lldb.SBFrame for the location at which you stopped
469 bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
470 internal_dict: an LLDB support object not to be used"""
471)";
472 break;
474 instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
475 break;
476 }
477
478 if (instructions && interactive) {
479 if (LockableStreamFileSP stream_sp = io_handler.GetOutputStreamFileSP()) {
480 LockedStreamFile locked_stream = stream_sp->Lock();
481 locked_stream.PutCString(instructions);
482 locked_stream.Flush();
483 }
484 }
485}
486
488 std::string &data) {
489 io_handler.SetIsDone(true);
490 bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
491
492 switch (m_active_io_handler) {
493 case eIOHandlerNone:
494 break;
496 std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
497 (std::vector<std::reference_wrapper<BreakpointOptions>> *)
498 io_handler.GetUserData();
499 for (BreakpointOptions &bp_options : *bp_options_vec) {
500
501 auto data_up = std::make_unique<CommandDataPython>();
502 if (!data_up)
503 break;
504 data_up->user_source.SplitIntoLines(data);
505
506 if (GenerateBreakpointCommandCallbackData(data_up->user_source,
507 data_up->script_source,
508 /*has_extra_args=*/false,
509 /*is_callback=*/false)
510 .Success()) {
511 auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
512 std::move(data_up));
513 bp_options.SetCallback(
515 } else if (!batch_mode) {
516 if (LockableStreamFileSP error_sp = io_handler.GetErrorStreamFileSP()) {
517 LockedStreamFile locked_stream = error_sp->Lock();
518 locked_stream.Printf("Warning: No command attached to breakpoint.\n");
519 }
520 }
521 }
523 } break;
525 WatchpointOptions *wp_options =
526 (WatchpointOptions *)io_handler.GetUserData();
527 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
528 data_up->user_source.SplitIntoLines(data);
529
530 if (GenerateWatchpointCommandCallbackData(data_up->user_source,
531 data_up->script_source,
532 /*is_callback=*/false)) {
533 auto baton_sp =
534 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
535 wp_options->SetCallback(
537 } else if (!batch_mode) {
538 if (LockableStreamFileSP error_sp = io_handler.GetErrorStreamFileSP()) {
539 LockedStreamFile locked_stream = error_sp->Lock();
540 locked_stream.Printf("Warning: No command attached to breakpoint.\n");
541 }
542 }
544 } break;
545 }
546}
547
550 return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
551}
552
554 Log *log = GetLog(LLDBLog::Script);
555 if (log)
556 log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
557
558 // Unset the LLDB global variables.
559 RunSimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
560 "= None; lldb.thread = None; lldb.frame = None");
561
562 // checking that we have a valid thread state - since we use our own
563 // threading and locking in some (rare) cases during cleanup Python may end
564 // up believing we have no thread state and PyImport_AddModule will crash if
565 // that is the case - since that seems to only happen when destroying the
566 // SBDebugger, we can make do without clearing up stdout and stderr
567 if (PyThreadState_GetDict()) {
568 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
569 if (sys_module_dict.IsValid()) {
570 if (m_saved_stdin.IsValid()) {
571 sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
573 }
574 if (m_saved_stdout.IsValid()) {
575 sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
577 }
578 if (m_saved_stderr.IsValid()) {
579 sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
580 m_saved_stderr.Reset();
581 }
582 }
584
585 m_session_is_active = false;
586}
587
589 const char *py_name,
590 PythonObject &save_file,
591 const char *mode) {
592 if (!file_sp || !*file_sp) {
593 save_file.Reset();
594 return false;
595 }
596 File &file = *file_sp;
597
598 // Flush the file before giving it to python to avoid interleaved output.
599 file.Flush();
600
601 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
602
603 auto new_file = PythonFile::FromFile(file, mode);
604 if (!new_file) {
605 LLDB_LOG_ERROR(GetLog(LLDBLog::Script), new_file.takeError(),
606 "ScriptInterpreterPythonImpl::SetStdHandle failed to wrap "
607 "sys.{1}: {0}",
608 py_name);
609 return false;
610 }
611
612 save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
614 sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
615 return true;
616}
617
618bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
619 FileSP in_sp, FileSP out_sp,
620 FileSP err_sp) {
621 // If we have already entered the session, without having officially 'left'
622 // it, then there is no need to 'enter' it again.
623 Log *log = GetLog(LLDBLog::Script);
625 LLDB_LOGF(
626 log,
627 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
628 ") session is already active, returning without doing anything",
629 on_entry_flags);
630 return false;
631 }
632
633 LLDB_LOGF(
634 log,
635 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
636 on_entry_flags);
637
638 m_session_is_active = true;
639
640 StreamString run_string;
641
642 if (on_entry_flags & Locker::InitGlobals) {
643 run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
645 run_string.Printf(
646 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
647 m_debugger.GetID());
648 run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
649 run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
650 run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
651 run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
652 run_string.PutCString("')");
653 } else {
654 // If we aren't initing the globals, we should still always set the
655 // debugger (since that is always unique.)
656 run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
657 m_dictionary_name.c_str(), m_debugger.GetID());
658 run_string.Printf(
659 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
660 m_debugger.GetID());
661 run_string.PutCString("')");
662 }
663
664 RunSimpleString(run_string.GetData());
665 run_string.Clear();
666
667 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
668 if (sys_module_dict.IsValid()) {
669 lldb::FileSP top_in_sp;
670 lldb::LockableStreamFileSP top_out_sp, top_err_sp;
671 if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
672 m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
673 top_err_sp);
674
675 if (on_entry_flags & Locker::NoSTDIN) {
676 m_saved_stdin.Reset();
677 } else {
678 if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
679 if (top_in_sp)
680 SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
681 }
682 }
683
684 if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
685 if (top_out_sp)
686 SetStdHandle(top_out_sp->GetUnlockedFileSP(), "stdout", m_saved_stdout,
687 "w");
688 }
689
690 if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
691 if (top_err_sp)
692 SetStdHandle(top_err_sp->GetUnlockedFileSP(), "stderr", m_saved_stderr,
693 "w");
694 }
695 }
696
697 if (PyErr_Occurred())
698 PyErr_Clear();
699
700 return true;
701}
702
704 if (!m_main_module.IsValid())
706 return m_main_module;
707}
708
711 return m_session_dict;
712
713 PythonObject &main_module = GetMainModule();
714 if (!main_module.IsValid())
715 return m_session_dict;
716
718 PyModule_GetDict(main_module.get()));
719 if (!main_dict.IsValid())
720 return m_session_dict;
721
729 return m_sys_module_dict;
732 return m_sys_module_dict;
733}
734
735llvm::Expected<unsigned>
737 const llvm::StringRef &callable_name) {
738 if (callable_name.empty()) {
739 return llvm::createStringError(llvm::inconvertibleErrorCode(),
740 "called with empty callable name.");
741 }
742 Locker py_lock(this,
747 callable_name, dict);
748 if (!pfunc.IsAllocated()) {
749 return llvm::createStringError(llvm::inconvertibleErrorCode(),
750 "can't find callable: %s",
751 callable_name.str().c_str());
752 }
753 llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
754 if (!arg_info)
755 return arg_info.takeError();
756 return arg_info.get().max_positional_args;
757}
758
759static std::string GenerateUniqueName(const char *base_name_wanted,
760 uint32_t &functions_counter,
761 const void *name_token = nullptr) {
762 StreamString sstr;
763
764 if (!base_name_wanted)
765 return std::string();
766
767 if (!name_token)
768 sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
769 else
770 sstr.Printf("%s_%p", base_name_wanted, name_token);
771
772 return std::string(sstr.GetString());
773}
774
777 return true;
778
780 PyImport_AddModule("lldb.embedded_interpreter"));
781 if (!module.IsValid())
782 return false;
783
785 PyModule_GetDict(module.get()));
786 if (!module_dict.IsValid())
787 return false;
788
790 module_dict.GetItemForKey(PythonString("run_one_line"));
792 module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
793 return m_run_one_line_function.IsValid();
794}
795
797 llvm::StringRef command, CommandReturnObject *result,
798 const ExecuteScriptOptions &options) {
799 std::string command_str = command.str();
800
801 if (!m_valid_session)
802 return false;
803
804 if (!command.empty()) {
805 // We want to call run_one_line, passing in the dictionary and the command
806 // string. We cannot do this through RunSimpleString here because the
807 // command string may contain escaped characters, and putting it inside
808 // another string to pass to RunSimpleString messes up the escaping. So
809 // we use the following more complicated method to pass the command string
810 // directly down to Python.
811 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
812 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
813 options.GetEnableIO(), m_debugger, result);
814 if (!io_redirect_or_error) {
815 if (result)
817 "failed to redirect I/O: {0}\n",
818 llvm::fmt_consume(io_redirect_or_error.takeError()));
819 else
820 llvm::consumeError(io_redirect_or_error.takeError());
821 return false;
822 }
823
824 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
825
826 bool success = false;
827 {
828 // WARNING! It's imperative that this RAII scope be as tight as
829 // possible. In particular, the scope must end *before* we try to join
830 // the read thread. The reason for this is that a pre-requisite for
831 // joining the read thread is that we close the write handle (to break
832 // the pipe and cause it to wake up and exit). But acquiring the GIL as
833 // below will redirect Python's stdio to use this same handle. If we
834 // close the handle while Python is still using it, bad things will
835 // happen.
836 Locker locker(
837 this,
839 (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
840 ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
842 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
843 io_redirect.GetErrorFile());
844
845 // Find the correct script interpreter dictionary in the main module.
846 PythonDictionary &session_dict = GetSessionDictionary();
847 if (session_dict.IsValid()) {
849 if (PyCallable_Check(m_run_one_line_function.get())) {
850 PythonObject pargs(
852 Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
853 if (pargs.IsValid()) {
854 PythonObject return_value(
856 PyObject_CallObject(m_run_one_line_function.get(),
857 pargs.get()));
858 if (return_value.IsValid())
859 success = true;
860 else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
861 PyErr_Print();
862 PyErr_Clear();
863 }
864 }
865 }
866 }
867 }
868
869 io_redirect.Flush();
870 }
871
872 if (success)
873 return true;
874
875 // The one-liner failed. Append the error message.
876 if (result) {
877 result->AppendErrorWithFormat("python failed attempting to evaluate '%s'",
878 command_str.c_str());
879 }
880 return false;
881 }
882
883 if (result)
884 result->AppendError("empty command passed to python\n");
885 return false;
886}
887
890
891 Debugger &debugger = m_debugger;
892
893 // At the moment, the only time the debugger does not have an input file
894 // handle is when this is called directly from Python, in which case it is
895 // both dangerous and unnecessary (not to mention confusing) to try to embed
896 // a running interpreter loop inside the already running Python interpreter
897 // loop, so we won't do it.
898
899 if (!debugger.GetInputFile().IsValid())
900 return;
901
902 IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
903 if (io_handler_sp) {
904 debugger.RunIOHandlerAsync(io_handler_sp);
905 }
906}
907
909#if LLDB_USE_PYTHON_SET_INTERRUPT
910 // If the interpreter isn't evaluating any Python at the moment then return
911 // false to signal that this function didn't handle the interrupt and the
912 // next component should try handling it.
913 if (!IsExecutingPython())
914 return false;
915
916 // Tell Python that it should pretend to have received a SIGINT.
917 PyErr_SetInterrupt();
918 // PyErr_SetInterrupt has no way to return an error so we can only pretend the
919 // signal got successfully handled and return true.
920 // Python 3.10 introduces PyErr_SetInterruptEx that could return an error, but
921 // the error handling is limited to checking the arguments which would be
922 // just our (hardcoded) input signal code SIGINT, so that's not useful at all.
923 return true;
924#else
925 Log *log = GetLog(LLDBLog::Script);
926
927 if (IsExecutingPython()) {
928 PyThreadState *state = PyThreadState_Get();
929 if (!state)
930 state = GetThreadState();
931 if (state) {
932 long tid = PyThread_get_thread_ident();
933 PyThreadState_Swap(state);
934 int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
935 LLDB_LOGF(log,
936 "ScriptInterpreterPythonImpl::Interrupt() sending "
937 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
938 tid, num_threads);
939 return true;
940 }
941 }
942 LLDB_LOGF(log,
943 "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
944 "can't interrupt");
945 return false;
946#endif
947}
948
950 llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
951 void *ret_value, const ExecuteScriptOptions &options) {
952
953 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
954 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
955 options.GetEnableIO(), m_debugger, /*result=*/nullptr);
956
957 if (!io_redirect_or_error) {
958 llvm::consumeError(io_redirect_or_error.takeError());
959 return false;
960 }
961
962 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
963
964 Locker locker(this,
966 (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
969 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
970 io_redirect.GetErrorFile());
971
972 PythonModule &main_module = GetMainModule();
973 PythonDictionary globals = main_module.GetDictionary();
974
976 if (!locals.IsValid())
977 locals = unwrapIgnoringErrors(
979 if (!locals.IsValid())
980 locals = globals;
981
982 Expected<PythonObject> maybe_py_return =
983 runStringOneLine(in_string, globals, locals);
984
985 if (!maybe_py_return) {
986 llvm::handleAllErrors(
987 maybe_py_return.takeError(),
988 [&](PythonException &E) {
989 E.Restore();
990 if (options.GetMaskoutErrors()) {
991 if (E.Matches(PyExc_SyntaxError)) {
992 PyErr_Print();
993 }
994 PyErr_Clear();
995 }
996 },
997 [](const llvm::ErrorInfoBase &E) {});
998 return false;
999 }
1000
1001 PythonObject py_return = std::move(maybe_py_return.get());
1002 assert(py_return.IsValid());
1003
1004 switch (return_type) {
1005 case eScriptReturnTypeCharPtr: // "char *"
1006 {
1007 const char format[3] = "s#";
1008 return PyArg_Parse(py_return.get(), format, (char **)ret_value);
1009 }
1010 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
1011 // Py_None
1012 {
1013 const char format[3] = "z";
1014 return PyArg_Parse(py_return.get(), format, (char **)ret_value);
1015 }
1016 case eScriptReturnTypeBool: {
1017 const char format[2] = "b";
1018 return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
1019 }
1020 case eScriptReturnTypeShortInt: {
1021 const char format[2] = "h";
1022 return PyArg_Parse(py_return.get(), format, (short *)ret_value);
1023 }
1024 case eScriptReturnTypeShortIntUnsigned: {
1025 const char format[2] = "H";
1026 return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
1027 }
1028 case eScriptReturnTypeInt: {
1029 const char format[2] = "i";
1030 return PyArg_Parse(py_return.get(), format, (int *)ret_value);
1031 }
1032 case eScriptReturnTypeIntUnsigned: {
1033 const char format[2] = "I";
1034 return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
1035 }
1036 case eScriptReturnTypeLongInt: {
1037 const char format[2] = "l";
1038 return PyArg_Parse(py_return.get(), format, (long *)ret_value);
1039 }
1040 case eScriptReturnTypeLongIntUnsigned: {
1041 const char format[2] = "k";
1042 return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
1043 }
1044 case eScriptReturnTypeLongLong: {
1045 const char format[2] = "L";
1046 return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
1047 }
1048 case eScriptReturnTypeLongLongUnsigned: {
1049 const char format[2] = "K";
1050 return PyArg_Parse(py_return.get(), format,
1051 (unsigned long long *)ret_value);
1052 }
1053 case eScriptReturnTypeFloat: {
1054 const char format[2] = "f";
1055 return PyArg_Parse(py_return.get(), format, (float *)ret_value);
1056 }
1057 case eScriptReturnTypeDouble: {
1058 const char format[2] = "d";
1059 return PyArg_Parse(py_return.get(), format, (double *)ret_value);
1060 }
1061 case eScriptReturnTypeChar: {
1062 const char format[2] = "c";
1063 return PyArg_Parse(py_return.get(), format, (char *)ret_value);
1064 }
1065 case eScriptReturnTypeOpaqueObject: {
1066 *((PyObject **)ret_value) = py_return.release();
1067 return true;
1069 }
1070 llvm_unreachable("Fully covered switch!");
1071}
1072
1074 const char *in_string, const ExecuteScriptOptions &options) {
1075
1076 if (in_string == nullptr)
1077 return Status();
1078
1079 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1080 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1081 options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1082
1083 if (!io_redirect_or_error)
1084 return Status::FromError(io_redirect_or_error.takeError());
1085
1086 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1087
1088 Locker locker(this,
1090 (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1093 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1094 io_redirect.GetErrorFile());
1095
1096 PythonModule &main_module = GetMainModule();
1097 PythonDictionary globals = main_module.GetDictionary();
1098
1099 PythonDictionary locals = GetSessionDictionary();
1100 if (!locals.IsValid())
1101 locals = unwrapIgnoringErrors(
1103 if (!locals.IsValid())
1104 locals = globals;
1105
1106 Expected<PythonObject> return_value =
1107 runStringMultiLine(in_string, globals, locals);
1108
1109 if (!return_value) {
1110 llvm::Error error =
1111 llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
1112 llvm::Error error = llvm::createStringError(
1113 llvm::inconvertibleErrorCode(), E.ReadBacktrace());
1114 if (!options.GetMaskoutErrors())
1115 E.Restore();
1116 return error;
1117 });
1118 return Status::FromError(std::move(error));
1120
1121 return Status();
1122}
1123
1125 std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1126 CommandReturnObject &result) {
1128 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1129 " ", *this, &bp_options_vec);
1130}
1131
1133 WatchpointOptions *wp_options, CommandReturnObject &result) {
1135 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1136 " ", *this, wp_options);
1137}
1138
1140 BreakpointOptions &bp_options, const char *function_name,
1141 StructuredData::ObjectSP extra_args_sp) {
1142 Status error;
1143 // For now just cons up a oneliner that calls the provided function.
1144 std::string function_signature = function_name;
1145
1146 llvm::Expected<unsigned> maybe_args =
1148 if (!maybe_args) {
1150 "could not get num args: %s",
1151 llvm::toString(maybe_args.takeError()).c_str());
1152 return error;
1153 }
1154 size_t max_args = *maybe_args;
1155
1156 bool uses_extra_args = false;
1157 if (max_args >= 4) {
1158 uses_extra_args = true;
1159 function_signature += "(frame, bp_loc, extra_args, internal_dict)";
1160 } else if (max_args >= 3) {
1161 if (extra_args_sp) {
1163 "cannot pass extra_args to a three argument callback");
1164 return error;
1165 }
1166 uses_extra_args = false;
1167 function_signature += "(frame, bp_loc, internal_dict)";
1168 } else {
1169 error = Status::FromErrorStringWithFormat("expected 3 or 4 argument "
1170 "function, %s can only take %zu",
1171 function_name, max_args);
1172 return error;
1173 }
1174
1175 SetBreakpointCommandCallback(bp_options, function_signature.c_str(),
1176 extra_args_sp, uses_extra_args,
1177 /*is_callback=*/true);
1178 return error;
1179}
1180
1182 BreakpointOptions &bp_options,
1183 std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
1184 Status error;
1185 error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1186 cmd_data_up->script_source,
1187 /*has_extra_args=*/false,
1188 /*is_callback=*/false);
1189 if (error.Fail()) {
1190 return error;
1191 }
1192 auto baton_sp =
1193 std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1200 BreakpointOptions &bp_options, const char *command_body_text,
1201 bool is_callback) {
1202 return SetBreakpointCommandCallback(bp_options, command_body_text, {},
1203 /*uses_extra_args=*/false, is_callback);
1204}
1205
1206// Set a Python one-liner as the callback for the breakpoint.
1208 BreakpointOptions &bp_options, const char *command_body_text,
1209 StructuredData::ObjectSP extra_args_sp, bool uses_extra_args,
1210 bool is_callback) {
1211 auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1212 // Split the command_body_text into lines, and pass that to
1213 // GenerateBreakpointCommandCallbackData. That will wrap the body in an
1214 // auto-generated function, and return the function name in script_source.
1215 // That is what the callback will actually invoke.
1216
1217 data_up->user_source.SplitIntoLines(command_body_text);
1219 data_up->user_source, data_up->script_source, uses_extra_args,
1220 is_callback);
1221 if (error.Success()) {
1222 auto baton_sp =
1223 std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1224 bp_options.SetCallback(
1226 return error;
1228 return error;
1229}
1230
1231// Set a Python one-liner as the callback for the watchpoint.
1233 WatchpointOptions *wp_options, const char *user_input, bool is_callback) {
1234 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
1235
1236 // It's necessary to set both user_source and script_source to the oneliner.
1237 // The former is used to generate callback description (as in watchpoint
1238 // command list) while the latter is used for Python to interpret during the
1239 // actual callback.
1240
1241 data_up->user_source.AppendString(user_input);
1242 data_up->script_source.assign(user_input);
1243
1245 data_up->user_source, data_up->script_source, is_callback)) {
1246 auto baton_sp =
1247 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
1248 wp_options->SetCallback(
1250 }
1251}
1252
1254 StringList &function_def) {
1255 // Convert StringList to one long, newline delimited, const char *.
1256 std::string function_def_string(function_def.CopyList());
1257 LLDB_LOG(GetLog(LLDBLog::Script), "Added Function:\n{0}\n",
1258 function_def_string.c_str());
1259
1261 function_def_string.c_str(), ExecuteScriptOptions().SetEnableIO(false));
1262 return error;
1263}
1264
1266 const StringList &input,
1267 bool is_callback) {
1268 Status error;
1269 int num_lines = input.GetSize();
1270 if (num_lines == 0) {
1271 error = Status::FromErrorString("No input data.");
1272 return error;
1273 }
1274
1275 if (!signature || *signature == 0) {
1276 error = Status::FromErrorString("No output function name.");
1277 return error;
1278 }
1279
1280 StreamString sstr;
1281 StringList auto_generated_function;
1282 auto_generated_function.AppendString(signature);
1283 auto_generated_function.AppendString(
1284 " global_dict = globals()"); // Grab the global dictionary
1285 auto_generated_function.AppendString(
1286 " new_keys = internal_dict.keys()"); // Make a list of keys in the
1287 // session dict
1288 auto_generated_function.AppendString(
1289 " old_keys = global_dict.keys()"); // Save list of keys in global dict
1290 auto_generated_function.AppendString(
1291 " global_dict.update(internal_dict)"); // Add the session dictionary
1292 // to the global dictionary.
1293
1294 if (is_callback) {
1295 // If the user input is a callback to a python function, make sure the input
1296 // is only 1 line, otherwise appending the user input would break the
1297 // generated wrapped function
1298 if (num_lines == 1) {
1299 sstr.Clear();
1300 sstr.Printf(" __return_val = %s", input.GetStringAtIndex(0));
1301 auto_generated_function.AppendString(sstr.GetData());
1302 } else {
1304 "ScriptInterpreterPythonImpl::GenerateFunction(is_callback="
1305 "true) = ERROR: python function is multiline.");
1306 }
1307 } else {
1308 auto_generated_function.AppendString(
1309 " __return_val = None"); // Initialize user callback return value.
1310 auto_generated_function.AppendString(
1311 " def __user_code():"); // Create a nested function that will wrap
1312 // the user input. This is necessary to
1313 // capture the return value of the user input
1314 // and prevent early returns.
1315 for (int i = 0; i < num_lines; ++i) {
1316 sstr.Clear();
1317 sstr.Printf(" %s", input.GetStringAtIndex(i));
1318 auto_generated_function.AppendString(sstr.GetData());
1319 }
1320 auto_generated_function.AppendString(
1321 " __return_val = __user_code()"); // Call user code and capture
1322 // return value
1323 }
1324 auto_generated_function.AppendString(
1325 " for key in new_keys:"); // Iterate over all the keys from session
1326 // dict
1327 auto_generated_function.AppendString(
1328 " if key in old_keys:"); // If key was originally in
1329 // global dict
1330 auto_generated_function.AppendString(
1331 " internal_dict[key] = global_dict[key]"); // Update it
1332 auto_generated_function.AppendString(
1333 " elif key in global_dict:"); // Then if it is still in the
1334 // global dict
1335 auto_generated_function.AppendString(
1336 " del global_dict[key]"); // remove key/value from the
1337 // global dict
1338 auto_generated_function.AppendString(
1339 " return __return_val"); // Return the user callback return value.
1340
1341 // Verify that the results are valid Python.
1343
1344 return error;
1345}
1346
1348 StringList &user_input, std::string &output, const void *name_token) {
1349 static uint32_t num_created_functions = 0;
1350 user_input.RemoveBlankLines();
1351 StreamString sstr;
1352
1353 // Check to see if we have any data; if not, just return.
1354 if (user_input.GetSize() == 0)
1355 return false;
1356
1357 // Take what the user wrote, wrap it all up inside one big auto-generated
1358 // Python function, passing in the ValueObject as parameter to the function.
1359
1360 std::string auto_generated_function_name(
1361 GenerateUniqueName("lldb_autogen_python_type_print_func",
1362 num_created_functions, name_token));
1363 sstr.Printf("def %s (valobj, internal_dict):",
1364 auto_generated_function_name.c_str());
1365
1366 if (!GenerateFunction(sstr.GetData(), user_input, /*is_callback=*/false)
1367 .Success())
1368 return false;
1369
1370 // Store the name of the auto-generated function to be called.
1371 output.assign(auto_generated_function_name);
1372 return true;
1373}
1374
1376 StringList &user_input, std::string &output) {
1377 static uint32_t num_created_functions = 0;
1378 user_input.RemoveBlankLines();
1379 StreamString sstr;
1380
1381 // Check to see if we have any data; if not, just return.
1382 if (user_input.GetSize() == 0)
1383 return false;
1384
1385 std::string auto_generated_function_name(GenerateUniqueName(
1386 "lldb_autogen_python_cmd_alias_func", num_created_functions));
1387
1388 sstr.Printf("def %s (debugger, args, exe_ctx, result, internal_dict):",
1389 auto_generated_function_name.c_str());
1390
1391 if (!GenerateFunction(sstr.GetData(), user_input, /*is_callback=*/false)
1392 .Success())
1393 return false;
1394
1395 // Store the name of the auto-generated function to be called.
1396 output.assign(auto_generated_function_name);
1397 return true;
1398}
1399
1401 StringList &user_input, std::string &output, const void *name_token) {
1402 static uint32_t num_created_classes = 0;
1403 user_input.RemoveBlankLines();
1404 int num_lines = user_input.GetSize();
1405 StreamString sstr;
1406
1407 // Check to see if we have any data; if not, just return.
1408 if (user_input.GetSize() == 0)
1409 return false;
1410
1411 // Wrap all user input into a Python class
1412
1413 std::string auto_generated_class_name(GenerateUniqueName(
1414 "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1415
1416 StringList auto_generated_class;
1417
1418 // Create the function name & definition string.
1419
1420 sstr.Printf("class %s:", auto_generated_class_name.c_str());
1421 auto_generated_class.AppendString(sstr.GetString());
1422
1423 // Wrap everything up inside the class, increasing the indentation. we don't
1424 // need to play any fancy indentation tricks here because there is no
1425 // surrounding code whose indentation we need to honor
1426 for (int i = 0; i < num_lines; ++i) {
1427 sstr.Clear();
1428 sstr.Printf(" %s", user_input.GetStringAtIndex(i));
1429 auto_generated_class.AppendString(sstr.GetString());
1430 }
1431
1432 // Verify that the results are valid Python. (even though the method is
1433 // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1434 // (TODO: rename that method to ExportDefinitionToInterpreter)
1435 if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
1436 return false;
1437
1438 // Store the name of the auto-generated class
1439
1440 output.assign(auto_generated_class_name);
1441 return true;
1442}
1443
1446 if (class_name == nullptr || class_name[0] == '\0')
1448
1451 class_name, m_dictionary_name.c_str());
1454 new StructuredPythonObject(std::move(ret_val)));
1455}
1456
1458 const StructuredData::ObjectSP &os_plugin_object_sp,
1459 lldb::StackFrameSP frame_sp) {
1461
1462 if (!os_plugin_object_sp)
1463 return ValueObjectListSP();
1464
1465 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1466 if (!generic)
1467 return nullptr;
1468
1470 (PyObject *)generic->GetValue());
1471
1472 if (!implementor.IsAllocated())
1473 return ValueObjectListSP();
1474
1477 implementor.get(), frame_sp));
1478
1479 // if it fails, print the error but otherwise go on
1480 if (PyErr_Occurred()) {
1481 PyErr_Print();
1482 PyErr_Clear();
1483 }
1484 if (py_return.get()) {
1485 PythonList result_list(PyRefType::Borrowed, py_return.get());
1486 ValueObjectListSP result = std::make_shared<ValueObjectList>();
1487 for (size_t i = 0; i < result_list.GetSize(); i++) {
1488 PyObject *item = result_list.GetItemAtIndex(i).get();
1489 lldb::SBValue *sb_value_ptr =
1491 auto valobj_sp =
1493 if (valobj_sp)
1494 result->Append(valobj_sp);
1495 }
1496 return result;
1497 }
1498 return ValueObjectListSP();
1499}
1500
1502 const StructuredData::ObjectSP &os_plugin_object_sp,
1503 lldb::StackFrameSP frame_sp) {
1505
1506 if (!os_plugin_object_sp)
1507 return false;
1508
1509 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1510 if (!generic)
1511 return false;
1512
1514 (PyObject *)generic->GetValue());
1515
1516 if (!implementor.IsAllocated())
1517 return false;
1518
1519 bool result =
1520 SWIGBridge::LLDBSwigPython_ShouldHide(implementor.get(), frame_sp);
1521
1522 // if it fails, print the error but otherwise go on
1523 if (PyErr_Occurred()) {
1524 PyErr_Print();
1525 PyErr_Clear();
1527 return result;
1528}
1529
1532 return std::make_unique<ScriptedProcessPythonInterface>(*this);
1533}
1534
1537 return std::make_shared<ScriptedStopHookPythonInterface>(*this);
1538}
1539
1542 return std::make_shared<ScriptedHookPythonInterface>(*this);
1543}
1544
1547 return std::make_shared<ScriptedBreakpointPythonInterface>(*this);
1548}
1549
1552 return std::make_shared<ScriptedThreadPythonInterface>(*this);
1553}
1554
1557 return std::make_shared<ScriptedFramePythonInterface>(*this);
1558}
1559
1562 return std::make_shared<ScriptedFrameProviderPythonInterface>(*this);
1563}
1564
1567 return std::make_shared<ScriptedThreadPlanPythonInterface>(*this);
1568}
1569
1572 return std::make_shared<OperatingSystemPythonInterface>(*this);
1573}
1574
1577 ScriptObject obj) {
1578 void *ptr = const_cast<void *>(obj.GetPointer());
1580 PythonObject py_obj(PyRefType::Borrowed, static_cast<PyObject *>(ptr));
1581 if (!py_obj.IsValid() || py_obj.IsNone())
1582 return {};
1583 return py_obj.CreateStructuredObject();
1584}
1585
1589 if (!FileSystem::Instance().Exists(file_spec)) {
1590 error = Status::FromErrorString("no such file");
1591 return StructuredData::ObjectSP();
1592 }
1593
1594 StructuredData::ObjectSP module_sp;
1595
1596 LoadScriptOptions load_script_options =
1597 LoadScriptOptions().SetInitSession(true).SetSilent(false);
1598 if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1599 error, &module_sp))
1600 return module_sp;
1601
1602 return StructuredData::ObjectSP();
1603}
1604
1606 StructuredData::ObjectSP plugin_module_sp, Target *target,
1607 const char *setting_name, lldb_private::Status &error) {
1608 if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
1610 StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
1611 if (!generic)
1613
1614 Locker py_lock(this,
1616 TargetSP target_sp(target->shared_from_this());
1617
1618 auto setting = (PyObject *)SWIGBridge::LLDBSWIGPython_GetDynamicSetting(
1619 generic->GetValue(), setting_name, target_sp);
1620
1621 if (!setting)
1623
1624 PythonDictionary py_dict =
1626
1627 if (!py_dict)
1630 return py_dict.CreateStructuredDictionary();
1631}
1632
1635 const char *class_name, lldb::ValueObjectSP valobj) {
1636 if (class_name == nullptr || class_name[0] == '\0')
1637 return StructuredData::ObjectSP();
1638
1639 if (!valobj.get())
1640 return StructuredData::ObjectSP();
1641
1642 ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
1643 Target *target = exe_ctx.GetTargetPtr();
1644
1645 if (!target)
1646 return StructuredData::ObjectSP();
1647
1648 Debugger &debugger = target->GetDebugger();
1649 ScriptInterpreterPythonImpl *python_interpreter =
1650 GetPythonInterpreter(debugger);
1651
1652 if (!python_interpreter)
1653 return StructuredData::ObjectSP();
1654
1655 Locker py_lock(this,
1658 class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
1659
1661 new StructuredPythonObject(std::move(ret_val)));
1662}
1663
1666 DebuggerSP debugger_sp(m_debugger.shared_from_this());
1667
1668 if (class_name == nullptr || class_name[0] == '\0')
1670
1671 if (!debugger_sp.get())
1673
1674 Locker py_lock(this,
1677 class_name, m_dictionary_name.c_str(), debugger_sp);
1678
1679 if (ret_val.IsValid())
1681 new StructuredPythonObject(std::move(ret_val)));
1682 else
1683 return {};
1684}
1685
1687 const char *oneliner, std::string &output, const void *name_token) {
1689 input.SplitIntoLines(oneliner, strlen(oneliner));
1690 return GenerateTypeScriptFunction(input, output, name_token);
1691}
1692
1694 const char *oneliner, std::string &output, const void *name_token) {
1696 input.SplitIntoLines(oneliner, strlen(oneliner));
1697 return GenerateTypeSynthClass(input, output, name_token);
1698}
1699
1701 StringList &user_input, std::string &output, bool has_extra_args,
1702 bool is_callback) {
1703 static uint32_t num_created_functions = 0;
1704 user_input.RemoveBlankLines();
1705 StreamString sstr;
1706 Status error;
1707 if (user_input.GetSize() == 0) {
1708 error = Status::FromErrorString("No input data.");
1709 return error;
1710 }
1711
1712 std::string auto_generated_function_name(GenerateUniqueName(
1713 "lldb_autogen_python_bp_callback_func_", num_created_functions));
1714 if (has_extra_args)
1715 sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
1716 auto_generated_function_name.c_str());
1717 else
1718 sstr.Printf("def %s (frame, bp_loc, internal_dict):",
1719 auto_generated_function_name.c_str());
1720
1721 error = GenerateFunction(sstr.GetData(), user_input, is_callback);
1722 if (!error.Success())
1723 return error;
1724
1725 // Store the name of the auto-generated function to be called.
1726 output.assign(auto_generated_function_name);
1727 return error;
1728}
1729
1731 StringList &user_input, std::string &output, bool is_callback) {
1732 static uint32_t num_created_functions = 0;
1733 user_input.RemoveBlankLines();
1734 StreamString sstr;
1735
1736 if (user_input.GetSize() == 0)
1737 return false;
1738
1739 std::string auto_generated_function_name(GenerateUniqueName(
1740 "lldb_autogen_python_wp_callback_func_", num_created_functions));
1741 sstr.Printf("def %s (frame, wp, internal_dict):",
1742 auto_generated_function_name.c_str());
1743
1744 if (!GenerateFunction(sstr.GetData(), user_input, is_callback).Success())
1745 return false;
1746
1747 // Store the name of the auto-generated function to be called.
1748 output.assign(auto_generated_function_name);
1749 return true;
1750}
1751
1753 const char *python_function_name, lldb::ValueObjectSP valobj,
1754 StructuredData::ObjectSP &callee_wrapper_sp,
1755 const TypeSummaryOptions &options, std::string &retval) {
1756
1758
1759 if (!valobj.get()) {
1760 retval.assign("<no object>");
1761 return false;
1762 }
1763
1764 void *old_callee = nullptr;
1765 StructuredData::Generic *generic = nullptr;
1766 if (callee_wrapper_sp) {
1767 generic = callee_wrapper_sp->GetAsGeneric();
1768 if (generic)
1769 old_callee = generic->GetValue();
1770 }
1771 void *new_callee = old_callee;
1772
1773 bool ret_val;
1774 if (python_function_name && *python_function_name) {
1775 {
1778 {
1779 TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
1780
1781 static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
1782 Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
1784 python_function_name, GetSessionDictionary().get(), valobj,
1785 &new_callee, options_sp, retval);
1786 }
1787 }
1788 } else {
1789 retval.assign("<no function name>");
1790 return false;
1791 }
1792
1793 if (new_callee && old_callee != new_callee) {
1794 Locker py_lock(this,
1796 callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
1797 PythonObject(PyRefType::Borrowed, static_cast<PyObject *>(new_callee)));
1799
1800 return ret_val;
1801}
1802
1804 const char *python_function_name, TypeImplSP type_impl_sp) {
1805 Locker py_lock(this,
1808 python_function_name, m_dictionary_name.c_str(), type_impl_sp);
1809}
1810
1812 void *baton, StoppointCallbackContext *context, user_id_t break_id,
1813 user_id_t break_loc_id) {
1814 CommandDataPython *bp_option_data = (CommandDataPython *)baton;
1815 const char *python_function_name = bp_option_data->script_source.c_str();
1816
1817 if (!context)
1818 return true;
1819
1820 ExecutionContext exe_ctx(context->exe_ctx_ref);
1821 Target *target = exe_ctx.GetTargetPtr();
1822
1823 if (!target)
1824 return true;
1825
1826 Debugger &debugger = target->GetDebugger();
1827 ScriptInterpreterPythonImpl *python_interpreter =
1828 GetPythonInterpreter(debugger);
1829
1830 if (!python_interpreter)
1831 return true;
1832
1833 if (python_function_name && python_function_name[0]) {
1834 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
1835 BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
1836 if (breakpoint_sp) {
1837 const BreakpointLocationSP bp_loc_sp(
1838 breakpoint_sp->FindLocationByID(break_loc_id));
1839
1840 if (stop_frame_sp && bp_loc_sp) {
1841 bool ret_val = true;
1842 {
1843 Locker py_lock(python_interpreter, Locker::AcquireLock |
1846 Expected<bool> maybe_ret_val =
1848 python_function_name,
1849 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
1850 bp_loc_sp, bp_option_data->m_extra_args);
1851
1852 if (!maybe_ret_val) {
1853
1854 llvm::handleAllErrors(
1855 maybe_ret_val.takeError(),
1856 [&](PythonException &E) {
1857 *debugger.GetAsyncErrorStream() << E.ReadBacktrace();
1858 },
1859 [&](const llvm::ErrorInfoBase &E) {
1860 *debugger.GetAsyncErrorStream() << E.message();
1861 });
1862
1863 } else {
1864 ret_val = maybe_ret_val.get();
1865 }
1866 }
1867 return ret_val;
1868 }
1869 }
1870 }
1871 // We currently always true so we stop in case anything goes wrong when
1872 // trying to call the script function
1873 return true;
1874}
1875
1877 void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
1878 WatchpointOptions::CommandData *wp_option_data =
1880 const char *python_function_name = wp_option_data->script_source.c_str();
1881
1882 if (!context)
1883 return true;
1884
1885 ExecutionContext exe_ctx(context->exe_ctx_ref);
1886 Target *target = exe_ctx.GetTargetPtr();
1887
1888 if (!target)
1889 return true;
1890
1891 Debugger &debugger = target->GetDebugger();
1892 ScriptInterpreterPythonImpl *python_interpreter =
1893 GetPythonInterpreter(debugger);
1894
1895 if (!python_interpreter)
1896 return true;
1897
1898 if (python_function_name && python_function_name[0]) {
1899 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
1900 WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
1901 if (wp_sp) {
1902 if (stop_frame_sp && wp_sp) {
1903 bool ret_val = true;
1904 {
1905 Locker py_lock(python_interpreter, Locker::AcquireLock |
1909 python_function_name,
1910 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
1911 wp_sp);
1912 }
1913 return ret_val;
1914 }
1915 }
1916 }
1917 // We currently always true so we stop in case anything goes wrong when
1918 // trying to call the script function
1919 return true;
1920}
1921
1923 const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
1924 if (!implementor_sp)
1925 return 0;
1926 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
1927 if (!generic)
1928 return 0;
1929 auto *implementor = static_cast<PyObject *>(generic->GetValue());
1930 if (!implementor)
1931 return 0;
1932
1933 size_t ret_val = 0;
1934
1935 {
1936 Locker py_lock(this,
1938 ret_val = SWIGBridge::LLDBSwigPython_CalculateNumChildren(implementor, max);
1940
1941 return ret_val;
1942}
1943
1945 const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
1946 if (!implementor_sp)
1947 return lldb::ValueObjectSP();
1948
1949 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
1950 if (!generic)
1951 return lldb::ValueObjectSP();
1952 auto *implementor = static_cast<PyObject *>(generic->GetValue());
1953 if (!implementor)
1954 return lldb::ValueObjectSP();
1955
1956 lldb::ValueObjectSP ret_val;
1957 {
1958 Locker py_lock(this,
1960 PyObject *child_ptr =
1962 if (child_ptr != nullptr && child_ptr != Py_None) {
1963 lldb::SBValue *sb_value_ptr =
1965 if (sb_value_ptr == nullptr)
1966 Py_XDECREF(child_ptr);
1967 else
1969 sb_value_ptr);
1970 } else {
1971 Py_XDECREF(child_ptr);
1972 }
1974
1975 return ret_val;
1976}
1977
1979 const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
1980 if (!implementor_sp)
1981 return llvm::createStringErrorV("type has no child named '{0}'",
1982 child_name);
1983
1984 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
1985 if (!generic)
1986 return llvm::createStringErrorV("type has no child named '{0}'",
1987 child_name);
1988 auto *implementor = static_cast<PyObject *>(generic->GetValue());
1989 if (!implementor)
1990 return llvm::createStringErrorV("type has no child named '{0}'",
1991 child_name);
1992
1993 uint32_t ret_val = UINT32_MAX;
1994
1995 {
1996 Locker py_lock(this,
1999 child_name);
2000 }
2001
2002 if (ret_val == UINT32_MAX)
2003 return llvm::createStringErrorV("type has no child named '{0}'",
2004 child_name);
2005 return ret_val;
2006}
2007
2009 const StructuredData::ObjectSP &implementor_sp) {
2010 bool ret_val = false;
2011
2012 if (!implementor_sp)
2013 return ret_val;
2014
2015 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2016 if (!generic)
2017 return ret_val;
2018 auto *implementor = static_cast<PyObject *>(generic->GetValue());
2019 if (!implementor)
2020 return ret_val;
2021
2022 {
2023 Locker py_lock(this,
2025 ret_val =
2028
2029 return ret_val;
2030}
2031
2033 const StructuredData::ObjectSP &implementor_sp) {
2034 bool ret_val = false;
2035
2036 if (!implementor_sp)
2037 return ret_val;
2038
2039 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2040 if (!generic)
2041 return ret_val;
2042 auto *implementor = static_cast<PyObject *>(generic->GetValue());
2043 if (!implementor)
2044 return ret_val;
2045
2046 {
2047 Locker py_lock(this,
2050 implementor);
2052
2053 return ret_val;
2054}
2055
2057 const StructuredData::ObjectSP &implementor_sp) {
2058 lldb::ValueObjectSP ret_val(nullptr);
2059
2060 if (!implementor_sp)
2061 return ret_val;
2062
2063 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2064 if (!generic)
2065 return ret_val;
2066 auto *implementor = static_cast<PyObject *>(generic->GetValue());
2067 if (!implementor)
2068 return ret_val;
2069
2070 {
2071 Locker py_lock(this,
2073 PyObject *child_ptr =
2075 if (child_ptr != nullptr && child_ptr != Py_None) {
2076 lldb::SBValue *sb_value_ptr =
2078 if (sb_value_ptr == nullptr)
2079 Py_XDECREF(child_ptr);
2080 else
2082 sb_value_ptr);
2083 } else {
2084 Py_XDECREF(child_ptr);
2085 }
2087
2088 return ret_val;
2089}
2090
2092 const StructuredData::ObjectSP &implementor_sp) {
2093 Locker py_lock(this,
2095
2096 if (!implementor_sp)
2097 return {};
2098
2099 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2100 if (!generic)
2101 return {};
2102
2103 PythonObject implementor(PyRefType::Borrowed,
2104 (PyObject *)generic->GetValue());
2105 if (!implementor.IsAllocated())
2106 return {};
2107
2108 llvm::Expected<PythonObject> expected_py_return =
2109 implementor.CallMethod("get_type_name");
2110
2111 if (!expected_py_return) {
2112 llvm::consumeError(expected_py_return.takeError());
2113 return {};
2114 }
2115
2116 PythonObject py_return = std::move(expected_py_return.get());
2117 if (!py_return.IsAllocated() || !PythonString::Check(py_return.get()))
2118 return {};
2120 PythonString type_name(PyRefType::Borrowed, py_return.get());
2121 return ConstString(type_name.GetString());
2122}
2123
2125 const char *impl_function, Process *process, std::string &output,
2126 Status &error) {
2127 bool ret_val;
2128 if (!process) {
2129 error = Status::FromErrorString("no process");
2130 return false;
2131 }
2132 if (!impl_function || !impl_function[0]) {
2133 error = Status::FromErrorString("no function to execute");
2134 return false;
2135 }
2136
2137 {
2138 Locker py_lock(this,
2141 impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
2142 output);
2143 if (!ret_val)
2144 error = Status::FromErrorString("python script evaluation failed");
2145 }
2146 return ret_val;
2147}
2148
2150 const char *impl_function, Thread *thread, std::string &output,
2151 Status &error) {
2152 if (!thread) {
2153 error = Status::FromErrorString("no thread");
2154 return false;
2155 }
2156 if (!impl_function || !impl_function[0]) {
2157 error = Status::FromErrorString("no function to execute");
2158 return false;
2159 }
2160
2161 Locker py_lock(this,
2163 if (std::optional<std::string> result =
2165 impl_function, m_dictionary_name.c_str(),
2166 thread->shared_from_this())) {
2167 output = std::move(*result);
2168 return true;
2170 error = Status::FromErrorString("python script evaluation failed");
2171 return false;
2172}
2173
2175 const char *impl_function, Target *target, std::string &output,
2176 Status &error) {
2177 bool ret_val;
2178 if (!target) {
2179 error = Status::FromErrorString("no thread");
2180 return false;
2181 }
2182 if (!impl_function || !impl_function[0]) {
2183 error = Status::FromErrorString("no function to execute");
2184 return false;
2185 }
2186
2187 {
2188 TargetSP target_sp(target->shared_from_this());
2189 Locker py_lock(this,
2192 impl_function, m_dictionary_name.c_str(), target_sp, output);
2193 if (!ret_val)
2194 error = Status::FromErrorString("python script evaluation failed");
2195 }
2196 return ret_val;
2197}
2198
2200 const char *impl_function, StackFrame *frame, std::string &output,
2201 Status &error) {
2202 if (!frame) {
2203 error = Status::FromErrorString("no frame");
2204 return false;
2205 }
2206 if (!impl_function || !impl_function[0]) {
2207 error = Status::FromErrorString("no function to execute");
2208 return false;
2209 }
2210
2211 Locker py_lock(this,
2213 if (std::optional<std::string> result =
2215 impl_function, m_dictionary_name.c_str(),
2216 frame->shared_from_this())) {
2217 output = std::move(*result);
2218 return true;
2220 error = Status::FromErrorString("python script evaluation failed");
2221 return false;
2222}
2223
2225 const char *impl_function, ValueObject *value, std::string &output,
2226 Status &error) {
2227 bool ret_val;
2228 if (!value) {
2229 error = Status::FromErrorString("no value");
2230 return false;
2231 }
2232 if (!impl_function || !impl_function[0]) {
2233 error = Status::FromErrorString("no function to execute");
2234 return false;
2235 }
2236
2237 {
2238 Locker py_lock(this,
2241 impl_function, m_dictionary_name.c_str(), value->GetSP(), output);
2242 if (!ret_val)
2243 error = Status::FromErrorString("python script evaluation failed");
2244 }
2245 return ret_val;
2246}
2247
2248uint64_t replace_all(std::string &str, const std::string &oldStr,
2249 const std::string &newStr) {
2250 size_t pos = 0;
2251 uint64_t matches = 0;
2252 while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2253 matches++;
2254 str.replace(pos, oldStr.length(), newStr);
2255 pos += newStr.length();
2256 }
2257 return matches;
2258}
2259
2261 const char *pathname, const LoadScriptOptions &options,
2263 FileSpec extra_search_dir, lldb::TargetSP target_sp) {
2264 namespace fs = llvm::sys::fs;
2265 namespace path = llvm::sys::path;
2266
2268 .SetEnableIO(!options.GetSilent())
2269 .SetSetLLDBGlobals(false);
2270
2271 if (!pathname || !pathname[0]) {
2272 error = Status::FromErrorString("empty path");
2273 return false;
2274 }
2275
2276 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2277 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2278 exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2279
2280 if (!io_redirect_or_error) {
2281 error = Status::FromError(io_redirect_or_error.takeError());
2282 return false;
2283 }
2284
2285 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
2286
2287 // Before executing Python code, lock the GIL.
2288 Locker py_lock(this,
2290 (options.GetInitSession() ? Locker::InitSession : 0) |
2293 (options.GetInitSession() ? Locker::TearDownSession : 0),
2294 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2295 io_redirect.GetErrorFile());
2296
2297 auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2298 if (directory.empty()) {
2299 return llvm::createStringError("invalid directory name");
2300 }
2301
2302 replace_all(directory, "\\", "\\\\");
2303 replace_all(directory, "'", "\\'");
2304
2305 // Make sure that Python has "directory" in the search path.
2306 StreamString command_stream;
2307 command_stream.Printf("if not (sys.path.__contains__('%s')):\n "
2308 "sys.path.insert(1,'%s');\n\n",
2309 directory.c_str(), directory.c_str());
2310 bool syspath_retval =
2311 ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
2312 if (!syspath_retval)
2313 return llvm::createStringError("Python sys.path handling failed");
2314
2315 return llvm::Error::success();
2316 };
2317
2318 std::string module_name(pathname);
2319 bool possible_package = false;
2320
2321 if (extra_search_dir) {
2322 if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2323 error = Status::FromError(std::move(e));
2324 return false;
2325 }
2326 } else {
2327 FileSpec module_file(pathname);
2328 FileSystem::Instance().Resolve(module_file);
2329
2330 fs::file_status st;
2331 std::error_code ec = status(module_file.GetPath(), st);
2332
2333 if (ec || st.type() == fs::file_type::status_error ||
2334 st.type() == fs::file_type::type_unknown ||
2335 st.type() == fs::file_type::file_not_found) {
2336 // if not a valid file of any sort, check if it might be a filename still
2337 // dot can't be used but / and \ can, and if either is found, reject
2338 if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2339 error = Status::FromErrorStringWithFormatv("invalid pathname '{0}'",
2340 pathname);
2341 return false;
2342 }
2343 // Not a filename, probably a package of some sort, let it go through.
2344 possible_package = true;
2345 } else if (is_directory(st) || is_regular_file(st)) {
2346 if (module_file.GetDirectory().IsEmpty()) {
2348 "invalid directory name '{0}'", pathname);
2349 return false;
2350 }
2351 if (llvm::Error e =
2352 ExtendSysPath(module_file.GetDirectory().GetCString())) {
2353 error = Status::FromError(std::move(e));
2354 return false;
2355 }
2356 module_name = module_file.GetFilename().GetCString();
2357 } else {
2359 "no known way to import this module specification");
2360 return false;
2361 }
2362 }
2363
2364 // Strip .py or .pyc extension
2365 llvm::StringRef extension = llvm::sys::path::extension(module_name);
2366 if (!extension.empty()) {
2367 if (extension == ".py")
2368 module_name.resize(module_name.length() - 3);
2369 else if (extension == ".pyc")
2370 module_name.resize(module_name.length() - 4);
2371 }
2372
2373 if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2375 "Python does not allow dots in module names: %s", module_name.c_str());
2376 return false;
2377 }
2378
2379 if (module_name.find('-') != llvm::StringRef::npos) {
2381 "Python discourages dashes in module names: %s", module_name.c_str());
2382 return false;
2383 }
2384
2385 // Check if the module is already imported.
2386 StreamString command_stream;
2387 command_stream.Clear();
2388 command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
2389 bool does_contain = false;
2390 // This call will succeed if the module was ever imported in any Debugger in
2391 // the lifetime of the process in which this LLDB framework is living.
2392 const bool does_contain_executed = ExecuteOneLineWithReturn(
2393 command_stream.GetData(),
2395 exc_options);
2396
2397 const bool was_imported_globally = does_contain_executed && does_contain;
2398 const bool was_imported_locally =
2400 .GetItemForKey(PythonString(module_name))
2401 .IsAllocated();
2402
2403 // now actually do the import
2404 command_stream.Clear();
2405
2406 if (was_imported_globally || was_imported_locally) {
2407 if (!was_imported_locally)
2408 command_stream.Printf("import %s ; reload_module(%s)",
2409 module_name.c_str(), module_name.c_str());
2410 else
2411 command_stream.Printf("reload_module(%s)", module_name.c_str());
2412 } else
2413 command_stream.Printf("import %s", module_name.c_str());
2414
2415 error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
2416 if (error.Fail())
2417 return false;
2418
2419 // if we are here, everything worked
2420 // call __lldb_init_module(debugger,dict)
2422 module_name.c_str(), m_dictionary_name.c_str(),
2423 m_debugger.shared_from_this())) {
2424 error = Status::FromErrorString("calling __lldb_init_module failed");
2425 return false;
2426 }
2427
2428 if (module_sp) {
2429 // everything went just great, now set the module object
2430 command_stream.Clear();
2431 command_stream.Printf("%s", module_name.c_str());
2432 void *module_pyobj = nullptr;
2434 command_stream.GetData(),
2436 exc_options) &&
2437 module_pyobj)
2438 *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2439 PyRefType::Owned, static_cast<PyObject *>(module_pyobj)));
2440 }
2441
2442 // Finally, if we got a target passed in, then we should tell the new module
2443 // about this target:
2444 if (target_sp)
2446 module_name.c_str(), m_dictionary_name.c_str(), target_sp);
2447
2448 return true;
2449}
2450
2451bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
2452 if (!word || !word[0])
2453 return false;
2454
2455 llvm::StringRef word_sr(word);
2456
2457 // filter out a few characters that would just confuse us and that are
2458 // clearly not keyword material anyway
2459 if (word_sr.find('"') != llvm::StringRef::npos ||
2460 word_sr.find('\'') != llvm::StringRef::npos)
2461 return false;
2462
2463 StreamString command_stream;
2464 command_stream.Printf("keyword.iskeyword('%s')", word);
2465 bool result;
2466 ExecuteScriptOptions options;
2467 options.SetEnableIO(false);
2468 options.SetMaskoutErrors(true);
2469 options.SetSetLLDBGlobals(false);
2470 if (ExecuteOneLineWithReturn(command_stream.GetData(),
2472 &result, options))
2473 return result;
2474 return false;
2475}
2476
2479 : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2480 m_old_asynch(debugger_sp->GetAsyncExecution()) {
2482 m_debugger_sp->SetAsyncExecution(false);
2484 m_debugger_sp->SetAsyncExecution(true);
2485}
2486
2488 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2489 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2490}
2491
2493 const char *impl_function, llvm::StringRef args,
2494 ScriptedCommandSynchronicity synchronicity,
2496 const lldb_private::ExecutionContext &exe_ctx) {
2497 if (!impl_function) {
2498 error = Status::FromErrorString("no function to execute");
2499 return false;
2500 }
2501
2502 lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2503 lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2504
2505 if (!debugger_sp.get()) {
2506 error = Status::FromErrorString("invalid Debugger pointer");
2507 return false;
2508 }
2509
2510 bool ret_val = false;
2511
2512 {
2513 Locker py_lock(this,
2515 (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2517
2518 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2519
2520 std::string args_str = args.str();
2522 impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2523 cmd_retobj, exe_ctx_ref_sp);
2524 }
2525
2526 if (!ret_val)
2527 error = Status::FromErrorString("unable to execute script function");
2528 else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2529 return false;
2531 error.Clear();
2532 return ret_val;
2533}
2534
2536 StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
2537 ScriptedCommandSynchronicity synchronicity,
2539 const lldb_private::ExecutionContext &exe_ctx) {
2540 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2541 error = Status::FromErrorString("no function to execute");
2542 return false;
2543 }
2544
2545 lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2546 lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2547
2548 if (!debugger_sp.get()) {
2549 error = Status::FromErrorString("invalid Debugger pointer");
2550 return false;
2551 }
2552
2553 bool ret_val = false;
2554
2555 {
2556 Locker py_lock(this,
2558 (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2560
2561 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2562
2563 std::string args_str = args.str();
2565 static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
2566 args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
2567 }
2568
2569 if (!ret_val)
2570 error = Status::FromErrorString("unable to execute script function");
2571 else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2572 return false;
2574 error.Clear();
2575 return ret_val;
2576}
2577
2579 StructuredData::GenericSP impl_obj_sp, Args &args,
2580 ScriptedCommandSynchronicity synchronicity,
2582 const lldb_private::ExecutionContext &exe_ctx) {
2583 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2584 error = Status::FromErrorString("no function to execute");
2585 return false;
2586 }
2587
2588 lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2589 lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2590
2591 if (!debugger_sp.get()) {
2592 error = Status::FromErrorString("invalid Debugger pointer");
2593 return false;
2594 }
2595
2596 bool ret_val = false;
2597
2598 {
2599 Locker py_lock(this,
2601 (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2603
2604 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2605
2606 StructuredData::ArraySP args_arr_sp(new StructuredData::Array());
2607
2608 for (const Args::ArgEntry &entry : args) {
2609 args_arr_sp->AddStringItem(entry.ref());
2610 }
2611 StructuredDataImpl args_impl(args_arr_sp);
2612
2614 static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
2615 args_impl, cmd_retobj, exe_ctx_ref_sp);
2616 }
2617
2618 if (!ret_val)
2619 error = Status::FromErrorString("unable to execute script function");
2620 else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2621 return false;
2622
2623 error.Clear();
2624 return ret_val;
2625}
2626
2627std::optional<std::string>
2629 StructuredData::GenericSP impl_obj_sp, Args &args) {
2630 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2631 return std::nullopt;
2632
2633 lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2634
2635 if (!debugger_sp.get())
2636 return std::nullopt;
2637
2638 std::optional<std::string> ret_val;
2639
2640 {
2643
2645
2646 // For scripting commands, we send the command string:
2647 std::string command;
2648 args.GetQuotedCommandString(command);
2650 static_cast<PyObject *>(impl_obj_sp->GetValue()), command);
2652 return ret_val;
2653}
2654
2657 StructuredData::GenericSP impl_obj_sp, std::vector<llvm::StringRef> &args,
2658 size_t args_pos, size_t char_in_arg) {
2659 StructuredData::DictionarySP completion_dict_sp;
2660 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2661 return completion_dict_sp;
2662
2663 {
2666
2667 completion_dict_sp =
2669 static_cast<PyObject *>(impl_obj_sp->GetValue()), args, args_pos,
2670 char_in_arg);
2672 return completion_dict_sp;
2673}
2674
2677 StructuredData::GenericSP impl_obj_sp, llvm::StringRef &long_option,
2678 size_t char_in_arg) {
2679 StructuredData::DictionarySP completion_dict_sp;
2680 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2681 return completion_dict_sp;
2682
2683 {
2686
2687 completion_dict_sp = SWIGBridge::
2689 static_cast<PyObject *>(impl_obj_sp->GetValue()), long_option,
2690 char_in_arg);
2691 }
2692 return completion_dict_sp;
2694
2695/// In Python, a special attribute __doc__ contains the docstring for an object
2696/// (function, method, class, ...) if any is defined Otherwise, the attribute's
2697/// value is None.
2699 std::string &dest) {
2700 dest.clear();
2701
2702 if (!item || !*item)
2703 return false;
2704
2705 std::string command(item);
2706 command += ".__doc__";
2707
2708 // Python is going to point this to valid data if ExecuteOneLineWithReturn
2709 // returns successfully.
2710 char *result_ptr = nullptr;
2711
2714 &result_ptr, ExecuteScriptOptions().SetEnableIO(false))) {
2715 if (result_ptr)
2716 dest.assign(result_ptr);
2717 return true;
2718 }
2719
2720 StreamString str_stream;
2721 str_stream << "Function " << item
2722 << " was not found. Containing module might be missing.";
2723 dest = std::string(str_stream.GetString());
2724
2725 return false;
2726}
2727
2729 StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2730 dest.clear();
2731
2733
2734 if (!cmd_obj_sp)
2735 return false;
2736
2738 (PyObject *)cmd_obj_sp->GetValue());
2739
2740 if (!implementor.IsAllocated())
2741 return false;
2742
2743 llvm::Expected<PythonObject> expected_py_return =
2744 implementor.CallMethod("get_short_help");
2745
2746 if (!expected_py_return) {
2747 llvm::consumeError(expected_py_return.takeError());
2748 return false;
2749 }
2750
2751 PythonObject py_return = std::move(expected_py_return.get());
2752
2753 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2754 PythonString py_string(PyRefType::Borrowed, py_return.get());
2755 llvm::StringRef return_data(py_string.GetString());
2756 dest.assign(return_data.data(), return_data.size());
2757 return true;
2759
2760 return false;
2761}
2762
2764 StructuredData::GenericSP cmd_obj_sp) {
2765 uint32_t result = 0;
2766
2768
2769 static char callee_name[] = "get_flags";
2770
2771 if (!cmd_obj_sp)
2772 return result;
2773
2775 (PyObject *)cmd_obj_sp->GetValue());
2776
2777 if (!implementor.IsAllocated())
2778 return result;
2779
2781 PyObject_GetAttrString(implementor.get(), callee_name));
2782
2783 if (PyErr_Occurred())
2784 PyErr_Clear();
2785
2786 if (!pmeth.IsAllocated())
2787 return result;
2788
2789 if (PyCallable_Check(pmeth.get()) == 0) {
2790 if (PyErr_Occurred())
2791 PyErr_Clear();
2792 return result;
2793 }
2794
2795 if (PyErr_Occurred())
2796 PyErr_Clear();
2797
2798 long long py_return = unwrapOrSetPythonException(
2799 As<long long>(implementor.CallMethod(callee_name)));
2800
2801 // if it fails, print the error but otherwise go on
2802 if (PyErr_Occurred()) {
2803 PyErr_Print();
2804 PyErr_Clear();
2805 } else {
2806 result = py_return;
2807 }
2809 return result;
2810}
2811
2814 StructuredData::GenericSP cmd_obj_sp) {
2815 StructuredData::ObjectSP result = {};
2816
2818
2819 static char callee_name[] = "get_options_definition";
2820
2821 if (!cmd_obj_sp)
2822 return result;
2823
2825 (PyObject *)cmd_obj_sp->GetValue());
2826
2827 if (!implementor.IsAllocated())
2828 return result;
2829
2831 PyObject_GetAttrString(implementor.get(), callee_name));
2832
2833 if (PyErr_Occurred())
2834 PyErr_Clear();
2835
2836 if (!pmeth.IsAllocated())
2837 return result;
2838
2839 if (PyCallable_Check(pmeth.get()) == 0) {
2840 if (PyErr_Occurred())
2841 PyErr_Clear();
2842 return result;
2843 }
2844
2845 if (PyErr_Occurred())
2846 PyErr_Clear();
2847
2848 PythonDictionary py_return = unwrapOrSetPythonException(
2849 As<PythonDictionary>(implementor.CallMethod(callee_name)));
2850
2851 // if it fails, print the error but otherwise go on
2852 if (PyErr_Occurred()) {
2853 PyErr_Print();
2854 PyErr_Clear();
2855 return {};
2857 return py_return.CreateStructuredObject();
2858}
2859
2862 StructuredData::GenericSP cmd_obj_sp) {
2863 StructuredData::ObjectSP result = {};
2864
2866
2867 static char callee_name[] = "get_args_definition";
2868
2869 if (!cmd_obj_sp)
2870 return result;
2871
2872 PythonObject implementor(PyRefType::Borrowed,
2873 (PyObject *)cmd_obj_sp->GetValue());
2874
2875 if (!implementor.IsAllocated())
2876 return result;
2877
2878 PythonObject pmeth(PyRefType::Owned,
2879 PyObject_GetAttrString(implementor.get(), callee_name));
2880
2881 if (PyErr_Occurred())
2882 PyErr_Clear();
2883
2884 if (!pmeth.IsAllocated())
2885 return result;
2886
2887 if (PyCallable_Check(pmeth.get()) == 0) {
2888 if (PyErr_Occurred())
2889 PyErr_Clear();
2890 return result;
2891 }
2892
2893 if (PyErr_Occurred())
2894 PyErr_Clear();
2895
2896 PythonList py_return = unwrapOrSetPythonException(
2897 As<PythonList>(implementor.CallMethod(callee_name)));
2898
2899 // if it fails, print the error but otherwise go on
2900 if (PyErr_Occurred()) {
2901 PyErr_Print();
2902 PyErr_Clear();
2903 return {};
2904 }
2905 return py_return.CreateStructuredObject();
2906}
2907
2909 StructuredData::GenericSP cmd_obj_sp) {
2910
2912
2913 static char callee_name[] = "option_parsing_started";
2914
2915 if (!cmd_obj_sp)
2916 return;
2917
2918 PythonObject implementor(PyRefType::Borrowed,
2919 (PyObject *)cmd_obj_sp->GetValue());
2920
2921 if (!implementor.IsAllocated())
2922 return;
2923
2924 PythonObject pmeth(PyRefType::Owned,
2925 PyObject_GetAttrString(implementor.get(), callee_name));
2926
2927 if (PyErr_Occurred())
2928 PyErr_Clear();
2929
2930 if (!pmeth.IsAllocated())
2931 return;
2932
2933 if (PyCallable_Check(pmeth.get()) == 0) {
2934 if (PyErr_Occurred())
2935 PyErr_Clear();
2936 return;
2937 }
2938
2939 if (PyErr_Occurred())
2940 PyErr_Clear();
2941
2942 // option_parsing_starting doesn't return anything, ignore anything but
2943 // python errors.
2944 unwrapOrSetPythonException(As<bool>(implementor.CallMethod(callee_name)));
2945
2946 // if it fails, print the error but otherwise go on
2947 if (PyErr_Occurred()) {
2948 PyErr_Print();
2949 PyErr_Clear();
2950 return;
2951 }
2952}
2953
2955 StructuredData::GenericSP cmd_obj_sp, ExecutionContext *exe_ctx,
2956 llvm::StringRef long_option, llvm::StringRef value) {
2957 StructuredData::ObjectSP result = {};
2958
2960
2961 static char callee_name[] = "set_option_value";
2962
2963 if (!cmd_obj_sp)
2964 return false;
2965
2966 PythonObject implementor(PyRefType::Borrowed,
2967 (PyObject *)cmd_obj_sp->GetValue());
2968
2969 if (!implementor.IsAllocated())
2970 return false;
2971
2972 PythonObject pmeth(PyRefType::Owned,
2973 PyObject_GetAttrString(implementor.get(), callee_name));
2974
2975 if (PyErr_Occurred())
2976 PyErr_Clear();
2977
2978 if (!pmeth.IsAllocated())
2979 return false;
2980
2981 if (PyCallable_Check(pmeth.get()) == 0) {
2982 if (PyErr_Occurred())
2983 PyErr_Clear();
2984 return false;
2985 }
2986
2987 if (PyErr_Occurred())
2988 PyErr_Clear();
2989
2990 lldb::ExecutionContextRefSP exe_ctx_ref_sp;
2991 if (exe_ctx)
2992 exe_ctx_ref_sp = std::make_shared<ExecutionContextRef>(exe_ctx);
2993 PythonObject ctx_ref_obj = SWIGBridge::ToSWIGWrapper(exe_ctx_ref_sp);
2994
2995 bool py_return = unwrapOrSetPythonException(As<bool>(
2996 implementor.CallMethod(callee_name, ctx_ref_obj,
2997 long_option.str().c_str(), value.str().c_str())));
2998
2999 // if it fails, print the error but otherwise go on
3000 if (PyErr_Occurred()) {
3001 PyErr_Print();
3002 PyErr_Clear();
3003 return false;
3004 }
3005 return py_return;
3006}
3007
3009 StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
3010 dest.clear();
3011
3013
3014 if (!cmd_obj_sp)
3015 return false;
3016
3018 (PyObject *)cmd_obj_sp->GetValue());
3019
3020 if (!implementor.IsAllocated())
3021 return false;
3022
3023 llvm::Expected<PythonObject> expected_py_return =
3024 implementor.CallMethod("get_long_help");
3025
3026 if (!expected_py_return) {
3027 llvm::consumeError(expected_py_return.takeError());
3028 return false;
3029 }
3030
3031 PythonObject py_return = std::move(expected_py_return.get());
3032
3033 bool got_string = false;
3034 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3035 PythonString str(PyRefType::Borrowed, py_return.get());
3036 llvm::StringRef str_data(str.GetString());
3037 dest.assign(str_data.data(), str_data.size());
3038 got_string = true;
3039 }
3041 return got_string;
3042}
3043
3044std::unique_ptr<ScriptInterpreterLocker>
3046 std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3049 return py_lock;
3050}
3051
3054
3055 // RAII-based initialization which correctly handles multiple-initialization,
3056 // version- specific differences among Python 2 and Python 3, and saving and
3057 // restoring various other pieces of state that can get mucked with during
3058 // initialization.
3059 InitializePythonRAII initialize_guard;
3060
3062
3063 // Update the path python uses to search for modules to include the current
3064 // directory.
3065
3066 RunSimpleString("import sys");
3068
3069 // Don't denormalize paths when calling file_spec.GetPath(). On platforms
3070 // that use a backslash as the path separator, this will result in executing
3071 // python code containing paths with unescaped backslashes. But Python also
3072 // accepts forward slashes, so to make life easier we just use that.
3073 if (FileSpec file_spec = GetPythonDir())
3074 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3075 if (FileSpec file_spec = HostInfo::GetShlibDir())
3076 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3077
3078 RunSimpleString("sys.dont_write_bytecode = 1; import "
3079 "lldb.embedded_interpreter; from "
3080 "lldb.embedded_interpreter import run_python_interpreter; "
3081 "from lldb.embedded_interpreter import run_one_line");
3082
3083#if LLDB_USE_PYTHON_SET_INTERRUPT
3084 // Python will not just overwrite its internal SIGINT handler but also the
3085 // one from the process. Backup the current SIGINT handler to prevent that
3086 // Python deletes it.
3087 RestoreSignalHandlerScope save_sigint(SIGINT);
3088
3089 // Setup a default SIGINT signal handler that works the same way as the
3090 // normal Python REPL signal handler which raises a KeyboardInterrupt.
3091 // Also make sure to not pollute the user's REPL with the signal module nor
3092 // our utility function.
3093 RunSimpleString("def lldb_setup_sigint_handler():\n"
3094 " import signal;\n"
3095 " def signal_handler(sig, frame):\n"
3096 " raise KeyboardInterrupt()\n"
3097 " signal.signal(signal.SIGINT, signal_handler);\n"
3098 "lldb_setup_sigint_handler();\n"
3099 "del lldb_setup_sigint_handler\n");
3100#endif
3101}
3102
3104 std::string path) {
3105 std::string statement;
3106 if (location == AddLocation::Beginning) {
3107 statement.assign("sys.path.insert(0,\"");
3108 statement.append(path);
3109 statement.append("\")");
3110 } else {
3111 statement.assign("sys.path.append(\"");
3112 statement.append(path);
3113 statement.append("\")");
3114 }
3115 RunSimpleString(statement.c_str());
3116}
3117
3118// We are intentionally NOT calling Py_Finalize here (this would be the logical
3119// place to call it). Calling Py_Finalize here causes test suite runs to seg
3120// fault: The test suite runs in Python. It registers SBDebugger::Terminate to
3121// be called 'at_exit'. When the test suite Python harness finishes up, it
3122// calls Py_Finalize, which calls all the 'at_exit' registered functions.
3123// SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3124// which calls ScriptInterpreter::Terminate, which calls
3125// ScriptInterpreterPythonImpl::Terminate. So if we call Py_Finalize here, we
3126// end up with Py_Finalize being called from within Py_Finalize, which results
3127// in a seg fault. Since this function only gets called when lldb is shutting
3128// down and going away anyway, the fact that we don't actually call Py_Finalize
3129// should not cause any problems (everything should shut down/go away anyway
3130// when the process exits).
3131//
3132// void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
static llvm::raw_ostream & error(Stream &strm)
#define lldbassert(x)
Definition LLDBAssert.h:16
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:364
#define LLDB_LOGF(log,...)
Definition Log.h:378
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:394
#define LLDB_LOG_VERBOSE(log,...)
Definition Log.h:371
ScriptInterpreterPythonImpl::Locker Locker
#define LLDB_PLUGIN_DEFINE(PluginName)
PyObject * PyInit__lldb(void)
static std::string GenerateUniqueName(const char *base_name_wanted, uint32_t &functions_counter, const void *name_token=nullptr)
#define LLDBSwigPyInit
static ScriptInterpreterPythonImpl * GetPythonInterpreter(Debugger &debugger)
static const char python_exe_relative_path[]
uint64_t replace_all(std::string &str, const std::string &oldStr, const std::string &newStr)
static const char GetInterpreterInfoScript[]
#define LLDB_SCOPED_TIMER()
Definition Timer.h:83
A command line argument class.
Definition Args.h:33
bool GetQuotedCommandString(std::string &command) const
Definition Args.cpp:232
"lldb/Breakpoint/BreakpointOptions.h" Class that manages the options on a breakpoint or breakpoint lo...
void SetCallback(BreakpointHitCallback callback, const lldb::BatonSP &baton_sp, bool synchronous=false)
Adds a callback to the breakpoint option set.
void AppendError(llvm::StringRef in_string)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
void AppendErrorWithFormatv(const char *format, Args &&...args)
A uniqued constant string class.
Definition ConstString.h:40
A class to manage flag bits.
Definition Debugger.h:100
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={})
ExecuteScriptOptions & SetMaskoutErrors(bool maskout)
ExecuteScriptOptions & SetSetLLDBGlobals(bool set)
ExecuteScriptOptions & SetEnableIO(bool enable)
Execution context objects refer to objects in the execution of the program that is being debugged.
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
const lldb::StackFrameSP & GetFrameSP() const
Get accessor to get the frame shared pointer.
Target * GetTargetPtr() const
Returns a pointer to the target object.
A file utility class.
Definition FileSpec.h:57
void AppendPathComponent(llvm::StringRef component)
Definition FileSpec.cpp:454
void SetDirectory(ConstString directory)
Directory string set accessor.
Definition FileSpec.cpp:342
bool RemoveLastPathComponent()
Removes the last path component by replacing the current path with its parent.
Definition FileSpec.cpp:465
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
llvm::StringRef GetFileNameExtension() const
Extract the extension of the file.
Definition FileSpec.cpp:410
Status ResolveSymbolicLink(const FileSpec &src, FileSpec &dst)
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
bool IsValid() const override
IsValid.
Definition File.cpp:105
virtual Status Flush()
Flush the current stream.
Definition File.cpp:148
lldb::LockableStreamFileSP GetErrorStreamFileSP()
Definition IOHandler.cpp:95
lldb::LockableStreamFileSP GetOutputStreamFileSP()
Definition IOHandler.cpp:93
void SetIsDone(bool b)
Definition IOHandler.h:81
void PutCString(const char *cstr)
Definition Log.cpp:145
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
A plug-in interface definition class for debugging a process.
Definition Process.h:357
void Flush()
Flush our output and error file handles.
static llvm::Expected< std::unique_ptr< ScriptInterpreterIORedirect > > Create(bool enable_io, Debugger &debugger, CommandReturnObject *result)
Create an IO redirect.
bool DoInitSession(uint16_t on_entry_flags, lldb::FileSP in, lldb::FileSP out, lldb::FileSP err)
Locker(ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry=AcquireLock|InitSession, uint16_t on_leave=FreeLock|TearDownSession, lldb::FileSP in=nullptr, lldb::FileSP out=nullptr, lldb::FileSP err=nullptr)
SynchronicityHandler(lldb::DebuggerSP, ScriptedCommandSynchronicity)
bool GenerateTypeScriptFunction(StringList &input, std::string &output, const void *name_token=nullptr) override
Status GenerateFunction(const char *signature, const StringList &input, bool is_callback) override
bool GenerateScriptAliasFunction(StringList &input, std::string &output) override
lldb_private::Status ExecuteMultipleLines(const char *in_string, const ExecuteScriptOptions &options=ExecuteScriptOptions()) override
bool ShouldHide(const StructuredData::ObjectSP &implementor, lldb::StackFrameSP frame_sp) override
bool GenerateWatchpointCommandCallbackData(StringList &input, std::string &output, bool is_callback) override
StructuredData::DictionarySP HandleOptionArgumentCompletionForScriptedCommand(StructuredData::GenericSP impl_obj_sp, llvm::StringRef &long_options, size_t char_in_arg) override
bool RunScriptBasedParsedCommand(StructuredData::GenericSP impl_obj_sp, Args &args, ScriptedCommandSynchronicity synchronicity, lldb_private::CommandReturnObject &cmd_retobj, Status &error, const lldb_private::ExecutionContext &exe_ctx) override
void OptionParsingStartedForCommandObject(StructuredData::GenericSP cmd_obj_sp) override
bool GetLongHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp, std::string &dest) override
lldb::ScriptedStopHookInterfaceSP CreateScriptedStopHookInterface() override
Status SetBreakpointCommandCallbackFunction(BreakpointOptions &bp_options, const char *function_name, StructuredData::ObjectSP extra_args_sp) override
Set a script function as the callback for the breakpoint.
lldb::ScriptedThreadInterfaceSP CreateScriptedThreadInterface() override
static bool BreakpointCallbackFunction(void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
StructuredData::DictionarySP GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target, const char *setting_name, lldb_private::Status &error) override
void CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options, CommandReturnObject &result) override
StructuredData::DictionarySP HandleArgumentCompletionForScriptedCommand(StructuredData::GenericSP impl_obj_sp, std::vector< llvm::StringRef > &args, size_t args_pos, size_t char_in_arg) override
bool RunScriptBasedCommand(const char *impl_function, llvm::StringRef args, ScriptedCommandSynchronicity synchronicity, lldb_private::CommandReturnObject &cmd_retobj, Status &error, const lldb_private::ExecutionContext &exe_ctx) override
lldb::ScriptedFrameProviderInterfaceSP CreateScriptedFrameProviderInterface() override
std::optional< std::string > GetRepeatCommandForScriptedCommand(StructuredData::GenericSP impl_obj_sp, Args &args) override
Status SetBreakpointCommandCallback(BreakpointOptions &bp_options, const char *callback_body, bool is_callback) override
Set the callback body text into the callback for the breakpoint.
StructuredData::ObjectSP GetArgumentsForCommandObject(StructuredData::GenericSP cmd_obj_sp) override
bool EnterSession(uint16_t on_entry_flags, lldb::FileSP in, lldb::FileSP out, lldb::FileSP err)
void SetWatchpointCommandCallback(WatchpointOptions *wp_options, const char *user_input, bool is_callback) override
Set a one-liner as the callback for the watchpoint.
lldb::ValueObjectSP GetSyntheticValue(const StructuredData::ObjectSP &implementor) override
std::unique_ptr< ScriptInterpreterLocker > AcquireInterpreterLock() override
void CollectDataForBreakpointCommandCallback(std::vector< std::reference_wrapper< BreakpointOptions > > &bp_options_vec, CommandReturnObject &result) override
bool UpdateSynthProviderInstance(const StructuredData::ObjectSP &implementor) override
static void AddToSysPath(AddLocation location, std::string path)
bool MightHaveChildrenSynthProviderInstance(const StructuredData::ObjectSP &implementor) override
bool LoadScriptingModule(const char *filename, const LoadScriptOptions &options, lldb_private::Status &error, StructuredData::ObjectSP *module_sp=nullptr, FileSpec extra_search_dir={}, lldb::TargetSP loaded_into_target_sp={}) override
StructuredData::GenericSP CreateFrameRecognizer(const char *class_name) override
ConstString GetSyntheticTypeName(const StructuredData::ObjectSP &implementor) override
Status GenerateBreakpointCommandCallbackData(StringList &input, std::string &output, bool has_extra_args, bool is_callback) override
lldb::OperatingSystemInterfaceSP CreateOperatingSystemInterface() override
bool SetOptionValueForCommandObject(StructuredData::GenericSP cmd_obj_sp, ExecutionContext *exe_ctx, llvm::StringRef long_option, llvm::StringRef value) override
llvm::Expected< uint32_t > GetIndexOfChildWithName(const StructuredData::ObjectSP &implementor, const char *child_name) override
bool FormatterCallbackFunction(const char *function_name, lldb::TypeImplSP type_impl_sp) override
Status ExportFunctionDefinitionToInterpreter(StringList &function_def) override
StructuredData::ObjectSP CreateSyntheticScriptedProvider(const char *class_name, lldb::ValueObjectSP valobj) override
bool ExecuteOneLine(llvm::StringRef command, CommandReturnObject *result, const ExecuteScriptOptions &options=ExecuteScriptOptions()) override
bool GetDocumentationForItem(const char *item, std::string &dest) override
In Python, a special attribute doc contains the docstring for an object (function,...
lldb::ScriptedHookInterfaceSP CreateScriptedHookInterface() override
uint32_t GetFlagsForCommandObject(StructuredData::GenericSP cmd_obj_sp) override
void IOHandlerInputComplete(IOHandler &io_handler, std::string &data) override
Called when a line or lines have been retrieved.
void IOHandlerActivated(IOHandler &io_handler, bool interactive) override
bool GetScriptedSummary(const char *function_name, lldb::ValueObjectSP valobj, StructuredData::ObjectSP &callee_wrapper_sp, const TypeSummaryOptions &options, std::string &retval) override
lldb::ScriptedFrameInterfaceSP CreateScriptedFrameInterface() override
lldb::ScriptedProcessInterfaceUP CreateScriptedProcessInterface() override
StructuredData::GenericSP CreateScriptCommandObject(const char *class_name) override
size_t CalculateNumChildren(const StructuredData::ObjectSP &implementor, uint32_t max) override
bool ExecuteOneLineWithReturn(llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type, void *ret_value, const ExecuteScriptOptions &options=ExecuteScriptOptions()) override
lldb::ScriptedBreakpointInterfaceSP CreateScriptedBreakpointInterface() override
bool RunScriptFormatKeyword(const char *impl_function, Process *process, std::string &output, Status &error) override
bool SetStdHandle(lldb::FileSP file, const char *py_name, python::PythonObject &save_file, const char *mode)
lldb::ValueObjectSP GetChildAtIndex(const StructuredData::ObjectSP &implementor, uint32_t idx) override
bool GenerateTypeSynthClass(StringList &input, std::string &output, const void *name_token=nullptr) override
StructuredData::ObjectSP CreateStructuredDataFromScriptObject(ScriptObject obj) override
StructuredData::ObjectSP GetOptionsForCommandObject(StructuredData::GenericSP cmd_obj_sp) override
StructuredData::ObjectSP LoadPluginModule(const FileSpec &file_spec, lldb_private::Status &error) override
bool GetShortHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp, std::string &dest) override
llvm::Expected< unsigned > GetMaxPositionalArgumentsForCallable(const llvm::StringRef &callable_name) override
static bool WatchpointCallbackFunction(void *baton, StoppointCallbackContext *context, lldb::user_id_t watch_id)
static lldb::ScriptInterpreterSP CreateInstance(Debugger &debugger)
lldb::ValueObjectListSP GetRecognizedArguments(const StructuredData::ObjectSP &implementor, lldb::StackFrameSP frame_sp) override
lldb::ScriptedThreadPlanInterfaceSP CreateScriptedThreadPlanInterface() override
Abstract interface for the Python script interpreter.
static void ComputePythonDir(llvm::SmallVectorImpl< char > &path)
static void ComputePythonDirForApple(llvm::SmallVectorImpl< char > &path)
StructuredData::DictionarySP GetInterpreterInfo() override
static void SharedLibraryDirectoryHelper(FileSpec &this_file)
const void * GetPointer() const
This base class provides an interface to stack frames.
Definition StackFrame.h:44
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
bool Success() const
Test for success condition.
Definition Status.cpp:303
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
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.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
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)
Definition Target.cpp:437
Debugger & GetDebugger() const
Definition Target.h:1324
WatchpointList & GetWatchpointList()
Definition Target.h:955
lldb::ValueObjectSP GetSP()
lldb::WatchpointSP FindByID(lldb::watch_id_t watchID) const
Returns a shared pointer to the watchpoint with id watchID, const version.
"lldb/Breakpoint/WatchpointOptions.h" Class that manages the options on a watchpoint.
void SetCallback(WatchpointHitCallback callback, const lldb::BatonSP &baton_sp, bool synchronous=false)
Adds a callback to the watchpoint option set.
StructuredData::DictionarySP CreateStructuredDictionary() const
PythonObject GetItemForKey(const PythonObject &key) const
void SetItemForKey(const PythonObject &key, const PythonObject &value)
static llvm::Expected< PythonFile > FromFile(File &file, const char *mode=nullptr)
static llvm::Expected< PythonModule > Import(const llvm::Twine &name)
PythonObject ResolveName(llvm::StringRef name) const
StructuredData::ObjectSP CreateStructuredObject() const
static PythonObject ResolveNameWithDictionary(llvm::StringRef name, const PythonDictionary &dict)
llvm::Expected< PythonObject > GetAttribute(const llvm::Twine &name) const
llvm::Expected< PythonObject > CallMethod(const char *name, const T &... t) const
static bool Check(PyObject *py_obj)
static PyObject * LLDBSwigPython_GetRecognizedArguments(PyObject *implementor, const lldb::StackFrameSP &frame_sp)
static bool LLDBSWIGPythonRunScriptKeywordValue(const char *python_function_name, const char *session_dictionary_name, const lldb::ValueObjectSP &value, std::string &output)
static bool LLDBSwigPythonCallParsedCommandObject(PyObject *implementor, lldb::DebuggerSP debugger, StructuredDataImpl &args_impl, lldb_private::CommandReturnObject &cmd_retobj, lldb::ExecutionContextRefSP exe_ctx_ref_sp)
static bool LLDBSwigPythonCallTypeScript(const char *python_function_name, const void *session_dictionary, const lldb::ValueObjectSP &valobj_sp, void **pyfunct_wrapper, const lldb::TypeSummaryOptionsSP &options_sp, std::string &retval)
static void * LLDBSWIGPython_GetDynamicSetting(void *module, const char *setting, const lldb::TargetSP &target_sp)
static lldb::ValueObjectSP LLDBSWIGPython_GetValueObjectSPFromSBValue(void *data)
static std::optional< std::string > LLDBSWIGPythonRunScriptKeywordThread(const char *python_function_name, const char *session_dictionary_name, lldb::ThreadSP thread)
static StructuredData::DictionarySP LLDBSwigPythonHandleArgumentCompletionForScriptedCommand(PyObject *implementor, std::vector< llvm::StringRef > &args_impl, size_t args_pos, size_t pos_in_arg)
static bool LLDBSwigPythonCallCommand(const char *python_function_name, const char *session_dictionary_name, lldb::DebuggerSP debugger, const char *args, lldb_private::CommandReturnObject &cmd_retobj, lldb::ExecutionContextRefSP exe_ctx_ref_sp)
static PyObject * LLDBSwigPython_GetValueSynthProviderInstance(PyObject *implementor)
static bool LLDBSwigPython_UpdateSynthProviderInstance(PyObject *implementor)
static StructuredData::DictionarySP LLDBSwigPythonHandleOptionArgumentCompletionForScriptedCommand(PyObject *implementor, llvm::StringRef &long_option, size_t pos_in_arg)
static bool LLDBSWIGPythonRunScriptKeywordTarget(const char *python_function_name, const char *session_dictionary_name, const lldb::TargetSP &target, std::string &output)
static uint32_t LLDBSwigPython_GetIndexOfChildWithName(PyObject *implementor, const char *child_name)
static std::optional< std::string > LLDBSwigPythonGetRepeatCommandForScriptedCommand(PyObject *implementor, std::string &command)
static std::optional< std::string > LLDBSWIGPythonRunScriptKeywordFrame(const char *python_function_name, const char *session_dictionary_name, lldb::StackFrameSP frame)
static PyObject * LLDBSwigPython_GetChildAtIndex(PyObject *implementor, uint32_t idx)
static bool LLDBSWIGPythonRunScriptKeywordProcess(const char *python_function_name, const char *session_dictionary_name, const lldb::ProcessSP &process, std::string &output)
static bool LLDBSwigPythonFormatterCallbackFunction(const char *python_function_name, const char *session_dictionary_name, lldb::TypeImplSP type_impl_sp)
static bool LLDBSwigPythonCallModuleInit(const char *python_module_name, const char *session_dictionary_name, lldb::DebuggerSP debugger)
static python::PythonObject LLDBSwigPythonCreateSyntheticProvider(const char *python_class_name, const char *session_dictionary_name, const lldb::ValueObjectSP &valobj_sp)
static bool LLDBSwigPythonWatchpointCallbackFunction(const char *python_function_name, const char *session_dictionary_name, const lldb::StackFrameSP &sb_frame, const lldb::WatchpointSP &sb_wp)
static python::PythonObject LLDBSWIGPython_CreateFrameRecognizer(const char *python_class_name, const char *session_dictionary_name)
static size_t LLDBSwigPython_CalculateNumChildren(PyObject *implementor, uint32_t max)
static PythonObject ToSWIGWrapper(std::unique_ptr< lldb::SBValue > value_sb)
static bool LLDBSwigPythonCallCommandObject(PyObject *implementor, lldb::DebuggerSP debugger, const char *args, lldb_private::CommandReturnObject &cmd_retobj, lldb::ExecutionContextRefSP exe_ctx_ref_sp)
static bool LLDBSwigPython_MightHaveChildrenSynthProviderInstance(PyObject *implementor)
static bool LLDBSwigPythonCallModuleNewTarget(const char *python_module_name, const char *session_dictionary_name, lldb::TargetSP target)
static python::PythonObject LLDBSwigPythonCreateCommandObject(const char *python_class_name, const char *session_dictionary_name, lldb::DebuggerSP debugger_sp)
static bool LLDBSwigPython_ShouldHide(PyObject *implementor, const lldb::StackFrameSP &frame_sp)
static llvm::Expected< bool > LLDBSwigPythonBreakpointCallbackFunction(const char *python_function_name, const char *session_dictionary_name, const lldb::StackFrameSP &sb_frame, const lldb::BreakpointLocationSP &sb_bp_loc, const lldb_private::StructuredDataImpl &args_impl)
#define UINT32_MAX
llvm::Expected< T > As(llvm::Expected< PythonObject > &&obj)
T unwrapOrSetPythonException(llvm::Expected< T > expected)
T unwrapIgnoringErrors(llvm::Expected< T > expected)
llvm::Expected< PythonObject > runStringMultiLine(const llvm::Twine &string, const PythonDictionary &globals, const PythonDictionary &locals)
int RunSimpleString(const char *str)
llvm::Expected< long long > As< long long >(llvm::Expected< PythonObject > &&obj)
void * LLDBSWIGPython_CastPyObjectToSBValue(PyObject *data)
llvm::Expected< bool > As< bool >(llvm::Expected< PythonObject > &&obj)
llvm::Expected< PythonObject > runStringOneLine(const llvm::Twine &string, const PythonDictionary &globals, const PythonDictionary &locals)
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:327
@ eScriptLanguagePython
std::shared_ptr< lldb_private::ScriptedHookInterface > ScriptedHookInterfaceSP
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
@ eReturnStatusFailed
std::shared_ptr< lldb_private::Watchpoint > WatchpointSP
std::shared_ptr< lldb_private::ScriptedFrameProviderInterface > ScriptedFrameProviderInterfaceSP
uint64_t user_id_t
Definition lldb-types.h:82
std::shared_ptr< lldb_private::LockableStreamFile > LockableStreamFileSP
std::shared_ptr< lldb_private::TypeImpl > TypeImplSP
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::File > FileSP
std::unique_ptr< lldb_private::ScriptedProcessInterface > ScriptedProcessInterfaceUP
std::shared_ptr< lldb_private::ScriptedFrameInterface > ScriptedFrameInterfaceSP
std::shared_ptr< lldb_private::ExecutionContextRef > ExecutionContextRefSP
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47