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