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