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