Bug Summary

File:build/source/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp
Warning:line 107, column 7
Value stored to 'ReadlinePatched' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ScriptInterpreterPython.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -isystem /usr/include/libxml2 -D HAVE_ROUND -D LLDB_PYTHON_EXE_RELATIVE_PATH="bin/python3.9" -D LLDB_PYTHON_RELATIVE_LIBDIR="lib/python3.9/site-packages" -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/lldb/source/Plugins/ScriptInterpreter/Python -I /build/source/lldb/source/Plugins/ScriptInterpreter/Python -I /build/source/lldb/include -I tools/lldb/include -I include -I /build/source/llvm/include -I /usr/include/python3.9 -I /build/source/clang/include -I tools/lldb/../clang/include -I /build/source/lldb/source -I tools/lldb/source -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/source/= -source-date-epoch 1668078801 -O2 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -Wno-deprecated-declarations -Wno-unknown-pragmas -Wno-strict-aliasing -Wno-stringop-truncation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-11-10-135928-647445-1 -x c++ /build/source/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp
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/Host/Config.h"
10#include "lldb/lldb-enumerations.h"
11
12#if LLDB_ENABLE_PYTHON1
13
14// LLDB Python header must be included first
15#include "lldb-python.h"
16
17#include "PythonDataObjects.h"
18#include "PythonReadline.h"
19#include "SWIGPythonBridge.h"
20#include "ScriptInterpreterPythonImpl.h"
21#include "ScriptedProcessPythonInterface.h"
22
23#include "lldb/API/SBError.h"
24#include "lldb/API/SBFrame.h"
25#include "lldb/API/SBValue.h"
26#include "lldb/Breakpoint/StoppointCallbackContext.h"
27#include "lldb/Breakpoint/WatchpointOptions.h"
28#include "lldb/Core/Debugger.h"
29#include "lldb/Core/PluginManager.h"
30#include "lldb/Core/ThreadedCommunication.h"
31#include "lldb/Core/ValueObject.h"
32#include "lldb/DataFormatters/TypeSummary.h"
33#include "lldb/Host/FileSystem.h"
34#include "lldb/Host/HostInfo.h"
35#include "lldb/Host/Pipe.h"
36#include "lldb/Interpreter/CommandInterpreter.h"
37#include "lldb/Interpreter/CommandReturnObject.h"
38#include "lldb/Target/Thread.h"
39#include "lldb/Target/ThreadPlan.h"
40#include "lldb/Utility/Instrumentation.h"
41#include "lldb/Utility/LLDBLog.h"
42#include "lldb/Utility/Timer.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/StringRef.h"
45#include "llvm/Support/Error.h"
46#include "llvm/Support/FileSystem.h"
47#include "llvm/Support/FormatAdapters.h"
48
49#include <cstdio>
50#include <cstdlib>
51#include <memory>
52#include <mutex>
53#include <string>
54
55using namespace lldb;
56using namespace lldb_private;
57using namespace lldb_private::python;
58using llvm::Expected;
59
60LLDB_PLUGIN_DEFINE(ScriptInterpreterPython)namespace lldb_private { void lldb_initialize_ScriptInterpreterPython
() { ScriptInterpreterPython::Initialize(); } void lldb_terminate_ScriptInterpreterPython
() { ScriptInterpreterPython::Terminate(); } }
61
62// Defined in the SWIG source file
63extern "C" PyObject *PyInit__lldb(void);
64
65#define LLDBSwigPyInitPyInit__lldb PyInit__lldb
66
67#if defined(_WIN32)
68// Don't mess with the signal handlers on Windows.
69#define LLDB_USE_PYTHON_SET_INTERRUPT(3 == 3 && 9 >= 2) || (3 > 3) 0
70#else
71// PyErr_SetInterrupt was introduced in 3.2.
72#define LLDB_USE_PYTHON_SET_INTERRUPT(3 == 3 && 9 >= 2) || (3 > 3) \
73 (PY_MAJOR_VERSION3 == 3 && PY_MINOR_VERSION9 >= 2) || (PY_MAJOR_VERSION3 > 3)
74#endif
75
76static ScriptInterpreterPythonImpl *GetPythonInterpreter(Debugger &debugger) {
77 ScriptInterpreter *script_interpreter =
78 debugger.GetScriptInterpreter(true, lldb::eScriptLanguagePython);
79 return static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
80}
81
82namespace {
83
84// Initializing Python is not a straightforward process. We cannot control
85// what external code may have done before getting to this point in LLDB,
86// including potentially having already initialized Python, so we need to do a
87// lot of work to ensure that the existing state of the system is maintained
88// across our initialization. We do this by using an RAII pattern where we
89// save off initial state at the beginning, and restore it at the end
90struct InitializePythonRAII {
91public:
92 InitializePythonRAII() {
93 InitializePythonHome();
94
95#ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE1
96 // Python's readline is incompatible with libedit being linked into lldb.
97 // Provide a patched version local to the embedded interpreter.
98 bool ReadlinePatched = false;
99 for (auto *p = PyImport_Inittab; p->name != nullptr; p++) {
100 if (strcmp(p->name, "readline") == 0) {
101 p->initfunc = initlldb_readline;
102 break;
103 }
104 }
105 if (!ReadlinePatched) {
106 PyImport_AppendInittab("readline", initlldb_readline);
107 ReadlinePatched = true;
Value stored to 'ReadlinePatched' is never read
108 }
109#endif
110
111 // Register _lldb as a built-in module.
112 PyImport_AppendInittab("_lldb", LLDBSwigPyInitPyInit__lldb);
113
114// Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
115// calling `Py_Initialize` and `PyEval_InitThreads`. < 3.2 requires that you
116// call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
117#if (PY_MAJOR_VERSION3 == 3 && PY_MINOR_VERSION9 >= 2) || (PY_MAJOR_VERSION3 > 3)
118 Py_InitializeEx(0);
119 InitializeThreadsPrivate();
120#else
121 InitializeThreadsPrivate();
122 Py_InitializeEx(0);
123#endif
124 }
125
126 ~InitializePythonRAII() {
127 if (m_was_already_initialized) {
128 Log *log = GetLog(LLDBLog::Script);
129 LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp"
, __func__, "Releasing PyGILState. Returning to state = {0}locked"
, m_gil_state == PyGILState_UNLOCKED ? "un" : ""); } while (0
)
130 m_gil_state == PyGILState_UNLOCKED ? "un" : "")do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp"
, __func__, "Releasing PyGILState. Returning to state = {0}locked"
, m_gil_state == PyGILState_UNLOCKED ? "un" : ""); } while (0
)
;
131 PyGILState_Release(m_gil_state);
132 } else {
133 // We initialized the threads in this function, just unlock the GIL.
134 PyEval_SaveThread();
135 }
136 }
137
138private:
139 void InitializePythonHome() {
140#if LLDB_EMBED_PYTHON_HOME0
141 typedef wchar_t *str_type;
142 static str_type g_python_home = []() -> str_type {
143 const char *lldb_python_home = LLDB_PYTHON_HOME;
144 const char *absolute_python_home = nullptr;
145 llvm::SmallString<64> path;
146 if (llvm::sys::path::is_absolute(lldb_python_home)) {
147 absolute_python_home = lldb_python_home;
148 } else {
149 FileSpec spec = HostInfo::GetShlibDir();
150 if (!spec)
151 return nullptr;
152 spec.GetPath(path);
153 llvm::sys::path::append(path, lldb_python_home);
154 absolute_python_home = path.c_str();
155 }
156 size_t size = 0;
157 return Py_DecodeLocale(absolute_python_home, &size);
158 }();
159 if (g_python_home != nullptr) {
160 Py_SetPythonHome(g_python_home);
161 }
162#endif
163 }
164
165 void InitializeThreadsPrivate() {
166// Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself,
167// so there is no way to determine whether the embedded interpreter
168// was already initialized by some external code. `PyEval_ThreadsInitialized`
169// would always return `true` and `PyGILState_Ensure/Release` flow would be
170// executed instead of unlocking GIL with `PyEval_SaveThread`. When
171// an another thread calls `PyGILState_Ensure` it would get stuck in deadlock.
172#if (PY_MAJOR_VERSION3 == 3 && PY_MINOR_VERSION9 >= 7) || (PY_MAJOR_VERSION3 > 3)
173 // The only case we should go further and acquire the GIL: it is unlocked.
174 if (PyGILState_Check())
175 return;
176#endif
177
178 if (PyEval_ThreadsInitialized()) {
179 Log *log = GetLog(LLDBLog::Script);
180
181 m_was_already_initialized = true;
182 m_gil_state = PyGILState_Ensure();
183 LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n",do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp"
, __func__, "Ensured PyGILState. Previous state = {0}locked\n"
, m_gil_state == PyGILState_UNLOCKED ? "un" : ""); } while (0
)
184 m_gil_state == PyGILState_UNLOCKED ? "un" : "")do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp"
, __func__, "Ensured PyGILState. Previous state = {0}locked\n"
, m_gil_state == PyGILState_UNLOCKED ? "un" : ""); } while (0
)
;
185 return;
186 }
187
188 // InitThreads acquires the GIL if it hasn't been called before.
189 PyEval_InitThreads();
190 }
191
192 PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
193 bool m_was_already_initialized = false;
194};
195
196#if LLDB_USE_PYTHON_SET_INTERRUPT(3 == 3 && 9 >= 2) || (3 > 3)
197/// Saves the current signal handler for the specified signal and restores
198/// it at the end of the current scope.
199struct RestoreSignalHandlerScope {
200 /// The signal handler.
201 struct sigaction m_prev_handler;
202 int m_signal_code;
203 RestoreSignalHandlerScope(int signal_code) : m_signal_code(signal_code) {
204 // Initialize sigaction to their default state.
205 std::memset(&m_prev_handler, 0, sizeof(m_prev_handler));
206 // Don't install a new handler, just read back the old one.
207 struct sigaction *new_handler = nullptr;
208 int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler);
209 lldbassert(signal_err == 0 && "sigaction failed to read handler")lldb_private::lldb_assert(static_cast<bool>(signal_err ==
0 && "sigaction failed to read handler"), "signal_err == 0 && \"sigaction failed to read handler\""
, __FUNCTION__, "lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp"
, 209)
;
210 }
211 ~RestoreSignalHandlerScope() {
212 int signal_err = ::sigaction(m_signal_code, &m_prev_handler, nullptr);
213 lldbassert(signal_err == 0 && "sigaction failed to restore old handler")lldb_private::lldb_assert(static_cast<bool>(signal_err ==
0 && "sigaction failed to restore old handler"), "signal_err == 0 && \"sigaction failed to restore old handler\""
, __FUNCTION__, "lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp"
, 213)
;
214 }
215};
216#endif
217} // namespace
218
219void ScriptInterpreterPython::ComputePythonDirForApple(
220 llvm::SmallVectorImpl<char> &path) {
221 auto style = llvm::sys::path::Style::posix;
222
223 llvm::StringRef path_ref(path.begin(), path.size());
224 auto rbegin = llvm::sys::path::rbegin(path_ref, style);
225 auto rend = llvm::sys::path::rend(path_ref);
226 auto framework = std::find(rbegin, rend, "LLDB.framework");
227 if (framework == rend) {
228 ComputePythonDir(path);
229 return;
230 }
231 path.resize(framework - rend);
232 llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
233}
234
235void ScriptInterpreterPython::ComputePythonDir(
236 llvm::SmallVectorImpl<char> &path) {
237 // Build the path by backing out of the lib dir, then building with whatever
238 // the real python interpreter uses. (e.g. lib for most, lib64 on RHEL
239 // x86_64, or bin on Windows).
240 llvm::sys::path::remove_filename(path);
241 llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR"lib/python3.9/site-packages");
242 // remove double "lib/lib" statement
243 std::replace(path.begin(), path.end(), '/lib/lib/', '/lib/');
244
245#if defined(_WIN32)
246 // This will be injected directly through FileSpec.SetDirectory(),
247 // so we need to normalize manually.
248 std::replace(path.begin(), path.end(), '\\', '/');
249#endif
250}
251
252FileSpec ScriptInterpreterPython::GetPythonDir() {
253 static FileSpec g_spec = []() {
254 FileSpec spec = HostInfo::GetShlibDir();
255 if (!spec)
256 return FileSpec();
257 llvm::SmallString<64> path;
258 spec.GetPath(path);
259
260#if defined(__APPLE__)
261 ComputePythonDirForApple(path);
262#else
263 ComputePythonDir(path);
264#endif
265 spec.SetDirectory(path);
266 return spec;
267 }();
268 return g_spec;
269}
270
271static const char GetInterpreterInfoScript[] = R"(
272import os
273import sys
274
275def main(lldb_python_dir, python_exe_relative_path):
276 info = {
277 "lldb-pythonpath": lldb_python_dir,
278 "language": "python",
279 "prefix": sys.prefix,
280 "executable": os.path.join(sys.prefix, python_exe_relative_path)
281 }
282 return info
283)";
284
285static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH"bin/python3.9";
286
287StructuredData::DictionarySP ScriptInterpreterPython::GetInterpreterInfo() {
288 GIL gil;
289 FileSpec python_dir_spec = GetPythonDir();
290 if (!python_dir_spec)
291 return nullptr;
292 PythonScript get_info(GetInterpreterInfoScript);
293 auto info_json = unwrapIgnoringErrors(
294 As<PythonDictionary>(get_info(PythonString(python_dir_spec.GetPath()),
295 PythonString(python_exe_relative_path))));
296 if (!info_json)
297 return nullptr;
298 return info_json.CreateStructuredDictionary();
299}
300
301void ScriptInterpreterPython::SharedLibraryDirectoryHelper(
302 FileSpec &this_file) {
303 // When we're loaded from python, this_file will point to the file inside the
304 // python package directory. Replace it with the one in the lib directory.
305#ifdef _WIN32
306 // On windows, we need to manually back out of the python tree, and go into
307 // the bin directory. This is pretty much the inverse of what ComputePythonDir
308 // does.
309 if (this_file.GetFileNameExtension() == ConstString(".pyd")) {
310 this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd
311 this_file.RemoveLastPathComponent(); // lldb
312 llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR"lib/python3.9/site-packages";
313 for (auto it = llvm::sys::path::begin(libdir),
314 end = llvm::sys::path::end(libdir);
315 it != end; ++it)
316 this_file.RemoveLastPathComponent();
317 this_file.AppendPathComponent("bin");
318 this_file.AppendPathComponent("liblldb.dll");
319 }
320#else
321 // The python file is a symlink, so we can find the real library by resolving
322 // it. We can do this unconditionally.
323 FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
324#endif
325}
326
327llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() {
328 return "Embedded Python interpreter";
329}
330
331void ScriptInterpreterPython::Initialize() {
332 static llvm::once_flag g_once_flag;
333 llvm::call_once(g_once_flag, []() {
334 PluginManager::RegisterPlugin(GetPluginNameStatic(),
335 GetPluginDescriptionStatic(),
336 lldb::eScriptLanguagePython,
337 ScriptInterpreterPythonImpl::CreateInstance);
338 ScriptInterpreterPythonImpl::Initialize();
339 });
340}
341
342void ScriptInterpreterPython::Terminate() {}
343
344ScriptInterpreterPythonImpl::Locker::Locker(
345 ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
346 uint16_t on_leave, FileSP in, FileSP out, FileSP err)
347 : ScriptInterpreterLocker(),
348 m_teardown_session((on_leave & TearDownSession) == TearDownSession),
349 m_python_interpreter(py_interpreter) {
350 DoAcquireLock();
351 if ((on_entry & InitSession) == InitSession) {
352 if (!DoInitSession(on_entry, in, out, err)) {
353 // Don't teardown the session if we didn't init it.
354 m_teardown_session = false;
355 }
356 }
357}
358
359bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
360 Log *log = GetLog(LLDBLog::Script);
361 m_GILState = PyGILState_Ensure();
362 LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked",do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp"
, __func__, "Ensured PyGILState. Previous state = {0}locked",
m_GILState == PyGILState_UNLOCKED ? "un" : ""); } while (0)
363 m_GILState == PyGILState_UNLOCKED ? "un" : "")do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp"
, __func__, "Ensured PyGILState. Previous state = {0}locked",
m_GILState == PyGILState_UNLOCKED ? "un" : ""); } while (0)
;
364
365 // we need to save the thread state when we first start the command because
366 // we might decide to interrupt it while some action is taking place outside
367 // of Python (e.g. printing to screen, waiting for the network, ...) in that
368 // case, _PyThreadState_Current will be NULL - and we would be unable to set
369 // the asynchronous exception - not a desirable situation
370 m_python_interpreter->SetThreadState(PyThreadState_Get());
371 m_python_interpreter->IncrementLockCount();
372 return true;
373}
374
375bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
376 FileSP in, FileSP out,
377 FileSP err) {
378 if (!m_python_interpreter)
379 return false;
380 return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
381}
382
383bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
384 Log *log = GetLog(LLDBLog::Script);
385 LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp"
, __func__, "Releasing PyGILState. Returning to state = {0}locked"
, m_GILState == PyGILState_UNLOCKED ? "un" : ""); } while (0)
386 m_GILState == PyGILState_UNLOCKED ? "un" : "")do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp"
, __func__, "Releasing PyGILState. Returning to state = {0}locked"
, m_GILState == PyGILState_UNLOCKED ? "un" : ""); } while (0)
;
387 PyGILState_Release(m_GILState);
388 m_python_interpreter->DecrementLockCount();
389 return true;
390}
391
392bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
393 if (!m_python_interpreter)
394 return false;
395 m_python_interpreter->LeaveSession();
396 return true;
397}
398
399ScriptInterpreterPythonImpl::Locker::~Locker() {
400 if (m_teardown_session)
401 DoTearDownSession();
402 DoFreeLock();
403}
404
405ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger)
406 : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
407 m_saved_stderr(), m_main_module(),
408 m_session_dict(PyInitialValue::Invalid),
409 m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(),
410 m_run_one_line_str_global(),
411 m_dictionary_name(m_debugger.GetInstanceName().AsCString()),
412 m_active_io_handler(eIOHandlerNone), m_session_is_active(false),
413 m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
414 m_command_thread_state(nullptr) {
415 m_scripted_process_interface_up =
416 std::make_unique<ScriptedProcessPythonInterface>(*this);
417
418 m_dictionary_name.append("_dict");
419 StreamString run_string;
420 run_string.Printf("%s = dict()", m_dictionary_name.c_str());
421
422 Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock);
423 PyRun_SimpleString(run_string.GetData())PyRun_SimpleStringFlags(run_string.GetData(), __null);
424
425 run_string.Clear();
426 run_string.Printf(
427 "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
428 m_dictionary_name.c_str());
429 PyRun_SimpleString(run_string.GetData())PyRun_SimpleStringFlags(run_string.GetData(), __null);
430
431 // Reloading modules requires a different syntax in Python 2 and Python 3.
432 // This provides a consistent syntax no matter what version of Python.
433 run_string.Clear();
434 run_string.Printf("run_one_line (%s, 'from importlib import reload as reload_module')",
435 m_dictionary_name.c_str());
436 PyRun_SimpleString(run_string.GetData())PyRun_SimpleStringFlags(run_string.GetData(), __null);
437
438 // WARNING: temporary code that loads Cocoa formatters - this should be done
439 // on a per-platform basis rather than loading the whole set and letting the
440 // individual formatter classes exploit APIs to check whether they can/cannot
441 // do their task
442 run_string.Clear();
443 run_string.Printf(
444 "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')",
445 m_dictionary_name.c_str());
446 PyRun_SimpleString(run_string.GetData())PyRun_SimpleStringFlags(run_string.GetData(), __null);
447 run_string.Clear();
448
449 run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
450 "lldb.embedded_interpreter import run_python_interpreter; "
451 "from lldb.embedded_interpreter import run_one_line')",
452 m_dictionary_name.c_str());
453 PyRun_SimpleString(run_string.GetData())PyRun_SimpleStringFlags(run_string.GetData(), __null);
454 run_string.Clear();
455
456 run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64"l" "u"
457 "; pydoc.pager = pydoc.plainpager')",
458 m_dictionary_name.c_str(), m_debugger.GetID());
459 PyRun_SimpleString(run_string.GetData())PyRun_SimpleStringFlags(run_string.GetData(), __null);
460}
461
462ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
463 // the session dictionary may hold objects with complex state which means
464 // that they may need to be torn down with some level of smarts and that, in
465 // turn, requires a valid thread state force Python to procure itself such a
466 // thread state, nuke the session dictionary and then release it for others
467 // to use and proceed with the rest of the shutdown
468 auto gil_state = PyGILState_Ensure();
469 m_session_dict.Reset();
470 PyGILState_Release(gil_state);
471}
472
473void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler,
474 bool interactive) {
475 const char *instructions = nullptr;
476
477 switch (m_active_io_handler) {
478 case eIOHandlerNone:
479 break;
480 case eIOHandlerBreakpoint:
481 instructions = R"(Enter your Python command(s). Type 'DONE' to end.
482def function (frame, bp_loc, internal_dict):
483 """frame: the lldb.SBFrame for the location at which you stopped
484 bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
485 internal_dict: an LLDB support object not to be used"""
486)";
487 break;
488 case eIOHandlerWatchpoint:
489 instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
490 break;
491 }
492
493 if (instructions) {
494 StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
495 if (output_sp && interactive) {
496 output_sp->PutCString(instructions);
497 output_sp->Flush();
498 }
499 }
500}
501
502void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler,
503 std::string &data) {
504 io_handler.SetIsDone(true);
505 bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
506
507 switch (m_active_io_handler) {
508 case eIOHandlerNone:
509 break;
510 case eIOHandlerBreakpoint: {
511 std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
512 (std::vector<std::reference_wrapper<BreakpointOptions>> *)
513 io_handler.GetUserData();
514 for (BreakpointOptions &bp_options : *bp_options_vec) {
515
516 auto data_up = std::make_unique<CommandDataPython>();
517 if (!data_up)
518 break;
519 data_up->user_source.SplitIntoLines(data);
520
521 StructuredData::ObjectSP empty_args_sp;
522 if (GenerateBreakpointCommandCallbackData(data_up->user_source,
523 data_up->script_source,
524 false)
525 .Success()) {
526 auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
527 std::move(data_up));
528 bp_options.SetCallback(
529 ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
530 } else if (!batch_mode) {
531 StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
532 if (error_sp) {
533 error_sp->Printf("Warning: No command attached to breakpoint.\n");
534 error_sp->Flush();
535 }
536 }
537 }
538 m_active_io_handler = eIOHandlerNone;
539 } break;
540 case eIOHandlerWatchpoint: {
541 WatchpointOptions *wp_options =
542 (WatchpointOptions *)io_handler.GetUserData();
543 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
544 data_up->user_source.SplitIntoLines(data);
545
546 if (GenerateWatchpointCommandCallbackData(data_up->user_source,
547 data_up->script_source)) {
548 auto baton_sp =
549 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
550 wp_options->SetCallback(
551 ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
552 } else if (!batch_mode) {
553 StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
554 if (error_sp) {
555 error_sp->Printf("Warning: No command attached to breakpoint.\n");
556 error_sp->Flush();
557 }
558 }
559 m_active_io_handler = eIOHandlerNone;
560 } break;
561 }
562}
563
564lldb::ScriptInterpreterSP
565ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) {
566 return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
567}
568
569void ScriptInterpreterPythonImpl::LeaveSession() {
570 Log *log = GetLog(LLDBLog::Script);
571 if (log)
572 log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
573
574 // Unset the LLDB global variables.
575 PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "PyRun_SimpleStringFlags("lldb.debugger = None; lldb.target = None; lldb.process "
"= None; lldb.thread = None; lldb.frame = None", __null)
576 "= None; lldb.thread = None; lldb.frame = None")PyRun_SimpleStringFlags("lldb.debugger = None; lldb.target = None; lldb.process "
"= None; lldb.thread = None; lldb.frame = None", __null)
;
577
578 // checking that we have a valid thread state - since we use our own
579 // threading and locking in some (rare) cases during cleanup Python may end
580 // up believing we have no thread state and PyImport_AddModule will crash if
581 // that is the case - since that seems to only happen when destroying the
582 // SBDebugger, we can make do without clearing up stdout and stderr
583
584 // rdar://problem/11292882
585 // When the current thread state is NULL, PyThreadState_Get() issues a fatal
586 // error.
587 if (PyThreadState_GetDict()) {
588 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
589 if (sys_module_dict.IsValid()) {
590 if (m_saved_stdin.IsValid()) {
591 sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
592 m_saved_stdin.Reset();
593 }
594 if (m_saved_stdout.IsValid()) {
595 sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
596 m_saved_stdout.Reset();
597 }
598 if (m_saved_stderr.IsValid()) {
599 sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
600 m_saved_stderr.Reset();
601 }
602 }
603 }
604
605 m_session_is_active = false;
606}
607
608bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp,
609 const char *py_name,
610 PythonObject &save_file,
611 const char *mode) {
612 if (!file_sp || !*file_sp) {
613 save_file.Reset();
614 return false;
615 }
616 File &file = *file_sp;
617
618 // Flush the file before giving it to python to avoid interleaved output.
619 file.Flush();
620
621 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
622
623 auto new_file = PythonFile::FromFile(file, mode);
624 if (!new_file) {
625 llvm::consumeError(new_file.takeError());
626 return false;
627 }
628
629 save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
630
631 sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
632 return true;
633}
634
635bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
636 FileSP in_sp, FileSP out_sp,
637 FileSP err_sp) {
638 // If we have already entered the session, without having officially 'left'
639 // it, then there is no need to 'enter' it again.
640 Log *log = GetLog(LLDBLog::Script);
641 if (m_session_is_active) {
642 LLDB_LOGF(do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%"
"x" ") session is already active, returning without doing anything"
, on_entry_flags); } while (0)
643 log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%"
"x" ") session is already active, returning without doing anything"
, on_entry_flags); } while (0)
644 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%"
"x" ") session is already active, returning without doing anything"
, on_entry_flags); } while (0)
645 ") session is already active, returning without doing anything",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%"
"x" ") session is already active, returning without doing anything"
, on_entry_flags); } while (0)
646 on_entry_flags)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%"
"x" ") session is already active, returning without doing anything"
, on_entry_flags); } while (0)
;
647 return false;
648 }
649
650 LLDB_LOGF(do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%"
"x" ")", on_entry_flags); } while (0)
651 log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%"
"x" ")", on_entry_flags); } while (0)
652 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%"
"x" ")", on_entry_flags); } while (0)
653 on_entry_flags)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%"
"x" ")", on_entry_flags); } while (0)
;
654
655 m_session_is_active = true;
656
657 StreamString run_string;
658
659 if (on_entry_flags & Locker::InitGlobals) {
660 run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64"l" "u",
661 m_dictionary_name.c_str(), m_debugger.GetID());
662 run_string.Printf(
663 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64"l" "u" ")",
664 m_debugger.GetID());
665 run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
666 run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
667 run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
668 run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
669 run_string.PutCString("')");
670 } else {
671 // If we aren't initing the globals, we should still always set the
672 // debugger (since that is always unique.)
673 run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64"l" "u",
674 m_dictionary_name.c_str(), m_debugger.GetID());
675 run_string.Printf(
676 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64"l" "u" ")",
677 m_debugger.GetID());
678 run_string.PutCString("')");
679 }
680
681 PyRun_SimpleString(run_string.GetData())PyRun_SimpleStringFlags(run_string.GetData(), __null);
682 run_string.Clear();
683
684 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
685 if (sys_module_dict.IsValid()) {
686 lldb::FileSP top_in_sp;
687 lldb::StreamFileSP top_out_sp, top_err_sp;
688 if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
689 m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
690 top_err_sp);
691
692 if (on_entry_flags & Locker::NoSTDIN) {
693 m_saved_stdin.Reset();
694 } else {
695 if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
696 if (top_in_sp)
697 SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
698 }
699 }
700
701 if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
702 if (top_out_sp)
703 SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w");
704 }
705
706 if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
707 if (top_err_sp)
708 SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w");
709 }
710 }
711
712 if (PyErr_Occurred())
713 PyErr_Clear();
714
715 return true;
716}
717
718PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
719 if (!m_main_module.IsValid())
720 m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__"));
721 return m_main_module;
722}
723
724PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
725 if (m_session_dict.IsValid())
726 return m_session_dict;
727
728 PythonObject &main_module = GetMainModule();
729 if (!main_module.IsValid())
730 return m_session_dict;
731
732 PythonDictionary main_dict(PyRefType::Borrowed,
733 PyModule_GetDict(main_module.get()));
734 if (!main_dict.IsValid())
735 return m_session_dict;
736
737 m_session_dict = unwrapIgnoringErrors(
738 As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
739 return m_session_dict;
740}
741
742PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
743 if (m_sys_module_dict.IsValid())
744 return m_sys_module_dict;
745 PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys"));
746 m_sys_module_dict = sys_module.GetDictionary();
747 return m_sys_module_dict;
748}
749
750llvm::Expected<unsigned>
751ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
752 const llvm::StringRef &callable_name) {
753 if (callable_name.empty()) {
754 return llvm::createStringError(
755 llvm::inconvertibleErrorCode(),
756 "called with empty callable name.");
757 }
758 Locker py_lock(this, Locker::AcquireLock |
759 Locker::InitSession |
760 Locker::NoSTDIN);
761 auto dict = PythonModule::MainModule()
762 .ResolveName<PythonDictionary>(m_dictionary_name);
763 auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
764 callable_name, dict);
765 if (!pfunc.IsAllocated()) {
766 return llvm::createStringError(
767 llvm::inconvertibleErrorCode(),
768 "can't find callable: %s", callable_name.str().c_str());
769 }
770 llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
771 if (!arg_info)
772 return arg_info.takeError();
773 return arg_info.get().max_positional_args;
774}
775
776static std::string GenerateUniqueName(const char *base_name_wanted,
777 uint32_t &functions_counter,
778 const void *name_token = nullptr) {
779 StreamString sstr;
780
781 if (!base_name_wanted)
782 return std::string();
783
784 if (!name_token)
785 sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
786 else
787 sstr.Printf("%s_%p", base_name_wanted, name_token);
788
789 return std::string(sstr.GetString());
790}
791
792bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
793 if (m_run_one_line_function.IsValid())
794 return true;
795
796 PythonObject module(PyRefType::Borrowed,
797 PyImport_AddModule("lldb.embedded_interpreter"));
798 if (!module.IsValid())
799 return false;
800
801 PythonDictionary module_dict(PyRefType::Borrowed,
802 PyModule_GetDict(module.get()));
803 if (!module_dict.IsValid())
804 return false;
805
806 m_run_one_line_function =
807 module_dict.GetItemForKey(PythonString("run_one_line"));
808 m_run_one_line_str_global =
809 module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
810 return m_run_one_line_function.IsValid();
811}
812
813bool ScriptInterpreterPythonImpl::ExecuteOneLine(
814 llvm::StringRef command, CommandReturnObject *result,
815 const ExecuteScriptOptions &options) {
816 std::string command_str = command.str();
817
818 if (!m_valid_session)
819 return false;
820
821 if (!command.empty()) {
822 // We want to call run_one_line, passing in the dictionary and the command
823 // string. We cannot do this through PyRun_SimpleString here because the
824 // command string may contain escaped characters, and putting it inside
825 // another string to pass to PyRun_SimpleString messes up the escaping. So
826 // we use the following more complicated method to pass the command string
827 // directly down to Python.
828 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
829 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
830 options.GetEnableIO(), m_debugger, result);
831 if (!io_redirect_or_error) {
832 if (result)
833 result->AppendErrorWithFormatv(
834 "failed to redirect I/O: {0}\n",
835 llvm::fmt_consume(io_redirect_or_error.takeError()));
836 else
837 llvm::consumeError(io_redirect_or_error.takeError());
838 return false;
839 }
840
841 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
842
843 bool success = false;
844 {
845 // WARNING! It's imperative that this RAII scope be as tight as
846 // possible. In particular, the scope must end *before* we try to join
847 // the read thread. The reason for this is that a pre-requisite for
848 // joining the read thread is that we close the write handle (to break
849 // the pipe and cause it to wake up and exit). But acquiring the GIL as
850 // below will redirect Python's stdio to use this same handle. If we
851 // close the handle while Python is still using it, bad things will
852 // happen.
853 Locker locker(
854 this,
855 Locker::AcquireLock | Locker::InitSession |
856 (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
857 ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
858 Locker::FreeAcquiredLock | Locker::TearDownSession,
859 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
860 io_redirect.GetErrorFile());
861
862 // Find the correct script interpreter dictionary in the main module.
863 PythonDictionary &session_dict = GetSessionDictionary();
864 if (session_dict.IsValid()) {
865 if (GetEmbeddedInterpreterModuleObjects()) {
866 if (PyCallable_Check(m_run_one_line_function.get())) {
867 PythonObject pargs(
868 PyRefType::Owned,
869 Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
870 if (pargs.IsValid()) {
871 PythonObject return_value(
872 PyRefType::Owned,
873 PyObject_CallObject(m_run_one_line_function.get(),
874 pargs.get()));
875 if (return_value.IsValid())
876 success = true;
877 else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
878 PyErr_Print();
879 PyErr_Clear();
880 }
881 }
882 }
883 }
884 }
885
886 io_redirect.Flush();
887 }
888
889 if (success)
890 return true;
891
892 // The one-liner failed. Append the error message.
893 if (result) {
894 result->AppendErrorWithFormat(
895 "python failed attempting to evaluate '%s'\n", command_str.c_str());
896 }
897 return false;
898 }
899
900 if (result)
901 result->AppendError("empty command passed to python\n");
902 return false;
903}
904
905void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
906 LLDB_SCOPED_TIMER()static ::lldb_private::Timer::Category _cat(__PRETTY_FUNCTION__
); ::lldb_private::Timer _scoped_timer(_cat, "%s", __PRETTY_FUNCTION__
)
;
907
908 Debugger &debugger = m_debugger;
909
910 // At the moment, the only time the debugger does not have an input file
911 // handle is when this is called directly from Python, in which case it is
912 // both dangerous and unnecessary (not to mention confusing) to try to embed
913 // a running interpreter loop inside the already running Python interpreter
914 // loop, so we won't do it.
915
916 if (!debugger.GetInputFile().IsValid())
917 return;
918
919 IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
920 if (io_handler_sp) {
921 debugger.RunIOHandlerAsync(io_handler_sp);
922 }
923}
924
925bool ScriptInterpreterPythonImpl::Interrupt() {
926#if LLDB_USE_PYTHON_SET_INTERRUPT(3 == 3 && 9 >= 2) || (3 > 3)
927 // If the interpreter isn't evaluating any Python at the moment then return
928 // false to signal that this function didn't handle the interrupt and the
929 // next component should try handling it.
930 if (!IsExecutingPython())
931 return false;
932
933 // Tell Python that it should pretend to have received a SIGINT.
934 PyErr_SetInterrupt();
935 // PyErr_SetInterrupt has no way to return an error so we can only pretend the
936 // signal got successfully handled and return true.
937 // Python 3.10 introduces PyErr_SetInterruptEx that could return an error, but
938 // the error handling is limited to checking the arguments which would be
939 // just our (hardcoded) input signal code SIGINT, so that's not useful at all.
940 return true;
941#else
942 Log *log = GetLog(LLDBLog::Script);
943
944 if (IsExecutingPython()) {
945 PyThreadState *state = PyThreadState_GET()PyThreadState_Get();
946 if (!state)
947 state = GetThreadState();
948 if (state) {
949 long tid = state->thread_id;
950 PyThreadState_Swap(state);
951 int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
952 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ScriptInterpreterPythonImpl::Interrupt() sending "
"PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...", tid
, num_threads); } while (0)
953 "ScriptInterpreterPythonImpl::Interrupt() sending "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ScriptInterpreterPythonImpl::Interrupt() sending "
"PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...", tid
, num_threads); } while (0)
954 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ScriptInterpreterPythonImpl::Interrupt() sending "
"PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...", tid
, num_threads); } while (0)
955 tid, num_threads)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ScriptInterpreterPythonImpl::Interrupt() sending "
"PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...", tid
, num_threads); } while (0)
;
956 return true;
957 }
958 }
959 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ScriptInterpreterPythonImpl::Interrupt() python code not running, "
"can't interrupt"); } while (0)
960 "ScriptInterpreterPythonImpl::Interrupt() python code not running, "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ScriptInterpreterPythonImpl::Interrupt() python code not running, "
"can't interrupt"); } while (0)
961 "can't interrupt")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ScriptInterpreterPythonImpl::Interrupt() python code not running, "
"can't interrupt"); } while (0)
;
962 return false;
963#endif
964}
965
966bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
967 llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
968 void *ret_value, const ExecuteScriptOptions &options) {
969
970 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
971 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
972 options.GetEnableIO(), m_debugger, /*result=*/nullptr);
973
974 if (!io_redirect_or_error) {
975 llvm::consumeError(io_redirect_or_error.takeError());
976 return false;
977 }
978
979 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
980
981 Locker locker(this,
982 Locker::AcquireLock | Locker::InitSession |
983 (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
984 Locker::NoSTDIN,
985 Locker::FreeAcquiredLock | Locker::TearDownSession,
986 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
987 io_redirect.GetErrorFile());
988
989 PythonModule &main_module = GetMainModule();
990 PythonDictionary globals = main_module.GetDictionary();
991
992 PythonDictionary locals = GetSessionDictionary();
993 if (!locals.IsValid())
994 locals = unwrapIgnoringErrors(
995 As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
996 if (!locals.IsValid())
997 locals = globals;
998
999 Expected<PythonObject> maybe_py_return =
1000 runStringOneLine(in_string, globals, locals);
1001
1002 if (!maybe_py_return) {
1003 llvm::handleAllErrors(
1004 maybe_py_return.takeError(),
1005 [&](PythonException &E) {
1006 E.Restore();
1007 if (options.GetMaskoutErrors()) {
1008 if (E.Matches(PyExc_SyntaxError)) {
1009 PyErr_Print();
1010 }
1011 PyErr_Clear();
1012 }
1013 },
1014 [](const llvm::ErrorInfoBase &E) {});
1015 return false;
1016 }
1017
1018 PythonObject py_return = std::move(maybe_py_return.get());
1019 assert(py_return.IsValid())(static_cast <bool> (py_return.IsValid()) ? void (0) : __assert_fail
("py_return.IsValid()", "lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp"
, 1019, __extension__ __PRETTY_FUNCTION__))
;
1020
1021 switch (return_type) {
1022 case eScriptReturnTypeCharPtr: // "char *"
1023 {
1024 const char format[3] = "s#";
1025 return PyArg_Parse(py_return.get(), format, (char **)ret_value);
1026 }
1027 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
1028 // Py_None
1029 {
1030 const char format[3] = "z";
1031 return PyArg_Parse(py_return.get(), format, (char **)ret_value);
1032 }
1033 case eScriptReturnTypeBool: {
1034 const char format[2] = "b";
1035 return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
1036 }
1037 case eScriptReturnTypeShortInt: {
1038 const char format[2] = "h";
1039 return PyArg_Parse(py_return.get(), format, (short *)ret_value);
1040 }
1041 case eScriptReturnTypeShortIntUnsigned: {
1042 const char format[2] = "H";
1043 return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
1044 }
1045 case eScriptReturnTypeInt: {
1046 const char format[2] = "i";
1047 return PyArg_Parse(py_return.get(), format, (int *)ret_value);
1048 }
1049 case eScriptReturnTypeIntUnsigned: {
1050 const char format[2] = "I";
1051 return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
1052 }
1053 case eScriptReturnTypeLongInt: {
1054 const char format[2] = "l";
1055 return PyArg_Parse(py_return.get(), format, (long *)ret_value);
1056 }
1057 case eScriptReturnTypeLongIntUnsigned: {
1058 const char format[2] = "k";
1059 return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
1060 }
1061 case eScriptReturnTypeLongLong: {
1062 const char format[2] = "L";
1063 return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
1064 }
1065 case eScriptReturnTypeLongLongUnsigned: {
1066 const char format[2] = "K";
1067 return PyArg_Parse(py_return.get(), format,
1068 (unsigned long long *)ret_value);
1069 }
1070 case eScriptReturnTypeFloat: {
1071 const char format[2] = "f";
1072 return PyArg_Parse(py_return.get(), format, (float *)ret_value);
1073 }
1074 case eScriptReturnTypeDouble: {
1075 const char format[2] = "d";
1076 return PyArg_Parse(py_return.get(), format, (double *)ret_value);
1077 }
1078 case eScriptReturnTypeChar: {
1079 const char format[2] = "c";
1080 return PyArg_Parse(py_return.get(), format, (char *)ret_value);
1081 }
1082 case eScriptReturnTypeOpaqueObject: {
1083 *((PyObject **)ret_value) = py_return.release();
1084 return true;
1085 }
1086 }
1087 llvm_unreachable("Fully covered switch!")::llvm::llvm_unreachable_internal("Fully covered switch!", "lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp"
, 1087)
;
1088}
1089
1090Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1091 const char *in_string, const ExecuteScriptOptions &options) {
1092
1093 if (in_string == nullptr)
1094 return Status();
1095
1096 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1097 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1098 options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1099
1100 if (!io_redirect_or_error)
1101 return Status(io_redirect_or_error.takeError());
1102
1103 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1104
1105 Locker locker(this,
1106 Locker::AcquireLock | Locker::InitSession |
1107 (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1108 Locker::NoSTDIN,
1109 Locker::FreeAcquiredLock | Locker::TearDownSession,
1110 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1111 io_redirect.GetErrorFile());
1112
1113 PythonModule &main_module = GetMainModule();
1114 PythonDictionary globals = main_module.GetDictionary();
1115
1116 PythonDictionary locals = GetSessionDictionary();
1117 if (!locals.IsValid())
1118 locals = unwrapIgnoringErrors(
1119 As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1120 if (!locals.IsValid())
1121 locals = globals;
1122
1123 Expected<PythonObject> return_value =
1124 runStringMultiLine(in_string, globals, locals);
1125
1126 if (!return_value) {
1127 llvm::Error error =
1128 llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
1129 llvm::Error error = llvm::createStringError(
1130 llvm::inconvertibleErrorCode(), E.ReadBacktrace());
1131 if (!options.GetMaskoutErrors())
1132 E.Restore();
1133 return error;
1134 });
1135 return Status(std::move(error));
1136 }
1137
1138 return Status();
1139}
1140
1141void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1142 std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1143 CommandReturnObject &result) {
1144 m_active_io_handler = eIOHandlerBreakpoint;
1145 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1146 " ", *this, &bp_options_vec);
1147}
1148
1149void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1150 WatchpointOptions *wp_options, CommandReturnObject &result) {
1151 m_active_io_handler = eIOHandlerWatchpoint;
1152 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1153 " ", *this, wp_options);
1154}
1155
1156Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1157 BreakpointOptions &bp_options, const char *function_name,
1158 StructuredData::ObjectSP extra_args_sp) {
1159 Status error;
1160 // For now just cons up a oneliner that calls the provided function.
1161 std::string oneliner("return ");
1162 oneliner += function_name;
1163
1164 llvm::Expected<unsigned> maybe_args =
1165 GetMaxPositionalArgumentsForCallable(function_name);
1166 if (!maybe_args) {
1167 error.SetErrorStringWithFormat(
1168 "could not get num args: %s",
1169 llvm::toString(maybe_args.takeError()).c_str());
1170 return error;
1171 }
1172 size_t max_args = *maybe_args;
1173
1174 bool uses_extra_args = false;
1175 if (max_args >= 4) {
1176 uses_extra_args = true;
1177 oneliner += "(frame, bp_loc, extra_args, internal_dict)";
1178 } else if (max_args >= 3) {
1179 if (extra_args_sp) {
1180 error.SetErrorString("cannot pass extra_args to a three argument callback"
1181 );
1182 return error;
1183 }
1184 uses_extra_args = false;
1185 oneliner += "(frame, bp_loc, internal_dict)";
1186 } else {
1187 error.SetErrorStringWithFormat("expected 3 or 4 argument "
1188 "function, %s can only take %zu",
1189 function_name, max_args);
1190 return error;
1191 }
1192
1193 SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp,
1194 uses_extra_args);
1195 return error;
1196}
1197
1198Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1199 BreakpointOptions &bp_options,
1200 std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
1201 Status error;
1202 error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1203 cmd_data_up->script_source,
1204 false);
1205 if (error.Fail()) {
1206 return error;
1207 }
1208 auto baton_sp =
1209 std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1210 bp_options.SetCallback(
1211 ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1212 return error;
1213}
1214
1215Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1216 BreakpointOptions &bp_options, const char *command_body_text) {
1217 return SetBreakpointCommandCallback(bp_options, command_body_text, {},false);
1218}
1219
1220// Set a Python one-liner as the callback for the breakpoint.
1221Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1222 BreakpointOptions &bp_options, const char *command_body_text,
1223 StructuredData::ObjectSP extra_args_sp, bool uses_extra_args) {
1224 auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1225 // Split the command_body_text into lines, and pass that to
1226 // GenerateBreakpointCommandCallbackData. That will wrap the body in an
1227 // auto-generated function, and return the function name in script_source.
1228 // That is what the callback will actually invoke.
1229
1230 data_up->user_source.SplitIntoLines(command_body_text);
1231 Status error = GenerateBreakpointCommandCallbackData(data_up->user_source,
1232 data_up->script_source,
1233 uses_extra_args);
1234 if (error.Success()) {
1235 auto baton_sp =
1236 std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1237 bp_options.SetCallback(
1238 ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1239 return error;
1240 }
1241 return error;
1242}
1243
1244// Set a Python one-liner as the callback for the watchpoint.
1245void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1246 WatchpointOptions *wp_options, const char *oneliner) {
1247 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
1248
1249 // It's necessary to set both user_source and script_source to the oneliner.
1250 // The former is used to generate callback description (as in watchpoint
1251 // command list) while the latter is used for Python to interpret during the
1252 // actual callback.
1253
1254 data_up->user_source.AppendString(oneliner);
1255 data_up->script_source.assign(oneliner);
1256
1257 if (GenerateWatchpointCommandCallbackData(data_up->user_source,
1258 data_up->script_source)) {
1259 auto baton_sp =
1260 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
1261 wp_options->SetCallback(
1262 ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
1263 }
1264}
1265
1266Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1267 StringList &function_def) {
1268 // Convert StringList to one long, newline delimited, const char *.
1269 std::string function_def_string(function_def.CopyList());
1270
1271 Status error = ExecuteMultipleLines(
1272 function_def_string.c_str(),
1273 ExecuteScriptOptions().SetEnableIO(false));
1274 return error;
1275}
1276
1277Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature,
1278 const StringList &input) {
1279 Status error;
1280 int num_lines = input.GetSize();
1281 if (num_lines == 0) {
1282 error.SetErrorString("No input data.");
1283 return error;
1284 }
1285
1286 if (!signature || *signature == 0) {
1287 error.SetErrorString("No output function name.");
1288 return error;
1289 }
1290
1291 StreamString sstr;
1292 StringList auto_generated_function;
1293 auto_generated_function.AppendString(signature);
1294 auto_generated_function.AppendString(
1295 " global_dict = globals()"); // Grab the global dictionary
1296 auto_generated_function.AppendString(
1297 " new_keys = internal_dict.keys()"); // Make a list of keys in the
1298 // session dict
1299 auto_generated_function.AppendString(
1300 " old_keys = global_dict.keys()"); // Save list of keys in global dict
1301 auto_generated_function.AppendString(
1302 " global_dict.update (internal_dict)"); // Add the session dictionary
1303 // to the
1304 // global dictionary.
1305
1306 // Wrap everything up inside the function, increasing the indentation.
1307
1308 auto_generated_function.AppendString(" if True:");
1309 for (int i = 0; i < num_lines; ++i) {
1310 sstr.Clear();
1311 sstr.Printf(" %s", input.GetStringAtIndex(i));
1312 auto_generated_function.AppendString(sstr.GetData());
1313 }
1314 auto_generated_function.AppendString(
1315 " for key in new_keys:"); // Iterate over all the keys from session
1316 // dict
1317 auto_generated_function.AppendString(
1318 " internal_dict[key] = global_dict[key]"); // Update session dict
1319 // values
1320 auto_generated_function.AppendString(
1321 " if key not in old_keys:"); // If key was not originally in
1322 // global dict
1323 auto_generated_function.AppendString(
1324 " del global_dict[key]"); // ...then remove key/value from
1325 // global dict
1326
1327 // Verify that the results are valid Python.
1328
1329 error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
1330
1331 return error;
1332}
1333
1334bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1335 StringList &user_input, std::string &output, const void *name_token) {
1336 static uint32_t num_created_functions = 0;
1337 user_input.RemoveBlankLines();
1338 StreamString sstr;
1339
1340 // Check to see if we have any data; if not, just return.
1341 if (user_input.GetSize() == 0)
1342 return false;
1343
1344 // Take what the user wrote, wrap it all up inside one big auto-generated
1345 // Python function, passing in the ValueObject as parameter to the function.
1346
1347 std::string auto_generated_function_name(
1348 GenerateUniqueName("lldb_autogen_python_type_print_func",
1349 num_created_functions, name_token));
1350 sstr.Printf("def %s (valobj, internal_dict):",
1351 auto_generated_function_name.c_str());
1352
1353 if (!GenerateFunction(sstr.GetData(), user_input).Success())
1354 return false;
1355
1356 // Store the name of the auto-generated function to be called.
1357 output.assign(auto_generated_function_name);
1358 return true;
1359}
1360
1361bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1362 StringList &user_input, std::string &output) {
1363 static uint32_t num_created_functions = 0;
1364 user_input.RemoveBlankLines();
1365 StreamString sstr;
1366
1367 // Check to see if we have any data; if not, just return.
1368 if (user_input.GetSize() == 0)
1369 return false;
1370
1371 std::string auto_generated_function_name(GenerateUniqueName(
1372 "lldb_autogen_python_cmd_alias_func", num_created_functions));
1373
1374 sstr.Printf("def %s (debugger, args, result, internal_dict):",
1375 auto_generated_function_name.c_str());
1376
1377 if (!GenerateFunction(sstr.GetData(), user_input).Success())
1378 return false;
1379
1380 // Store the name of the auto-generated function to be called.
1381 output.assign(auto_generated_function_name);
1382 return true;
1383}
1384
1385bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1386 StringList &user_input, std::string &output, const void *name_token) {
1387 static uint32_t num_created_classes = 0;
1388 user_input.RemoveBlankLines();
1389 int num_lines = user_input.GetSize();
1390 StreamString sstr;
1391
1392 // Check to see if we have any data; if not, just return.
1393 if (user_input.GetSize() == 0)
1394 return false;
1395
1396 // Wrap all user input into a Python class
1397
1398 std::string auto_generated_class_name(GenerateUniqueName(
1399 "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1400
1401 StringList auto_generated_class;
1402
1403 // Create the function name & definition string.
1404
1405 sstr.Printf("class %s:", auto_generated_class_name.c_str());
1406 auto_generated_class.AppendString(sstr.GetString());
1407
1408 // Wrap everything up inside the class, increasing the indentation. we don't
1409 // need to play any fancy indentation tricks here because there is no
1410 // surrounding code whose indentation we need to honor
1411 for (int i = 0; i < num_lines; ++i) {
1412 sstr.Clear();
1413 sstr.Printf(" %s", user_input.GetStringAtIndex(i));
1414 auto_generated_class.AppendString(sstr.GetString());
1415 }
1416
1417 // Verify that the results are valid Python. (even though the method is
1418 // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1419 // (TODO: rename that method to ExportDefinitionToInterpreter)
1420 if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
1421 return false;
1422
1423 // Store the name of the auto-generated class
1424
1425 output.assign(auto_generated_class_name);
1426 return true;
1427}
1428
1429StructuredData::GenericSP
1430ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
1431 if (class_name == nullptr || class_name[0] == '\0')
1432 return StructuredData::GenericSP();
1433
1434 Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1435 PythonObject ret_val = LLDBSWIGPython_CreateFrameRecognizer(
1436 class_name, m_dictionary_name.c_str());
1437
1438 return StructuredData::GenericSP(
1439 new StructuredPythonObject(std::move(ret_val)));
1440}
1441
1442lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
1443 const StructuredData::ObjectSP &os_plugin_object_sp,
1444 lldb::StackFrameSP frame_sp) {
1445 Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1446
1447 if (!os_plugin_object_sp)
1448 return ValueObjectListSP();
1449
1450 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1451 if (!generic)
1452 return nullptr;
1453
1454 PythonObject implementor(PyRefType::Borrowed,
1455 (PyObject *)generic->GetValue());
1456
1457 if (!implementor.IsAllocated())
1458 return ValueObjectListSP();
1459
1460 PythonObject py_return(
1461 PyRefType::Owned,
1462 LLDBSwigPython_GetRecognizedArguments(implementor.get(), frame_sp));
1463
1464 // if it fails, print the error but otherwise go on
1465 if (PyErr_Occurred()) {
1466 PyErr_Print();
1467 PyErr_Clear();
1468 }
1469 if (py_return.get()) {
1470 PythonList result_list(PyRefType::Borrowed, py_return.get());
1471 ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
1472 for (size_t i = 0; i < result_list.GetSize(); i++) {
1473 PyObject *item = result_list.GetItemAtIndex(i).get();
1474 lldb::SBValue *sb_value_ptr =
1475 (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
1476 auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
1477 if (valobj_sp)
1478 result->Append(valobj_sp);
1479 }
1480 return result;
1481 }
1482 return ValueObjectListSP();
1483}
1484
1485StructuredData::GenericSP
1486ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject(
1487 const char *class_name, lldb::ProcessSP process_sp) {
1488 if (class_name == nullptr || class_name[0] == '\0')
1489 return StructuredData::GenericSP();
1490
1491 if (!process_sp)
1492 return StructuredData::GenericSP();
1493
1494 Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1495 PythonObject ret_val = LLDBSWIGPythonCreateOSPlugin(
1496 class_name, m_dictionary_name.c_str(), process_sp);
1497
1498 return StructuredData::GenericSP(
1499 new StructuredPythonObject(std::move(ret_val)));
1500}
1501
1502StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo(
1503 StructuredData::ObjectSP os_plugin_object_sp) {
1504 Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1505
1506 static char callee_name[] = "get_register_info";
1507
1508 if (!os_plugin_object_sp)
1509 return StructuredData::DictionarySP();
1510
1511 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1512 if (!generic)
1513 return nullptr;
1514
1515 PythonObject implementor(PyRefType::Borrowed,
1516 (PyObject *)generic->GetValue());
1517
1518 if (!implementor.IsAllocated())
1519 return StructuredData::DictionarySP();
1520
1521 PythonObject pmeth(PyRefType::Owned,
1522 PyObject_GetAttrString(implementor.get(), callee_name));
1523
1524 if (PyErr_Occurred())
1525 PyErr_Clear();
1526
1527 if (!pmeth.IsAllocated())
1528 return StructuredData::DictionarySP();
1529
1530 if (PyCallable_Check(pmeth.get()) == 0) {
1531 if (PyErr_Occurred())
1532 PyErr_Clear();
1533
1534 return StructuredData::DictionarySP();
1535 }
1536
1537 if (PyErr_Occurred())
1538 PyErr_Clear();
1539
1540 // right now we know this function exists and is callable..
1541 PythonObject py_return(
1542 PyRefType::Owned,
1543 PyObject_CallMethod(implementor.get(), callee_name, nullptr));
1544
1545 // if it fails, print the error but otherwise go on
1546 if (PyErr_Occurred()) {
1547 PyErr_Print();
1548 PyErr_Clear();
1549 }
1550 if (py_return.get()) {
1551 PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1552 return result_dict.CreateStructuredDictionary();
1553 }
1554 return StructuredData::DictionarySP();
1555}
1556
1557StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo(
1558 StructuredData::ObjectSP os_plugin_object_sp) {
1559 Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1560
1561 static char callee_name[] = "get_thread_info";
1562
1563 if (!os_plugin_object_sp)
1564 return StructuredData::ArraySP();
1565
1566 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1567 if (!generic)
1568 return nullptr;
1569
1570 PythonObject implementor(PyRefType::Borrowed,
1571 (PyObject *)generic->GetValue());
1572
1573 if (!implementor.IsAllocated())
1574 return StructuredData::ArraySP();
1575
1576 PythonObject pmeth(PyRefType::Owned,
1577 PyObject_GetAttrString(implementor.get(), callee_name));
1578
1579 if (PyErr_Occurred())
1580 PyErr_Clear();
1581
1582 if (!pmeth.IsAllocated())
1583 return StructuredData::ArraySP();
1584
1585 if (PyCallable_Check(pmeth.get()) == 0) {
1586 if (PyErr_Occurred())
1587 PyErr_Clear();
1588
1589 return StructuredData::ArraySP();
1590 }
1591
1592 if (PyErr_Occurred())
1593 PyErr_Clear();
1594
1595 // right now we know this function exists and is callable..
1596 PythonObject py_return(
1597 PyRefType::Owned,
1598 PyObject_CallMethod(implementor.get(), callee_name, nullptr));
1599
1600 // if it fails, print the error but otherwise go on
1601 if (PyErr_Occurred()) {
1602 PyErr_Print();
1603 PyErr_Clear();
1604 }
1605
1606 if (py_return.get()) {
1607 PythonList result_list(PyRefType::Borrowed, py_return.get());
1608 return result_list.CreateStructuredArray();
1609 }
1610 return StructuredData::ArraySP();
1611}
1612
1613StructuredData::StringSP
1614ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData(
1615 StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
1616 Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1617
1618 static char callee_name[] = "get_register_data";
1619 static char *param_format =
1620 const_cast<char *>(GetPythonValueFormatString(tid));
1621
1622 if (!os_plugin_object_sp)
1623 return StructuredData::StringSP();
1624
1625 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1626 if (!generic)
1627 return nullptr;
1628 PythonObject implementor(PyRefType::Borrowed,
1629 (PyObject *)generic->GetValue());
1630
1631 if (!implementor.IsAllocated())
1632 return StructuredData::StringSP();
1633
1634 PythonObject pmeth(PyRefType::Owned,
1635 PyObject_GetAttrString(implementor.get(), callee_name));
1636
1637 if (PyErr_Occurred())
1638 PyErr_Clear();
1639
1640 if (!pmeth.IsAllocated())
1641 return StructuredData::StringSP();
1642
1643 if (PyCallable_Check(pmeth.get()) == 0) {
1644 if (PyErr_Occurred())
1645 PyErr_Clear();
1646 return StructuredData::StringSP();
1647 }
1648
1649 if (PyErr_Occurred())
1650 PyErr_Clear();
1651
1652 // right now we know this function exists and is callable..
1653 PythonObject py_return(
1654 PyRefType::Owned,
1655 PyObject_CallMethod(implementor.get(), callee_name, param_format, tid));
1656
1657 // if it fails, print the error but otherwise go on
1658 if (PyErr_Occurred()) {
1659 PyErr_Print();
1660 PyErr_Clear();
1661 }
1662
1663 if (py_return.get()) {
1664 PythonBytes result(PyRefType::Borrowed, py_return.get());
1665 return result.CreateStructuredString();
1666 }
1667 return StructuredData::StringSP();
1668}
1669
1670StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread(
1671 StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
1672 lldb::addr_t context) {
1673 Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1674
1675 static char callee_name[] = "create_thread";
1676 std::string param_format;
1677 param_format += GetPythonValueFormatString(tid);
1678 param_format += GetPythonValueFormatString(context);
1679
1680 if (!os_plugin_object_sp)
1681 return StructuredData::DictionarySP();
1682
1683 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1684 if (!generic)
1685 return nullptr;
1686
1687 PythonObject implementor(PyRefType::Borrowed,
1688 (PyObject *)generic->GetValue());
1689
1690 if (!implementor.IsAllocated())
1691 return StructuredData::DictionarySP();
1692
1693 PythonObject pmeth(PyRefType::Owned,
1694 PyObject_GetAttrString(implementor.get(), callee_name));
1695
1696 if (PyErr_Occurred())
1697 PyErr_Clear();
1698
1699 if (!pmeth.IsAllocated())
1700 return StructuredData::DictionarySP();
1701
1702 if (PyCallable_Check(pmeth.get()) == 0) {
1703 if (PyErr_Occurred())
1704 PyErr_Clear();
1705 return StructuredData::DictionarySP();
1706 }
1707
1708 if (PyErr_Occurred())
1709 PyErr_Clear();
1710
1711 // right now we know this function exists and is callable..
1712 PythonObject py_return(PyRefType::Owned,
1713 PyObject_CallMethod(implementor.get(), callee_name,
1714 &param_format[0], tid, context));
1715
1716 // if it fails, print the error but otherwise go on
1717 if (PyErr_Occurred()) {
1718 PyErr_Print();
1719 PyErr_Clear();
1720 }
1721
1722 if (py_return.get()) {
1723 PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1724 return result_dict.CreateStructuredDictionary();
1725 }
1726 return StructuredData::DictionarySP();
1727}
1728
1729StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan(
1730 const char *class_name, const StructuredDataImpl &args_data,
1731 std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) {
1732 if (class_name == nullptr || class_name[0] == '\0')
1733 return StructuredData::ObjectSP();
1734
1735 if (!thread_plan_sp.get())
1736 return {};
1737
1738 Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
1739 ScriptInterpreterPythonImpl *python_interpreter =
1740 GetPythonInterpreter(debugger);
1741
1742 if (!python_interpreter)
1743 return {};
1744
1745 Locker py_lock(this,
1746 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1747 PythonObject ret_val = LLDBSwigPythonCreateScriptedThreadPlan(
1748 class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
1749 error_str, thread_plan_sp);
1750 if (!ret_val)
1751 return {};
1752
1753 return StructuredData::ObjectSP(
1754 new StructuredPythonObject(std::move(ret_val)));
1755}
1756
1757bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop(
1758 StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1759 bool explains_stop = true;
1760 StructuredData::Generic *generic = nullptr;
1761 if (implementor_sp)
1762 generic = implementor_sp->GetAsGeneric();
1763 if (generic) {
1764 Locker py_lock(this,
1765 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1766 explains_stop = LLDBSWIGPythonCallThreadPlan(
1767 generic->GetValue(), "explains_stop", event, script_error);
1768 if (script_error)
1769 return true;
1770 }
1771 return explains_stop;
1772}
1773
1774bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop(
1775 StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1776 bool should_stop = true;
1777 StructuredData::Generic *generic = nullptr;
1778 if (implementor_sp)
1779 generic = implementor_sp->GetAsGeneric();
1780 if (generic) {
1781 Locker py_lock(this,
1782 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1783 should_stop = LLDBSWIGPythonCallThreadPlan(
1784 generic->GetValue(), "should_stop", event, script_error);
1785 if (script_error)
1786 return true;
1787 }
1788 return should_stop;
1789}
1790
1791bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale(
1792 StructuredData::ObjectSP implementor_sp, bool &script_error) {
1793 bool is_stale = true;
1794 StructuredData::Generic *generic = nullptr;
1795 if (implementor_sp)
1796 generic = implementor_sp->GetAsGeneric();
1797 if (generic) {
1798 Locker py_lock(this,
1799 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1800 is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale",
1801 nullptr, script_error);
1802 if (script_error)
1803 return true;
1804 }
1805 return is_stale;
1806}
1807
1808lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState(
1809 StructuredData::ObjectSP implementor_sp, bool &script_error) {
1810 bool should_step = false;
1811 StructuredData::Generic *generic = nullptr;
1812 if (implementor_sp)
1813 generic = implementor_sp->GetAsGeneric();
1814 if (generic) {
1815 Locker py_lock(this,
1816 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1817 should_step = LLDBSWIGPythonCallThreadPlan(
1818 generic->GetValue(), "should_step", nullptr, script_error);
1819 if (script_error)
1820 should_step = true;
1821 }
1822 if (should_step)
1823 return lldb::eStateStepping;
1824 return lldb::eStateRunning;
1825}
1826
1827StructuredData::GenericSP
1828ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
1829 const char *class_name, const StructuredDataImpl &args_data,
1830 lldb::BreakpointSP &bkpt_sp) {
1831
1832 if (class_name == nullptr || class_name[0] == '\0')
1833 return StructuredData::GenericSP();
1834
1835 if (!bkpt_sp.get())
1836 return StructuredData::GenericSP();
1837
1838 Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
1839 ScriptInterpreterPythonImpl *python_interpreter =
1840 GetPythonInterpreter(debugger);
1841
1842 if (!python_interpreter)
1843 return StructuredData::GenericSP();
1844
1845 Locker py_lock(this,
1846 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1847
1848 PythonObject ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver(
1849 class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
1850 bkpt_sp);
1851
1852 return StructuredData::GenericSP(
1853 new StructuredPythonObject(std::move(ret_val)));
1854}
1855
1856bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
1857 StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
1858 bool should_continue = false;
1859
1860 if (implementor_sp) {
1861 Locker py_lock(this,
1862 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1863 should_continue = LLDBSwigPythonCallBreakpointResolver(
1864 implementor_sp->GetValue(), "__callback__", sym_ctx);
1865 if (PyErr_Occurred()) {
1866 PyErr_Print();
1867 PyErr_Clear();
1868 }
1869 }
1870 return should_continue;
1871}
1872
1873lldb::SearchDepth
1874ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
1875 StructuredData::GenericSP implementor_sp) {
1876 int depth_as_int = lldb::eSearchDepthModule;
1877 if (implementor_sp) {
1878 Locker py_lock(this,
1879 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1880 depth_as_int = LLDBSwigPythonCallBreakpointResolver(
1881 implementor_sp->GetValue(), "__get_depth__", nullptr);
1882 if (PyErr_Occurred()) {
1883 PyErr_Print();
1884 PyErr_Clear();
1885 }
1886 }
1887 if (depth_as_int == lldb::eSearchDepthInvalid)
1888 return lldb::eSearchDepthModule;
1889
1890 if (depth_as_int <= lldb::kLastSearchDepthKind)
1891 return (lldb::SearchDepth)depth_as_int;
1892 return lldb::eSearchDepthModule;
1893}
1894
1895StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
1896 TargetSP target_sp, const char *class_name,
1897 const StructuredDataImpl &args_data, Status &error) {
1898
1899 if (!target_sp) {
1900 error.SetErrorString("No target for scripted stop-hook.");
1901 return StructuredData::GenericSP();
1902 }
1903
1904 if (class_name == nullptr || class_name[0] == '\0') {
1905 error.SetErrorString("No class name for scripted stop-hook.");
1906 return StructuredData::GenericSP();
1907 }
1908
1909 ScriptInterpreterPythonImpl *python_interpreter =
1910 GetPythonInterpreter(m_debugger);
1911
1912 if (!python_interpreter) {
1913 error.SetErrorString("No script interpreter for scripted stop-hook.");
1914 return StructuredData::GenericSP();
1915 }
1916
1917 Locker py_lock(this,
1918 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1919
1920 PythonObject ret_val = LLDBSwigPythonCreateScriptedStopHook(
1921 target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
1922 args_data, error);
1923
1924 return StructuredData::GenericSP(
1925 new StructuredPythonObject(std::move(ret_val)));
1926}
1927
1928bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
1929 StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
1930 lldb::StreamSP stream_sp) {
1931 assert(implementor_sp &&(static_cast <bool> (implementor_sp && "can't call a stop hook with an invalid implementor"
) ? void (0) : __assert_fail ("implementor_sp && \"can't call a stop hook with an invalid implementor\""
, "lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp"
, 1932, __extension__ __PRETTY_FUNCTION__))
1932 "can't call a stop hook with an invalid implementor")(static_cast <bool> (implementor_sp && "can't call a stop hook with an invalid implementor"
) ? void (0) : __assert_fail ("implementor_sp && \"can't call a stop hook with an invalid implementor\""
, "lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp"
, 1932, __extension__ __PRETTY_FUNCTION__))
;
1933 assert(stream_sp && "can't call a stop hook with an invalid stream")(static_cast <bool> (stream_sp && "can't call a stop hook with an invalid stream"
) ? void (0) : __assert_fail ("stream_sp && \"can't call a stop hook with an invalid stream\""
, "lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp"
, 1933, __extension__ __PRETTY_FUNCTION__))
;
1934
1935 Locker py_lock(this,
1936 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1937
1938 lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
1939
1940 bool ret_val = LLDBSwigPythonStopHookCallHandleStop(
1941 implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
1942 return ret_val;
1943}
1944
1945StructuredData::ObjectSP
1946ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
1947 lldb_private::Status &error) {
1948 if (!FileSystem::Instance().Exists(file_spec)) {
1949 error.SetErrorString("no such file");
1950 return StructuredData::ObjectSP();
1951 }
1952
1953 StructuredData::ObjectSP module_sp;
1954
1955 LoadScriptOptions load_script_options =
1956 LoadScriptOptions().SetInitSession(true).SetSilent(false);
1957 if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1958 error, &module_sp))
1959 return module_sp;
1960
1961 return StructuredData::ObjectSP();
1962}
1963
1964StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
1965 StructuredData::ObjectSP plugin_module_sp, Target *target,
1966 const char *setting_name, lldb_private::Status &error) {
1967 if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
1968 return StructuredData::DictionarySP();
1969 StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
1970 if (!generic)
1971 return StructuredData::DictionarySP();
1972
1973 Locker py_lock(this,
1974 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1975 TargetSP target_sp(target->shared_from_this());
1976
1977 auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting(
1978 generic->GetValue(), setting_name, target_sp);
1979
1980 if (!setting)
1981 return StructuredData::DictionarySP();
1982
1983 PythonDictionary py_dict =
1984 unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
1985
1986 if (!py_dict)
1987 return StructuredData::DictionarySP();
1988
1989 return py_dict.CreateStructuredDictionary();
1990}
1991
1992StructuredData::ObjectSP
1993ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
1994 const char *class_name, lldb::ValueObjectSP valobj) {
1995 if (class_name == nullptr || class_name[0] == '\0')
1996 return StructuredData::ObjectSP();
1997
1998 if (!valobj.get())
1999 return StructuredData::ObjectSP();
2000
2001 ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
2002 Target *target = exe_ctx.GetTargetPtr();
2003
2004 if (!target)
2005 return StructuredData::ObjectSP();
2006
2007 Debugger &debugger = target->GetDebugger();
2008 ScriptInterpreterPythonImpl *python_interpreter =
2009 GetPythonInterpreter(debugger);
2010
2011 if (!python_interpreter)
2012 return StructuredData::ObjectSP();
2013
2014 Locker py_lock(this,
2015 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2016 PythonObject ret_val = LLDBSwigPythonCreateSyntheticProvider(
2017 class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
2018
2019 return StructuredData::ObjectSP(
2020 new StructuredPythonObject(std::move(ret_val)));
2021}
2022
2023StructuredData::GenericSP
2024ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
2025 DebuggerSP debugger_sp(m_debugger.shared_from_this());
2026
2027 if (class_name == nullptr || class_name[0] == '\0')
2028 return StructuredData::GenericSP();
2029
2030 if (!debugger_sp.get())
2031 return StructuredData::GenericSP();
2032
2033 Locker py_lock(this,
2034 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2035 PythonObject ret_val = LLDBSwigPythonCreateCommandObject(
2036 class_name, m_dictionary_name.c_str(), debugger_sp);
2037
2038 return StructuredData::GenericSP(
2039 new StructuredPythonObject(std::move(ret_val)));
2040}
2041
2042bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
2043 const char *oneliner, std::string &output, const void *name_token) {
2044 StringList input;
2045 input.SplitIntoLines(oneliner, strlen(oneliner));
2046 return GenerateTypeScriptFunction(input, output, name_token);
2047}
2048
2049bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
2050 const char *oneliner, std::string &output, const void *name_token) {
2051 StringList input;
2052 input.SplitIntoLines(oneliner, strlen(oneliner));
2053 return GenerateTypeSynthClass(input, output, name_token);
2054}
2055
2056Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
2057 StringList &user_input, std::string &output,
2058 bool has_extra_args) {
2059 static uint32_t num_created_functions = 0;
2060 user_input.RemoveBlankLines();
2061 StreamString sstr;
2062 Status error;
2063 if (user_input.GetSize() == 0) {
2064 error.SetErrorString("No input data.");
2065 return error;
2066 }
2067
2068 std::string auto_generated_function_name(GenerateUniqueName(
2069 "lldb_autogen_python_bp_callback_func_", num_created_functions));
2070 if (has_extra_args)
2071 sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
2072 auto_generated_function_name.c_str());
2073 else
2074 sstr.Printf("def %s (frame, bp_loc, internal_dict):",
2075 auto_generated_function_name.c_str());
2076
2077 error = GenerateFunction(sstr.GetData(), user_input);
2078 if (!error.Success())
2079 return error;
2080
2081 // Store the name of the auto-generated function to be called.
2082 output.assign(auto_generated_function_name);
2083 return error;
2084}
2085
2086bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
2087 StringList &user_input, std::string &output) {
2088 static uint32_t num_created_functions = 0;
2089 user_input.RemoveBlankLines();
2090 StreamString sstr;
2091
2092 if (user_input.GetSize() == 0)
2093 return false;
2094
2095 std::string auto_generated_function_name(GenerateUniqueName(
2096 "lldb_autogen_python_wp_callback_func_", num_created_functions));
2097 sstr.Printf("def %s (frame, wp, internal_dict):",
2098 auto_generated_function_name.c_str());
2099
2100 if (!GenerateFunction(sstr.GetData(), user_input).Success())
2101 return false;
2102
2103 // Store the name of the auto-generated function to be called.
2104 output.assign(auto_generated_function_name);
2105 return true;
2106}
2107
2108bool ScriptInterpreterPythonImpl::GetScriptedSummary(
2109 const char *python_function_name, lldb::ValueObjectSP valobj,
2110 StructuredData::ObjectSP &callee_wrapper_sp,
2111 const TypeSummaryOptions &options, std::string &retval) {
2112
2113 LLDB_SCOPED_TIMER()static ::lldb_private::Timer::Category _cat(__PRETTY_FUNCTION__
); ::lldb_private::Timer _scoped_timer(_cat, "%s", __PRETTY_FUNCTION__
)
;
2114
2115 if (!valobj.get()) {
2116 retval.assign("<no object>");
2117 return false;
2118 }
2119
2120 void *old_callee = nullptr;
2121 StructuredData::Generic *generic = nullptr;
2122 if (callee_wrapper_sp) {
2123 generic = callee_wrapper_sp->GetAsGeneric();
2124 if (generic)
2125 old_callee = generic->GetValue();
2126 }
2127 void *new_callee = old_callee;
2128
2129 bool ret_val;
2130 if (python_function_name && *python_function_name) {
2131 {
2132 Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
2133 Locker::NoSTDIN);
2134 {
2135 TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
2136
2137 static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
2138 Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
2139 ret_val = LLDBSwigPythonCallTypeScript(
2140 python_function_name, GetSessionDictionary().get(), valobj,
2141 &new_callee, options_sp, retval);
2142 }
2143 }
2144 } else {
2145 retval.assign("<no function name>");
2146 return false;
2147 }
2148
2149 if (new_callee && old_callee != new_callee) {
2150 Locker py_lock(this,
2151 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2152 callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
2153 PythonObject(PyRefType::Borrowed, static_cast<PyObject *>(new_callee)));
2154 }
2155
2156 return ret_val;
2157}
2158
2159bool ScriptInterpreterPythonImpl::FormatterCallbackFunction(
2160 const char *python_function_name, TypeImplSP type_impl_sp) {
2161 Locker py_lock(this,
2162 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2163 return LLDBSwigPythonFormatterCallbackFunction(
2164 python_function_name, m_dictionary_name.c_str(), type_impl_sp);
2165}
2166
2167bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
2168 void *baton, StoppointCallbackContext *context, user_id_t break_id,
2169 user_id_t break_loc_id) {
2170 CommandDataPython *bp_option_data = (CommandDataPython *)baton;
2171 const char *python_function_name = bp_option_data->script_source.c_str();
2172
2173 if (!context)
2174 return true;
2175
2176 ExecutionContext exe_ctx(context->exe_ctx_ref);
2177 Target *target = exe_ctx.GetTargetPtr();
2178
2179 if (!target)
2180 return true;
2181
2182 Debugger &debugger = target->GetDebugger();
2183 ScriptInterpreterPythonImpl *python_interpreter =
2184 GetPythonInterpreter(debugger);
2185
2186 if (!python_interpreter)
2187 return true;
2188
2189 if (python_function_name && python_function_name[0]) {
2190 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2191 BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2192 if (breakpoint_sp) {
2193 const BreakpointLocationSP bp_loc_sp(
2194 breakpoint_sp->FindLocationByID(break_loc_id));
2195
2196 if (stop_frame_sp && bp_loc_sp) {
2197 bool ret_val = true;
2198 {
2199 Locker py_lock(python_interpreter, Locker::AcquireLock |
2200 Locker::InitSession |
2201 Locker::NoSTDIN);
2202 Expected<bool> maybe_ret_val =
2203 LLDBSwigPythonBreakpointCallbackFunction(
2204 python_function_name,
2205 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2206 bp_loc_sp, bp_option_data->m_extra_args);
2207
2208 if (!maybe_ret_val) {
2209
2210 llvm::handleAllErrors(
2211 maybe_ret_val.takeError(),
2212 [&](PythonException &E) {
2213 debugger.GetErrorStream() << E.ReadBacktrace();
2214 },
2215 [&](const llvm::ErrorInfoBase &E) {
2216 debugger.GetErrorStream() << E.message();
2217 });
2218
2219 } else {
2220 ret_val = maybe_ret_val.get();
2221 }
2222 }
2223 return ret_val;
2224 }
2225 }
2226 }
2227 // We currently always true so we stop in case anything goes wrong when
2228 // trying to call the script function
2229 return true;
2230}
2231
2232bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
2233 void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2234 WatchpointOptions::CommandData *wp_option_data =
2235 (WatchpointOptions::CommandData *)baton;
2236 const char *python_function_name = wp_option_data->script_source.c_str();
2237
2238 if (!context)
2239 return true;
2240
2241 ExecutionContext exe_ctx(context->exe_ctx_ref);
2242 Target *target = exe_ctx.GetTargetPtr();
2243
2244 if (!target)
2245 return true;
2246
2247 Debugger &debugger = target->GetDebugger();
2248 ScriptInterpreterPythonImpl *python_interpreter =
2249 GetPythonInterpreter(debugger);
2250
2251 if (!python_interpreter)
2252 return true;
2253
2254 if (python_function_name && python_function_name[0]) {
2255 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2256 WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2257 if (wp_sp) {
2258 if (stop_frame_sp && wp_sp) {
2259 bool ret_val = true;
2260 {
2261 Locker py_lock(python_interpreter, Locker::AcquireLock |
2262 Locker::InitSession |
2263 Locker::NoSTDIN);
2264 ret_val = LLDBSwigPythonWatchpointCallbackFunction(
2265 python_function_name,
2266 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2267 wp_sp);
2268 }
2269 return ret_val;
2270 }
2271 }
2272 }
2273 // We currently always true so we stop in case anything goes wrong when
2274 // trying to call the script function
2275 return true;
2276}
2277
2278size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2279 const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
2280 if (!implementor_sp)
2281 return 0;
2282 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2283 if (!generic)
2284 return 0;
2285 auto *implementor = static_cast<PyObject *>(generic->GetValue());
2286 if (!implementor)
2287 return 0;
2288
2289 size_t ret_val = 0;
2290
2291 {
2292 Locker py_lock(this,
2293 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2294 ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max);
2295 }
2296
2297 return ret_val;
2298}
2299
2300lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
2301 const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
2302 if (!implementor_sp)
2303 return lldb::ValueObjectSP();
2304
2305 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2306 if (!generic)
2307 return lldb::ValueObjectSP();
2308 auto *implementor = static_cast<PyObject *>(generic->GetValue());
2309 if (!implementor)
2310 return lldb::ValueObjectSP();
2311
2312 lldb::ValueObjectSP ret_val;
2313 {
2314 Locker py_lock(this,
2315 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2316 PyObject *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx);
2317 if (child_ptr != nullptr && child_ptr != Py_None(&_Py_NoneStruct)) {
2318 lldb::SBValue *sb_value_ptr =
2319 (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2320 if (sb_value_ptr == nullptr)
2321 Py_XDECREF(child_ptr)_Py_XDECREF(((PyObject*)(child_ptr)));
2322 else
2323 ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2324 } else {
2325 Py_XDECREF(child_ptr)_Py_XDECREF(((PyObject*)(child_ptr)));
2326 }
2327 }
2328
2329 return ret_val;
2330}
2331
2332int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2333 const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
2334 if (!implementor_sp)
2335 return UINT32_MAX(4294967295U);
2336
2337 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2338 if (!generic)
2339 return UINT32_MAX(4294967295U);
2340 auto *implementor = static_cast<PyObject *>(generic->GetValue());
2341 if (!implementor)
2342 return UINT32_MAX(4294967295U);
2343
2344 int ret_val = UINT32_MAX(4294967295U);
2345
2346 {
2347 Locker py_lock(this,
2348 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2349 ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
2350 }
2351
2352 return ret_val;
2353}
2354
2355bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2356 const StructuredData::ObjectSP &implementor_sp) {
2357 bool ret_val = false;
2358
2359 if (!implementor_sp)
2360 return ret_val;
2361
2362 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2363 if (!generic)
2364 return ret_val;
2365 auto *implementor = static_cast<PyObject *>(generic->GetValue());
2366 if (!implementor)
2367 return ret_val;
2368
2369 {
2370 Locker py_lock(this,
2371 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2372 ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor);
2373 }
2374
2375 return ret_val;
2376}
2377
2378bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2379 const StructuredData::ObjectSP &implementor_sp) {
2380 bool ret_val = false;
2381
2382 if (!implementor_sp)
2383 return ret_val;
2384
2385 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2386 if (!generic)
2387 return ret_val;
2388 auto *implementor = static_cast<PyObject *>(generic->GetValue());
2389 if (!implementor)
2390 return ret_val;
2391
2392 {
2393 Locker py_lock(this,
2394 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2395 ret_val =
2396 LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor);
2397 }
2398
2399 return ret_val;
2400}
2401
2402lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
2403 const StructuredData::ObjectSP &implementor_sp) {
2404 lldb::ValueObjectSP ret_val(nullptr);
2405
2406 if (!implementor_sp)
2407 return ret_val;
2408
2409 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2410 if (!generic)
2411 return ret_val;
2412 auto *implementor = static_cast<PyObject *>(generic->GetValue());
2413 if (!implementor)
2414 return ret_val;
2415
2416 {
2417 Locker py_lock(this,
2418 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2419 PyObject *child_ptr =
2420 LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2421 if (child_ptr != nullptr && child_ptr != Py_None(&_Py_NoneStruct)) {
2422 lldb::SBValue *sb_value_ptr =
2423 (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2424 if (sb_value_ptr == nullptr)
2425 Py_XDECREF(child_ptr)_Py_XDECREF(((PyObject*)(child_ptr)));
2426 else
2427 ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2428 } else {
2429 Py_XDECREF(child_ptr)_Py_XDECREF(((PyObject*)(child_ptr)));
2430 }
2431 }
2432
2433 return ret_val;
2434}
2435
2436ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2437 const StructuredData::ObjectSP &implementor_sp) {
2438 Locker py_lock(this,
2439 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2440
2441 static char callee_name[] = "get_type_name";
2442
2443 ConstString ret_val;
2444 bool got_string = false;
2445 std::string buffer;
2446
2447 if (!implementor_sp)
2448 return ret_val;
2449
2450 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2451 if (!generic)
2452 return ret_val;
2453 PythonObject implementor(PyRefType::Borrowed,
2454 (PyObject *)generic->GetValue());
2455 if (!implementor.IsAllocated())
2456 return ret_val;
2457
2458 PythonObject pmeth(PyRefType::Owned,
2459 PyObject_GetAttrString(implementor.get(), callee_name));
2460
2461 if (PyErr_Occurred())
2462 PyErr_Clear();
2463
2464 if (!pmeth.IsAllocated())
2465 return ret_val;
2466
2467 if (PyCallable_Check(pmeth.get()) == 0) {
2468 if (PyErr_Occurred())
2469 PyErr_Clear();
2470 return ret_val;
2471 }
2472
2473 if (PyErr_Occurred())
2474 PyErr_Clear();
2475
2476 // right now we know this function exists and is callable..
2477 PythonObject py_return(
2478 PyRefType::Owned,
2479 PyObject_CallMethod(implementor.get(), callee_name, nullptr));
2480
2481 // if it fails, print the error but otherwise go on
2482 if (PyErr_Occurred()) {
2483 PyErr_Print();
2484 PyErr_Clear();
2485 }
2486
2487 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2488 PythonString py_string(PyRefType::Borrowed, py_return.get());
2489 llvm::StringRef return_data(py_string.GetString());
2490 if (!return_data.empty()) {
2491 buffer.assign(return_data.data(), return_data.size());
2492 got_string = true;
2493 }
2494 }
2495
2496 if (got_string)
2497 ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
2498
2499 return ret_val;
2500}
2501
2502bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2503 const char *impl_function, Process *process, std::string &output,
2504 Status &error) {
2505 bool ret_val;
2506 if (!process) {
2507 error.SetErrorString("no process");
2508 return false;
2509 }
2510 if (!impl_function || !impl_function[0]) {
2511 error.SetErrorString("no function to execute");
2512 return false;
2513 }
2514
2515 {
2516 Locker py_lock(this,
2517 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2518 ret_val = LLDBSWIGPythonRunScriptKeywordProcess(
2519 impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
2520 output);
2521 if (!ret_val)
2522 error.SetErrorString("python script evaluation failed");
2523 }
2524 return ret_val;
2525}
2526
2527bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2528 const char *impl_function, Thread *thread, std::string &output,
2529 Status &error) {
2530 if (!thread) {
2531 error.SetErrorString("no thread");
2532 return false;
2533 }
2534 if (!impl_function || !impl_function[0]) {
2535 error.SetErrorString("no function to execute");
2536 return false;
2537 }
2538
2539 Locker py_lock(this,
2540 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2541 if (llvm::Optional<std::string> result = LLDBSWIGPythonRunScriptKeywordThread(
2542 impl_function, m_dictionary_name.c_str(),
2543 thread->shared_from_this())) {
2544 output = std::move(*result);
2545 return true;
2546 }
2547 error.SetErrorString("python script evaluation failed");
2548 return false;
2549}
2550
2551bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2552 const char *impl_function, Target *target, std::string &output,
2553 Status &error) {
2554 bool ret_val;
2555 if (!target) {
2556 error.SetErrorString("no thread");
2557 return false;
2558 }
2559 if (!impl_function || !impl_function[0]) {
2560 error.SetErrorString("no function to execute");
2561 return false;
2562 }
2563
2564 {
2565 TargetSP target_sp(target->shared_from_this());
2566 Locker py_lock(this,
2567 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2568 ret_val = LLDBSWIGPythonRunScriptKeywordTarget(
2569 impl_function, m_dictionary_name.c_str(), target_sp, output);
2570 if (!ret_val)
2571 error.SetErrorString("python script evaluation failed");
2572 }
2573 return ret_val;
2574}
2575
2576bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2577 const char *impl_function, StackFrame *frame, std::string &output,
2578 Status &error) {
2579 if (!frame) {
2580 error.SetErrorString("no frame");
2581 return false;
2582 }
2583 if (!impl_function || !impl_function[0]) {
2584 error.SetErrorString("no function to execute");
2585 return false;
2586 }
2587
2588 Locker py_lock(this,
2589 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2590 if (llvm::Optional<std::string> result = LLDBSWIGPythonRunScriptKeywordFrame(
2591 impl_function, m_dictionary_name.c_str(),
2592 frame->shared_from_this())) {
2593 output = std::move(*result);
2594 return true;
2595 }
2596 error.SetErrorString("python script evaluation failed");
2597 return false;
2598}
2599
2600bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2601 const char *impl_function, ValueObject *value, std::string &output,
2602 Status &error) {
2603 bool ret_val;
2604 if (!value) {
2605 error.SetErrorString("no value");
2606 return false;
2607 }
2608 if (!impl_function || !impl_function[0]) {
2609 error.SetErrorString("no function to execute");
2610 return false;
2611 }
2612
2613 {
2614 Locker py_lock(this,
2615 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2616 ret_val = LLDBSWIGPythonRunScriptKeywordValue(
2617 impl_function, m_dictionary_name.c_str(), value->GetSP(), output);
2618 if (!ret_val)
2619 error.SetErrorString("python script evaluation failed");
2620 }
2621 return ret_val;
2622}
2623
2624uint64_t replace_all(std::string &str, const std::string &oldStr,
2625 const std::string &newStr) {
2626 size_t pos = 0;
2627 uint64_t matches = 0;
2628 while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2629 matches++;
2630 str.replace(pos, oldStr.length(), newStr);
2631 pos += newStr.length();
2632 }
2633 return matches;
2634}
2635
2636bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2637 const char *pathname, const LoadScriptOptions &options,
2638 lldb_private::Status &error, StructuredData::ObjectSP *module_sp,
2639 FileSpec extra_search_dir) {
2640 namespace fs = llvm::sys::fs;
2641 namespace path = llvm::sys::path;
2642
2643 ExecuteScriptOptions exc_options = ExecuteScriptOptions()
2644 .SetEnableIO(!options.GetSilent())
2645 .SetSetLLDBGlobals(false);
2646
2647 if (!pathname || !pathname[0]) {
2648 error.SetErrorString("empty path");
2649 return false;
2650 }
2651
2652 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2653 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2654 exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2655
2656 if (!io_redirect_or_error) {
2657 error = io_redirect_or_error.takeError();
2658 return false;
2659 }
2660
2661 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
2662
2663 // Before executing Python code, lock the GIL.
2664 Locker py_lock(this,
2665 Locker::AcquireLock |
2666 (options.GetInitSession() ? Locker::InitSession : 0) |
2667 Locker::NoSTDIN,
2668 Locker::FreeAcquiredLock |
2669 (options.GetInitSession() ? Locker::TearDownSession : 0),
2670 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2671 io_redirect.GetErrorFile());
2672
2673 auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2674 if (directory.empty()) {
2675 return llvm::make_error<llvm::StringError>(
2676 "invalid directory name", llvm::inconvertibleErrorCode());
2677 }
2678
2679 replace_all(directory, "\\", "\\\\");
2680 replace_all(directory, "'", "\\'");
2681
2682 // Make sure that Python has "directory" in the search path.
2683 StreamString command_stream;
2684 command_stream.Printf("if not (sys.path.__contains__('%s')):\n "
2685 "sys.path.insert(1,'%s');\n\n",
2686 directory.c_str(), directory.c_str());
2687 bool syspath_retval =
2688 ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
2689 if (!syspath_retval) {
2690 return llvm::make_error<llvm::StringError>(
2691 "Python sys.path handling failed", llvm::inconvertibleErrorCode());
2692 }
2693
2694 return llvm::Error::success();
2695 };
2696
2697 std::string module_name(pathname);
2698 bool possible_package = false;
2699
2700 if (extra_search_dir) {
2701 if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2702 error = std::move(e);
2703 return false;
2704 }
2705 } else {
2706 FileSpec module_file(pathname);
2707 FileSystem::Instance().Resolve(module_file);
2708
2709 fs::file_status st;
2710 std::error_code ec = status(module_file.GetPath(), st);
2711
2712 if (ec || st.type() == fs::file_type::status_error ||
2713 st.type() == fs::file_type::type_unknown ||
2714 st.type() == fs::file_type::file_not_found) {
2715 // if not a valid file of any sort, check if it might be a filename still
2716 // dot can't be used but / and \ can, and if either is found, reject
2717 if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2718 error.SetErrorStringWithFormatv("invalid pathname '{0}'", pathname);
2719 return false;
2720 }
2721 // Not a filename, probably a package of some sort, let it go through.
2722 possible_package = true;
2723 } else if (is_directory(st) || is_regular_file(st)) {
2724 if (module_file.GetDirectory().IsEmpty()) {
2725 error.SetErrorStringWithFormatv("invalid directory name '{0}'", pathname);
2726 return false;
2727 }
2728 if (llvm::Error e =
2729 ExtendSysPath(module_file.GetDirectory().GetCString())) {
2730 error = std::move(e);
2731 return false;
2732 }
2733 module_name = module_file.GetFilename().GetCString();
2734 } else {
2735 error.SetErrorString("no known way to import this module specification");
2736 return false;
2737 }
2738 }
2739
2740 // Strip .py or .pyc extension
2741 llvm::StringRef extension = llvm::sys::path::extension(module_name);
2742 if (!extension.empty()) {
2743 if (extension == ".py")
2744 module_name.resize(module_name.length() - 3);
2745 else if (extension == ".pyc")
2746 module_name.resize(module_name.length() - 4);
2747 }
2748
2749 if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2750 error.SetErrorStringWithFormat(
2751 "Python does not allow dots in module names: %s", module_name.c_str());
2752 return false;
2753 }
2754
2755 if (module_name.find('-') != llvm::StringRef::npos) {
2756 error.SetErrorStringWithFormat(
2757 "Python discourages dashes in module names: %s", module_name.c_str());
2758 return false;
2759 }
2760
2761 // Check if the module is already imported.
2762 StreamString command_stream;
2763 command_stream.Clear();
2764 command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
2765 bool does_contain = false;
2766 // This call will succeed if the module was ever imported in any Debugger in
2767 // the lifetime of the process in which this LLDB framework is living.
2768 const bool does_contain_executed = ExecuteOneLineWithReturn(
2769 command_stream.GetData(),
2770 ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options);
2771
2772 const bool was_imported_globally = does_contain_executed && does_contain;
2773 const bool was_imported_locally =
2774 GetSessionDictionary()
2775 .GetItemForKey(PythonString(module_name))
2776 .IsAllocated();
2777
2778 // now actually do the import
2779 command_stream.Clear();
2780
2781 if (was_imported_globally || was_imported_locally) {
2782 if (!was_imported_locally)
2783 command_stream.Printf("import %s ; reload_module(%s)",
2784 module_name.c_str(), module_name.c_str());
2785 else
2786 command_stream.Printf("reload_module(%s)", module_name.c_str());
2787 } else
2788 command_stream.Printf("import %s", module_name.c_str());
2789
2790 error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
2791 if (error.Fail())
2792 return false;
2793
2794 // if we are here, everything worked
2795 // call __lldb_init_module(debugger,dict)
2796 if (!LLDBSwigPythonCallModuleInit(module_name.c_str(),
2797 m_dictionary_name.c_str(),
2798 m_debugger.shared_from_this())) {
2799 error.SetErrorString("calling __lldb_init_module failed");
2800 return false;
2801 }
2802
2803 if (module_sp) {
2804 // everything went just great, now set the module object
2805 command_stream.Clear();
2806 command_stream.Printf("%s", module_name.c_str());
2807 void *module_pyobj = nullptr;
2808 if (ExecuteOneLineWithReturn(
2809 command_stream.GetData(),
2810 ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2811 exc_options) &&
2812 module_pyobj)
2813 *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2814 PyRefType::Owned, static_cast<PyObject *>(module_pyobj)));
2815 }
2816
2817 return true;
2818}
2819
2820bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
2821 if (!word || !word[0])
2822 return false;
2823
2824 llvm::StringRef word_sr(word);
2825
2826 // filter out a few characters that would just confuse us and that are
2827 // clearly not keyword material anyway
2828 if (word_sr.find('"') != llvm::StringRef::npos ||
2829 word_sr.find('\'') != llvm::StringRef::npos)
2830 return false;
2831
2832 StreamString command_stream;
2833 command_stream.Printf("keyword.iskeyword('%s')", word);
2834 bool result;
2835 ExecuteScriptOptions options;
2836 options.SetEnableIO(false);
2837 options.SetMaskoutErrors(true);
2838 options.SetSetLLDBGlobals(false);
2839 if (ExecuteOneLineWithReturn(command_stream.GetData(),
2840 ScriptInterpreter::eScriptReturnTypeBool,
2841 &result, options))
2842 return result;
2843 return false;
2844}
2845
2846ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2847 lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2848 : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2849 m_old_asynch(debugger_sp->GetAsyncExecution()) {
2850 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2851 m_debugger_sp->SetAsyncExecution(false);
2852 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2853 m_debugger_sp->SetAsyncExecution(true);
2854}
2855
2856ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
2857 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2858 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2859}
2860
2861bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2862 const char *impl_function, llvm::StringRef args,
2863 ScriptedCommandSynchronicity synchronicity,
2864 lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2865 const lldb_private::ExecutionContext &exe_ctx) {
2866 if (!impl_function) {
2867 error.SetErrorString("no function to execute");
2868 return false;
2869 }
2870
2871 lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2872 lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2873
2874 if (!debugger_sp.get()) {
2875 error.SetErrorString("invalid Debugger pointer");
2876 return false;
2877 }
2878
2879 bool ret_val = false;
2880
2881 std::string err_msg;
2882
2883 {
2884 Locker py_lock(this,
2885 Locker::AcquireLock | Locker::InitSession |
2886 (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2887 Locker::FreeLock | Locker::TearDownSession);
2888
2889 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2890
2891 std::string args_str = args.str();
2892 ret_val = LLDBSwigPythonCallCommand(
2893 impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2894 cmd_retobj, exe_ctx_ref_sp);
2895 }
2896
2897 if (!ret_val)
2898 error.SetErrorString("unable to execute script function");
2899 else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2900 return false;
2901
2902 error.Clear();
2903 return ret_val;
2904}
2905
2906bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2907 StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
2908 ScriptedCommandSynchronicity synchronicity,
2909 lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2910 const lldb_private::ExecutionContext &exe_ctx) {
2911 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2912 error.SetErrorString("no function to execute");
2913 return false;
2914 }
2915
2916 lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2917 lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2918
2919 if (!debugger_sp.get()) {
2920 error.SetErrorString("invalid Debugger pointer");
2921 return false;
2922 }
2923
2924 bool ret_val = false;
2925
2926 std::string err_msg;
2927
2928 {
2929 Locker py_lock(this,
2930 Locker::AcquireLock | Locker::InitSession |
2931 (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2932 Locker::FreeLock | Locker::TearDownSession);
2933
2934 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2935
2936 std::string args_str = args.str();
2937 ret_val = LLDBSwigPythonCallCommandObject(
2938 static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
2939 args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
2940 }
2941
2942 if (!ret_val)
2943 error.SetErrorString("unable to execute script function");
2944 else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2945 return false;
2946
2947 error.Clear();
2948 return ret_val;
2949}
2950
2951/// In Python, a special attribute __doc__ contains the docstring for an object
2952/// (function, method, class, ...) if any is defined Otherwise, the attribute's
2953/// value is None.
2954bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
2955 std::string &dest) {
2956 dest.clear();
2957
2958 if (!item || !*item)
2959 return false;
2960
2961 std::string command(item);
2962 command += ".__doc__";
2963
2964 // Python is going to point this to valid data if ExecuteOneLineWithReturn
2965 // returns successfully.
2966 char *result_ptr = nullptr;
2967
2968 if (ExecuteOneLineWithReturn(
2969 command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
2970 &result_ptr,
2971 ExecuteScriptOptions().SetEnableIO(false))) {
2972 if (result_ptr)
2973 dest.assign(result_ptr);
2974 return true;
2975 }
2976
2977 StreamString str_stream;
2978 str_stream << "Function " << item
2979 << " was not found. Containing module might be missing.";
2980 dest = std::string(str_stream.GetString());
2981
2982 return false;
2983}
2984
2985bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
2986 StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2987 dest.clear();
2988
2989 Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2990
2991 static char callee_name[] = "get_short_help";
2992
2993 if (!cmd_obj_sp)
2994 return false;
2995
2996 PythonObject implementor(PyRefType::Borrowed,
2997 (PyObject *)cmd_obj_sp->GetValue());
2998
2999 if (!implementor.IsAllocated())
3000 return false;
3001
3002 PythonObject pmeth(PyRefType::Owned,
3003 PyObject_GetAttrString(implementor.get(), callee_name));
3004
3005 if (PyErr_Occurred())
3006 PyErr_Clear();
3007
3008 if (!pmeth.IsAllocated())
3009 return false;
3010
3011 if (PyCallable_Check(pmeth.get()) == 0) {
3012 if (PyErr_Occurred())
3013 PyErr_Clear();
3014 return false;
3015 }
3016
3017 if (PyErr_Occurred())
3018 PyErr_Clear();
3019
3020 // Right now we know this function exists and is callable.
3021 PythonObject py_return(
3022 PyRefType::Owned,
3023 PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3024
3025 // If it fails, print the error but otherwise go on.
3026 if (PyErr_Occurred()) {
3027 PyErr_Print();
3028 PyErr_Clear();
3029 }
3030
3031 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3032 PythonString py_string(PyRefType::Borrowed, py_return.get());
3033 llvm::StringRef return_data(py_string.GetString());
3034 dest.assign(return_data.data(), return_data.size());
3035 return true;
3036 }
3037
3038 return false;
3039}
3040
3041uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
3042 StructuredData::GenericSP cmd_obj_sp) {
3043 uint32_t result = 0;
3044
3045 Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3046
3047 static char callee_name[] = "get_flags";
3048
3049 if (!cmd_obj_sp)
3050 return result;
3051
3052 PythonObject implementor(PyRefType::Borrowed,
3053 (PyObject *)cmd_obj_sp->GetValue());
3054
3055 if (!implementor.IsAllocated())
3056 return result;
3057
3058 PythonObject pmeth(PyRefType::Owned,
3059 PyObject_GetAttrString(implementor.get(), callee_name));
3060
3061 if (PyErr_Occurred())
3062 PyErr_Clear();
3063
3064 if (!pmeth.IsAllocated())
3065 return result;
3066
3067 if (PyCallable_Check(pmeth.get()) == 0) {
3068 if (PyErr_Occurred())
3069 PyErr_Clear();
3070 return result;
3071 }
3072
3073 if (PyErr_Occurred())
3074 PyErr_Clear();
3075
3076 long long py_return = unwrapOrSetPythonException(
3077 As<long long>(implementor.CallMethod(callee_name)));
3078
3079 // if it fails, print the error but otherwise go on
3080 if (PyErr_Occurred()) {
3081 PyErr_Print();
3082 PyErr_Clear();
3083 } else {
3084 result = py_return;
3085 }
3086
3087 return result;
3088}
3089
3090bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3091 StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
3092 bool got_string = false;
3093 dest.clear();
3094
3095 Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3096
3097 static char callee_name[] = "get_long_help";
3098
3099 if (!cmd_obj_sp)
3100 return false;
3101
3102 PythonObject implementor(PyRefType::Borrowed,
3103 (PyObject *)cmd_obj_sp->GetValue());
3104
3105 if (!implementor.IsAllocated())
3106 return false;
3107
3108 PythonObject pmeth(PyRefType::Owned,
3109 PyObject_GetAttrString(implementor.get(), callee_name));
3110
3111 if (PyErr_Occurred())
3112 PyErr_Clear();
3113
3114 if (!pmeth.IsAllocated())
3115 return false;
3116
3117 if (PyCallable_Check(pmeth.get()) == 0) {
3118 if (PyErr_Occurred())
3119 PyErr_Clear();
3120
3121 return false;
3122 }
3123
3124 if (PyErr_Occurred())
3125 PyErr_Clear();
3126
3127 // right now we know this function exists and is callable..
3128 PythonObject py_return(
3129 PyRefType::Owned,
3130 PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3131
3132 // if it fails, print the error but otherwise go on
3133 if (PyErr_Occurred()) {
3134 PyErr_Print();
3135 PyErr_Clear();
3136 }
3137
3138 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3139 PythonString str(PyRefType::Borrowed, py_return.get());
3140 llvm::StringRef str_data(str.GetString());
3141 dest.assign(str_data.data(), str_data.size());
3142 got_string = true;
3143 }
3144
3145 return got_string;
3146}
3147
3148std::unique_ptr<ScriptInterpreterLocker>
3149ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3150 std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3151 this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3152 Locker::FreeLock | Locker::TearDownSession));
3153 return py_lock;
3154}
3155
3156void ScriptInterpreterPythonImpl::Initialize() {
3157 LLDB_SCOPED_TIMER()static ::lldb_private::Timer::Category _cat(__PRETTY_FUNCTION__
); ::lldb_private::Timer _scoped_timer(_cat, "%s", __PRETTY_FUNCTION__
)
;
3158
3159 // RAII-based initialization which correctly handles multiple-initialization,
3160 // version- specific differences among Python 2 and Python 3, and saving and
3161 // restoring various other pieces of state that can get mucked with during
3162 // initialization.
3163 InitializePythonRAII initialize_guard;
3164
3165 LLDBSwigPyInitPyInit__lldb();
3166
3167 // Update the path python uses to search for modules to include the current
3168 // directory.
3169
3170 PyRun_SimpleString("import sys")PyRun_SimpleStringFlags("import sys", __null);
3171 AddToSysPath(AddLocation::End, ".");
3172
3173 // Don't denormalize paths when calling file_spec.GetPath(). On platforms
3174 // that use a backslash as the path separator, this will result in executing
3175 // python code containing paths with unescaped backslashes. But Python also
3176 // accepts forward slashes, so to make life easier we just use that.
3177 if (FileSpec file_spec = GetPythonDir())
3178 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3179 if (FileSpec file_spec = HostInfo::GetShlibDir())
3180 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3181
3182 PyRun_SimpleString("sys.dont_write_bytecode = 1; import "PyRun_SimpleStringFlags("sys.dont_write_bytecode = 1; import "
"lldb.embedded_interpreter; from " "lldb.embedded_interpreter import run_python_interpreter; "
"from lldb.embedded_interpreter import run_one_line", __null
)
3183 "lldb.embedded_interpreter; from "PyRun_SimpleStringFlags("sys.dont_write_bytecode = 1; import "
"lldb.embedded_interpreter; from " "lldb.embedded_interpreter import run_python_interpreter; "
"from lldb.embedded_interpreter import run_one_line", __null
)
3184 "lldb.embedded_interpreter import run_python_interpreter; "PyRun_SimpleStringFlags("sys.dont_write_bytecode = 1; import "
"lldb.embedded_interpreter; from " "lldb.embedded_interpreter import run_python_interpreter; "
"from lldb.embedded_interpreter import run_one_line", __null
)
3185 "from lldb.embedded_interpreter import run_one_line")PyRun_SimpleStringFlags("sys.dont_write_bytecode = 1; import "
"lldb.embedded_interpreter; from " "lldb.embedded_interpreter import run_python_interpreter; "
"from lldb.embedded_interpreter import run_one_line", __null
)
;
3186
3187#if LLDB_USE_PYTHON_SET_INTERRUPT(3 == 3 && 9 >= 2) || (3 > 3)
3188 // Python will not just overwrite its internal SIGINT handler but also the
3189 // one from the process. Backup the current SIGINT handler to prevent that
3190 // Python deletes it.
3191 RestoreSignalHandlerScope save_sigint(SIGINT2);
3192
3193 // Setup a default SIGINT signal handler that works the same way as the
3194 // normal Python REPL signal handler which raises a KeyboardInterrupt.
3195 // Also make sure to not pollute the user's REPL with the signal module nor
3196 // our utility function.
3197 PyRun_SimpleString("def lldb_setup_sigint_handler():\n"PyRun_SimpleStringFlags("def lldb_setup_sigint_handler():\n" " import signal;\n"
" def signal_handler(sig, frame):\n" " raise KeyboardInterrupt()\n"
" signal.signal(signal.SIGINT, signal_handler);\n" "lldb_setup_sigint_handler();\n"
"del lldb_setup_sigint_handler\n", __null)
3198 " import signal;\n"PyRun_SimpleStringFlags("def lldb_setup_sigint_handler():\n" " import signal;\n"
" def signal_handler(sig, frame):\n" " raise KeyboardInterrupt()\n"
" signal.signal(signal.SIGINT, signal_handler);\n" "lldb_setup_sigint_handler();\n"
"del lldb_setup_sigint_handler\n", __null)
3199 " def signal_handler(sig, frame):\n"PyRun_SimpleStringFlags("def lldb_setup_sigint_handler():\n" " import signal;\n"
" def signal_handler(sig, frame):\n" " raise KeyboardInterrupt()\n"
" signal.signal(signal.SIGINT, signal_handler);\n" "lldb_setup_sigint_handler();\n"
"del lldb_setup_sigint_handler\n", __null)
3200 " raise KeyboardInterrupt()\n"PyRun_SimpleStringFlags("def lldb_setup_sigint_handler():\n" " import signal;\n"
" def signal_handler(sig, frame):\n" " raise KeyboardInterrupt()\n"
" signal.signal(signal.SIGINT, signal_handler);\n" "lldb_setup_sigint_handler();\n"
"del lldb_setup_sigint_handler\n", __null)
3201 " signal.signal(signal.SIGINT, signal_handler);\n"PyRun_SimpleStringFlags("def lldb_setup_sigint_handler():\n" " import signal;\n"
" def signal_handler(sig, frame):\n" " raise KeyboardInterrupt()\n"
" signal.signal(signal.SIGINT, signal_handler);\n" "lldb_setup_sigint_handler();\n"
"del lldb_setup_sigint_handler\n", __null)
3202 "lldb_setup_sigint_handler();\n"PyRun_SimpleStringFlags("def lldb_setup_sigint_handler():\n" " import signal;\n"
" def signal_handler(sig, frame):\n" " raise KeyboardInterrupt()\n"
" signal.signal(signal.SIGINT, signal_handler);\n" "lldb_setup_sigint_handler();\n"
"del lldb_setup_sigint_handler\n", __null)
3203 "del lldb_setup_sigint_handler\n")PyRun_SimpleStringFlags("def lldb_setup_sigint_handler():\n" " import signal;\n"
" def signal_handler(sig, frame):\n" " raise KeyboardInterrupt()\n"
" signal.signal(signal.SIGINT, signal_handler);\n" "lldb_setup_sigint_handler();\n"
"del lldb_setup_sigint_handler\n", __null)
;
3204#endif
3205}
3206
3207void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3208 std::string path) {
3209 std::string path_copy;
3210
3211 std::string statement;
3212 if (location == AddLocation::Beginning) {
3213 statement.assign("sys.path.insert(0,\"");
3214 statement.append(path);
3215 statement.append("\")");
3216 } else {
3217 statement.assign("sys.path.append(\"");
3218 statement.append(path);
3219 statement.append("\")");
3220 }
3221 PyRun_SimpleString(statement.c_str())PyRun_SimpleStringFlags(statement.c_str(), __null);
3222}
3223
3224// We are intentionally NOT calling Py_Finalize here (this would be the logical
3225// place to call it). Calling Py_Finalize here causes test suite runs to seg
3226// fault: The test suite runs in Python. It registers SBDebugger::Terminate to
3227// be called 'at_exit'. When the test suite Python harness finishes up, it
3228// calls Py_Finalize, which calls all the 'at_exit' registered functions.
3229// SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3230// which calls ScriptInterpreter::Terminate, which calls
3231// ScriptInterpreterPythonImpl::Terminate. So if we call Py_Finalize here, we
3232// end up with Py_Finalize being called from within Py_Finalize, which results
3233// in a seg fault. Since this function only gets called when lldb is shutting
3234// down and going away anyway, the fact that we don't actually call Py_Finalize
3235// should not cause any problems (everything should shut down/go away anyway
3236// when the process exits).
3237//
3238// void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3239
3240#endif