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