Bug Summary

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