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