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