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