Bug Summary

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