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