xref: /llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp (revision 547917aebd1e79a8929b53f0ddf3b5185ee4df74)
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(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(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.SetErrorStringWithFormat(
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.SetErrorString("cannot pass extra_args to a three argument callback"
1192                           );
1193       return error;
1194     }
1195     uses_extra_args = false;
1196     function_signature += "(frame, bp_loc, internal_dict)";
1197   } else {
1198     error.SetErrorStringWithFormat("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.SetErrorString("No input data.");
1301     return error;
1302   }
1303 
1304   if (!signature || *signature == 0) {
1305     error.SetErrorString("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("ScriptInterpreterPythonImpl::GenerateFunction(is_callback="
1333                     "true) = ERROR: python function is multiline.");
1334     }
1335   } else {
1336     auto_generated_function.AppendString(
1337         "    __return_val = None"); // Initialize user callback return value.
1338     auto_generated_function.AppendString(
1339         "    def __user_code():"); // Create a nested function that will wrap
1340                                    // the user input. This is necessary to
1341                                    // capture the return value of the user input
1342                                    // and prevent early returns.
1343     for (int i = 0; i < num_lines; ++i) {
1344       sstr.Clear();
1345       sstr.Printf("      %s", input.GetStringAtIndex(i));
1346       auto_generated_function.AppendString(sstr.GetData());
1347     }
1348     auto_generated_function.AppendString(
1349         "    __return_val = __user_code()"); //  Call user code and capture
1350                                              //  return value
1351   }
1352   auto_generated_function.AppendString(
1353       "    for key in new_keys:"); // Iterate over all the keys from session
1354                                    // dict
1355   auto_generated_function.AppendString(
1356       "        internal_dict[key] = global_dict[key]"); // Update session dict
1357                                                         // values
1358   auto_generated_function.AppendString(
1359       "        if key not in old_keys:"); // If key was not originally in
1360                                           // global dict
1361   auto_generated_function.AppendString(
1362       "            del global_dict[key]"); //  ...then remove key/value from
1363                                            //  global dict
1364   auto_generated_function.AppendString(
1365       "    return __return_val"); //  Return the user callback return value.
1366 
1367   // Verify that the results are valid Python.
1368   error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
1369 
1370   return error;
1371 }
1372 
1373 bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1374     StringList &user_input, std::string &output, const void *name_token) {
1375   static uint32_t num_created_functions = 0;
1376   user_input.RemoveBlankLines();
1377   StreamString sstr;
1378 
1379   // Check to see if we have any data; if not, just return.
1380   if (user_input.GetSize() == 0)
1381     return false;
1382 
1383   // Take what the user wrote, wrap it all up inside one big auto-generated
1384   // Python function, passing in the ValueObject as parameter to the function.
1385 
1386   std::string auto_generated_function_name(
1387       GenerateUniqueName("lldb_autogen_python_type_print_func",
1388                          num_created_functions, name_token));
1389   sstr.Printf("def %s (valobj, internal_dict):",
1390               auto_generated_function_name.c_str());
1391 
1392   if (!GenerateFunction(sstr.GetData(), user_input, /*is_callback=*/false)
1393            .Success())
1394     return false;
1395 
1396   // Store the name of the auto-generated function to be called.
1397   output.assign(auto_generated_function_name);
1398   return true;
1399 }
1400 
1401 bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1402     StringList &user_input, std::string &output) {
1403   static uint32_t num_created_functions = 0;
1404   user_input.RemoveBlankLines();
1405   StreamString sstr;
1406 
1407   // Check to see if we have any data; if not, just return.
1408   if (user_input.GetSize() == 0)
1409     return false;
1410 
1411   std::string auto_generated_function_name(GenerateUniqueName(
1412       "lldb_autogen_python_cmd_alias_func", num_created_functions));
1413 
1414   sstr.Printf("def %s (debugger, args, exe_ctx, result, internal_dict):",
1415               auto_generated_function_name.c_str());
1416 
1417   if (!GenerateFunction(sstr.GetData(), user_input, /*is_callback=*/false)
1418            .Success())
1419     return false;
1420 
1421   // Store the name of the auto-generated function to be called.
1422   output.assign(auto_generated_function_name);
1423   return true;
1424 }
1425 
1426 bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1427     StringList &user_input, std::string &output, const void *name_token) {
1428   static uint32_t num_created_classes = 0;
1429   user_input.RemoveBlankLines();
1430   int num_lines = user_input.GetSize();
1431   StreamString sstr;
1432 
1433   // Check to see if we have any data; if not, just return.
1434   if (user_input.GetSize() == 0)
1435     return false;
1436 
1437   // Wrap all user input into a Python class
1438 
1439   std::string auto_generated_class_name(GenerateUniqueName(
1440       "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1441 
1442   StringList auto_generated_class;
1443 
1444   // Create the function name & definition string.
1445 
1446   sstr.Printf("class %s:", auto_generated_class_name.c_str());
1447   auto_generated_class.AppendString(sstr.GetString());
1448 
1449   // Wrap everything up inside the class, increasing the indentation. we don't
1450   // need to play any fancy indentation tricks here because there is no
1451   // surrounding code whose indentation we need to honor
1452   for (int i = 0; i < num_lines; ++i) {
1453     sstr.Clear();
1454     sstr.Printf("     %s", user_input.GetStringAtIndex(i));
1455     auto_generated_class.AppendString(sstr.GetString());
1456   }
1457 
1458   // Verify that the results are valid Python. (even though the method is
1459   // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1460   // (TODO: rename that method to ExportDefinitionToInterpreter)
1461   if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
1462     return false;
1463 
1464   // Store the name of the auto-generated class
1465 
1466   output.assign(auto_generated_class_name);
1467   return true;
1468 }
1469 
1470 StructuredData::GenericSP
1471 ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
1472   if (class_name == nullptr || class_name[0] == '\0')
1473     return StructuredData::GenericSP();
1474 
1475   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1476   PythonObject ret_val = SWIGBridge::LLDBSWIGPython_CreateFrameRecognizer(
1477       class_name, m_dictionary_name.c_str());
1478 
1479   return StructuredData::GenericSP(
1480       new StructuredPythonObject(std::move(ret_val)));
1481 }
1482 
1483 lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
1484     const StructuredData::ObjectSP &os_plugin_object_sp,
1485     lldb::StackFrameSP frame_sp) {
1486   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1487 
1488   if (!os_plugin_object_sp)
1489     return ValueObjectListSP();
1490 
1491   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1492   if (!generic)
1493     return nullptr;
1494 
1495   PythonObject implementor(PyRefType::Borrowed,
1496                            (PyObject *)generic->GetValue());
1497 
1498   if (!implementor.IsAllocated())
1499     return ValueObjectListSP();
1500 
1501   PythonObject py_return(PyRefType::Owned,
1502                          SWIGBridge::LLDBSwigPython_GetRecognizedArguments(
1503                              implementor.get(), frame_sp));
1504 
1505   // if it fails, print the error but otherwise go on
1506   if (PyErr_Occurred()) {
1507     PyErr_Print();
1508     PyErr_Clear();
1509   }
1510   if (py_return.get()) {
1511     PythonList result_list(PyRefType::Borrowed, py_return.get());
1512     ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
1513     for (size_t i = 0; i < result_list.GetSize(); i++) {
1514       PyObject *item = result_list.GetItemAtIndex(i).get();
1515       lldb::SBValue *sb_value_ptr =
1516           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
1517       auto valobj_sp =
1518           SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
1519       if (valobj_sp)
1520         result->Append(valobj_sp);
1521     }
1522     return result;
1523   }
1524   return ValueObjectListSP();
1525 }
1526 
1527 ScriptedProcessInterfaceUP
1528 ScriptInterpreterPythonImpl::CreateScriptedProcessInterface() {
1529   return std::make_unique<ScriptedProcessPythonInterface>(*this);
1530 }
1531 
1532 ScriptedThreadInterfaceSP
1533 ScriptInterpreterPythonImpl::CreateScriptedThreadInterface() {
1534   return std::make_shared<ScriptedThreadPythonInterface>(*this);
1535 }
1536 
1537 ScriptedThreadPlanInterfaceSP
1538 ScriptInterpreterPythonImpl::CreateScriptedThreadPlanInterface() {
1539   return std::make_shared<ScriptedThreadPlanPythonInterface>(*this);
1540 }
1541 
1542 OperatingSystemInterfaceSP
1543 ScriptInterpreterPythonImpl::CreateOperatingSystemInterface() {
1544   return std::make_shared<OperatingSystemPythonInterface>(*this);
1545 }
1546 
1547 StructuredData::ObjectSP
1548 ScriptInterpreterPythonImpl::CreateStructuredDataFromScriptObject(
1549     ScriptObject obj) {
1550   void *ptr = const_cast<void *>(obj.GetPointer());
1551   PythonObject py_obj(PyRefType::Borrowed, static_cast<PyObject *>(ptr));
1552   if (!py_obj.IsValid() || py_obj.IsNone())
1553     return {};
1554   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1555   return py_obj.CreateStructuredObject();
1556 }
1557 
1558 StructuredData::GenericSP
1559 ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
1560     const char *class_name, const StructuredDataImpl &args_data,
1561     lldb::BreakpointSP &bkpt_sp) {
1562 
1563   if (class_name == nullptr || class_name[0] == '\0')
1564     return StructuredData::GenericSP();
1565 
1566   if (!bkpt_sp.get())
1567     return StructuredData::GenericSP();
1568 
1569   Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
1570   ScriptInterpreterPythonImpl *python_interpreter =
1571       GetPythonInterpreter(debugger);
1572 
1573   if (!python_interpreter)
1574     return StructuredData::GenericSP();
1575 
1576   Locker py_lock(this,
1577                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1578 
1579   PythonObject ret_val =
1580       SWIGBridge::LLDBSwigPythonCreateScriptedBreakpointResolver(
1581           class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
1582           bkpt_sp);
1583 
1584   return StructuredData::GenericSP(
1585       new StructuredPythonObject(std::move(ret_val)));
1586 }
1587 
1588 bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
1589     StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
1590   bool should_continue = false;
1591 
1592   if (implementor_sp) {
1593     Locker py_lock(this,
1594                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1595     should_continue = SWIGBridge::LLDBSwigPythonCallBreakpointResolver(
1596         implementor_sp->GetValue(), "__callback__", sym_ctx);
1597     if (PyErr_Occurred()) {
1598       PyErr_Print();
1599       PyErr_Clear();
1600     }
1601   }
1602   return should_continue;
1603 }
1604 
1605 lldb::SearchDepth
1606 ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
1607     StructuredData::GenericSP implementor_sp) {
1608   int depth_as_int = lldb::eSearchDepthModule;
1609   if (implementor_sp) {
1610     Locker py_lock(this,
1611                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1612     depth_as_int = SWIGBridge::LLDBSwigPythonCallBreakpointResolver(
1613         implementor_sp->GetValue(), "__get_depth__", nullptr);
1614     if (PyErr_Occurred()) {
1615       PyErr_Print();
1616       PyErr_Clear();
1617     }
1618   }
1619   if (depth_as_int == lldb::eSearchDepthInvalid)
1620     return lldb::eSearchDepthModule;
1621 
1622   if (depth_as_int <= lldb::kLastSearchDepthKind)
1623     return (lldb::SearchDepth)depth_as_int;
1624   return lldb::eSearchDepthModule;
1625 }
1626 
1627 StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
1628     TargetSP target_sp, const char *class_name,
1629     const StructuredDataImpl &args_data, Status &error) {
1630 
1631   if (!target_sp) {
1632     error.SetErrorString("No target for scripted stop-hook.");
1633     return StructuredData::GenericSP();
1634   }
1635 
1636   if (class_name == nullptr || class_name[0] == '\0') {
1637     error.SetErrorString("No class name for scripted stop-hook.");
1638     return StructuredData::GenericSP();
1639   }
1640 
1641   ScriptInterpreterPythonImpl *python_interpreter =
1642       GetPythonInterpreter(m_debugger);
1643 
1644   if (!python_interpreter) {
1645     error.SetErrorString("No script interpreter for scripted stop-hook.");
1646     return StructuredData::GenericSP();
1647   }
1648 
1649   Locker py_lock(this,
1650                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1651 
1652   PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateScriptedStopHook(
1653       target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
1654       args_data, error);
1655 
1656   return StructuredData::GenericSP(
1657       new StructuredPythonObject(std::move(ret_val)));
1658 }
1659 
1660 bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
1661     StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
1662     lldb::StreamSP stream_sp) {
1663   assert(implementor_sp &&
1664          "can't call a stop hook with an invalid implementor");
1665   assert(stream_sp && "can't call a stop hook with an invalid stream");
1666 
1667   Locker py_lock(this,
1668                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1669 
1670   lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
1671 
1672   bool ret_val = SWIGBridge::LLDBSwigPythonStopHookCallHandleStop(
1673       implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
1674   return ret_val;
1675 }
1676 
1677 StructuredData::ObjectSP
1678 ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
1679                                               lldb_private::Status &error) {
1680   if (!FileSystem::Instance().Exists(file_spec)) {
1681     error.SetErrorString("no such file");
1682     return StructuredData::ObjectSP();
1683   }
1684 
1685   StructuredData::ObjectSP module_sp;
1686 
1687   LoadScriptOptions load_script_options =
1688       LoadScriptOptions().SetInitSession(true).SetSilent(false);
1689   if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1690                           error, &module_sp))
1691     return module_sp;
1692 
1693   return StructuredData::ObjectSP();
1694 }
1695 
1696 StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
1697     StructuredData::ObjectSP plugin_module_sp, Target *target,
1698     const char *setting_name, lldb_private::Status &error) {
1699   if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
1700     return StructuredData::DictionarySP();
1701   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
1702   if (!generic)
1703     return StructuredData::DictionarySP();
1704 
1705   Locker py_lock(this,
1706                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1707   TargetSP target_sp(target->shared_from_this());
1708 
1709   auto setting = (PyObject *)SWIGBridge::LLDBSWIGPython_GetDynamicSetting(
1710       generic->GetValue(), setting_name, target_sp);
1711 
1712   if (!setting)
1713     return StructuredData::DictionarySP();
1714 
1715   PythonDictionary py_dict =
1716       unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
1717 
1718   if (!py_dict)
1719     return StructuredData::DictionarySP();
1720 
1721   return py_dict.CreateStructuredDictionary();
1722 }
1723 
1724 StructuredData::ObjectSP
1725 ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
1726     const char *class_name, lldb::ValueObjectSP valobj) {
1727   if (class_name == nullptr || class_name[0] == '\0')
1728     return StructuredData::ObjectSP();
1729 
1730   if (!valobj.get())
1731     return StructuredData::ObjectSP();
1732 
1733   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
1734   Target *target = exe_ctx.GetTargetPtr();
1735 
1736   if (!target)
1737     return StructuredData::ObjectSP();
1738 
1739   Debugger &debugger = target->GetDebugger();
1740   ScriptInterpreterPythonImpl *python_interpreter =
1741       GetPythonInterpreter(debugger);
1742 
1743   if (!python_interpreter)
1744     return StructuredData::ObjectSP();
1745 
1746   Locker py_lock(this,
1747                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1748   PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateSyntheticProvider(
1749       class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
1750 
1751   return StructuredData::ObjectSP(
1752       new StructuredPythonObject(std::move(ret_val)));
1753 }
1754 
1755 StructuredData::GenericSP
1756 ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
1757   DebuggerSP debugger_sp(m_debugger.shared_from_this());
1758 
1759   if (class_name == nullptr || class_name[0] == '\0')
1760     return StructuredData::GenericSP();
1761 
1762   if (!debugger_sp.get())
1763     return StructuredData::GenericSP();
1764 
1765   Locker py_lock(this,
1766                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1767   PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateCommandObject(
1768       class_name, m_dictionary_name.c_str(), debugger_sp);
1769 
1770   if (ret_val.IsValid())
1771     return StructuredData::GenericSP(
1772         new StructuredPythonObject(std::move(ret_val)));
1773   else
1774     return {};
1775 }
1776 
1777 bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1778     const char *oneliner, std::string &output, const void *name_token) {
1779   StringList input;
1780   input.SplitIntoLines(oneliner, strlen(oneliner));
1781   return GenerateTypeScriptFunction(input, output, name_token);
1782 }
1783 
1784 bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1785     const char *oneliner, std::string &output, const void *name_token) {
1786   StringList input;
1787   input.SplitIntoLines(oneliner, strlen(oneliner));
1788   return GenerateTypeSynthClass(input, output, name_token);
1789 }
1790 
1791 Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
1792     StringList &user_input, std::string &output, bool has_extra_args,
1793     bool is_callback) {
1794   static uint32_t num_created_functions = 0;
1795   user_input.RemoveBlankLines();
1796   StreamString sstr;
1797   Status error;
1798   if (user_input.GetSize() == 0) {
1799     error.SetErrorString("No input data.");
1800     return error;
1801   }
1802 
1803   std::string auto_generated_function_name(GenerateUniqueName(
1804       "lldb_autogen_python_bp_callback_func_", num_created_functions));
1805   if (has_extra_args)
1806     sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
1807                 auto_generated_function_name.c_str());
1808   else
1809     sstr.Printf("def %s (frame, bp_loc, internal_dict):",
1810                 auto_generated_function_name.c_str());
1811 
1812   error = GenerateFunction(sstr.GetData(), user_input, is_callback);
1813   if (!error.Success())
1814     return error;
1815 
1816   // Store the name of the auto-generated function to be called.
1817   output.assign(auto_generated_function_name);
1818   return error;
1819 }
1820 
1821 bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
1822     StringList &user_input, std::string &output, bool is_callback) {
1823   static uint32_t num_created_functions = 0;
1824   user_input.RemoveBlankLines();
1825   StreamString sstr;
1826 
1827   if (user_input.GetSize() == 0)
1828     return false;
1829 
1830   std::string auto_generated_function_name(GenerateUniqueName(
1831       "lldb_autogen_python_wp_callback_func_", num_created_functions));
1832   sstr.Printf("def %s (frame, wp, internal_dict):",
1833               auto_generated_function_name.c_str());
1834 
1835   if (!GenerateFunction(sstr.GetData(), user_input, is_callback).Success())
1836     return false;
1837 
1838   // Store the name of the auto-generated function to be called.
1839   output.assign(auto_generated_function_name);
1840   return true;
1841 }
1842 
1843 bool ScriptInterpreterPythonImpl::GetScriptedSummary(
1844     const char *python_function_name, lldb::ValueObjectSP valobj,
1845     StructuredData::ObjectSP &callee_wrapper_sp,
1846     const TypeSummaryOptions &options, std::string &retval) {
1847 
1848   LLDB_SCOPED_TIMER();
1849 
1850   if (!valobj.get()) {
1851     retval.assign("<no object>");
1852     return false;
1853   }
1854 
1855   void *old_callee = nullptr;
1856   StructuredData::Generic *generic = nullptr;
1857   if (callee_wrapper_sp) {
1858     generic = callee_wrapper_sp->GetAsGeneric();
1859     if (generic)
1860       old_callee = generic->GetValue();
1861   }
1862   void *new_callee = old_callee;
1863 
1864   bool ret_val;
1865   if (python_function_name && *python_function_name) {
1866     {
1867       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
1868                                Locker::NoSTDIN);
1869       {
1870         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
1871 
1872         static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
1873         Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
1874         ret_val = SWIGBridge::LLDBSwigPythonCallTypeScript(
1875             python_function_name, GetSessionDictionary().get(), valobj,
1876             &new_callee, options_sp, retval);
1877       }
1878     }
1879   } else {
1880     retval.assign("<no function name>");
1881     return false;
1882   }
1883 
1884   if (new_callee && old_callee != new_callee) {
1885     Locker py_lock(this,
1886                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1887     callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
1888         PythonObject(PyRefType::Borrowed, static_cast<PyObject *>(new_callee)));
1889   }
1890 
1891   return ret_val;
1892 }
1893 
1894 bool ScriptInterpreterPythonImpl::FormatterCallbackFunction(
1895     const char *python_function_name, TypeImplSP type_impl_sp) {
1896   Locker py_lock(this,
1897                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1898   return SWIGBridge::LLDBSwigPythonFormatterCallbackFunction(
1899       python_function_name, m_dictionary_name.c_str(), type_impl_sp);
1900 }
1901 
1902 bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
1903     void *baton, StoppointCallbackContext *context, user_id_t break_id,
1904     user_id_t break_loc_id) {
1905   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
1906   const char *python_function_name = bp_option_data->script_source.c_str();
1907 
1908   if (!context)
1909     return true;
1910 
1911   ExecutionContext exe_ctx(context->exe_ctx_ref);
1912   Target *target = exe_ctx.GetTargetPtr();
1913 
1914   if (!target)
1915     return true;
1916 
1917   Debugger &debugger = target->GetDebugger();
1918   ScriptInterpreterPythonImpl *python_interpreter =
1919       GetPythonInterpreter(debugger);
1920 
1921   if (!python_interpreter)
1922     return true;
1923 
1924   if (python_function_name && python_function_name[0]) {
1925     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
1926     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
1927     if (breakpoint_sp) {
1928       const BreakpointLocationSP bp_loc_sp(
1929           breakpoint_sp->FindLocationByID(break_loc_id));
1930 
1931       if (stop_frame_sp && bp_loc_sp) {
1932         bool ret_val = true;
1933         {
1934           Locker py_lock(python_interpreter, Locker::AcquireLock |
1935                                                  Locker::InitSession |
1936                                                  Locker::NoSTDIN);
1937           Expected<bool> maybe_ret_val =
1938               SWIGBridge::LLDBSwigPythonBreakpointCallbackFunction(
1939                   python_function_name,
1940                   python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
1941                   bp_loc_sp, bp_option_data->m_extra_args);
1942 
1943           if (!maybe_ret_val) {
1944 
1945             llvm::handleAllErrors(
1946                 maybe_ret_val.takeError(),
1947                 [&](PythonException &E) {
1948                   debugger.GetErrorStream() << E.ReadBacktrace();
1949                 },
1950                 [&](const llvm::ErrorInfoBase &E) {
1951                   debugger.GetErrorStream() << E.message();
1952                 });
1953 
1954           } else {
1955             ret_val = maybe_ret_val.get();
1956           }
1957         }
1958         return ret_val;
1959       }
1960     }
1961   }
1962   // We currently always true so we stop in case anything goes wrong when
1963   // trying to call the script function
1964   return true;
1965 }
1966 
1967 bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
1968     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
1969   WatchpointOptions::CommandData *wp_option_data =
1970       (WatchpointOptions::CommandData *)baton;
1971   const char *python_function_name = wp_option_data->script_source.c_str();
1972 
1973   if (!context)
1974     return true;
1975 
1976   ExecutionContext exe_ctx(context->exe_ctx_ref);
1977   Target *target = exe_ctx.GetTargetPtr();
1978 
1979   if (!target)
1980     return true;
1981 
1982   Debugger &debugger = target->GetDebugger();
1983   ScriptInterpreterPythonImpl *python_interpreter =
1984       GetPythonInterpreter(debugger);
1985 
1986   if (!python_interpreter)
1987     return true;
1988 
1989   if (python_function_name && python_function_name[0]) {
1990     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
1991     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
1992     if (wp_sp) {
1993       if (stop_frame_sp && wp_sp) {
1994         bool ret_val = true;
1995         {
1996           Locker py_lock(python_interpreter, Locker::AcquireLock |
1997                                                  Locker::InitSession |
1998                                                  Locker::NoSTDIN);
1999           ret_val = SWIGBridge::LLDBSwigPythonWatchpointCallbackFunction(
2000               python_function_name,
2001               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2002               wp_sp);
2003         }
2004         return ret_val;
2005       }
2006     }
2007   }
2008   // We currently always true so we stop in case anything goes wrong when
2009   // trying to call the script function
2010   return true;
2011 }
2012 
2013 size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2014     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
2015   if (!implementor_sp)
2016     return 0;
2017   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2018   if (!generic)
2019     return 0;
2020   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2021   if (!implementor)
2022     return 0;
2023 
2024   size_t ret_val = 0;
2025 
2026   {
2027     Locker py_lock(this,
2028                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2029     ret_val = SWIGBridge::LLDBSwigPython_CalculateNumChildren(implementor, max);
2030   }
2031 
2032   return ret_val;
2033 }
2034 
2035 lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
2036     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
2037   if (!implementor_sp)
2038     return lldb::ValueObjectSP();
2039 
2040   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2041   if (!generic)
2042     return lldb::ValueObjectSP();
2043   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2044   if (!implementor)
2045     return lldb::ValueObjectSP();
2046 
2047   lldb::ValueObjectSP ret_val;
2048   {
2049     Locker py_lock(this,
2050                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2051     PyObject *child_ptr =
2052         SWIGBridge::LLDBSwigPython_GetChildAtIndex(implementor, idx);
2053     if (child_ptr != nullptr && child_ptr != Py_None) {
2054       lldb::SBValue *sb_value_ptr =
2055           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2056       if (sb_value_ptr == nullptr)
2057         Py_XDECREF(child_ptr);
2058       else
2059         ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
2060             sb_value_ptr);
2061     } else {
2062       Py_XDECREF(child_ptr);
2063     }
2064   }
2065 
2066   return ret_val;
2067 }
2068 
2069 int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2070     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
2071   if (!implementor_sp)
2072     return UINT32_MAX;
2073 
2074   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2075   if (!generic)
2076     return UINT32_MAX;
2077   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2078   if (!implementor)
2079     return UINT32_MAX;
2080 
2081   int ret_val = UINT32_MAX;
2082 
2083   {
2084     Locker py_lock(this,
2085                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2086     ret_val = SWIGBridge::LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
2087   }
2088 
2089   return ret_val;
2090 }
2091 
2092 bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2093     const StructuredData::ObjectSP &implementor_sp) {
2094   bool ret_val = false;
2095 
2096   if (!implementor_sp)
2097     return ret_val;
2098 
2099   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2100   if (!generic)
2101     return ret_val;
2102   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2103   if (!implementor)
2104     return ret_val;
2105 
2106   {
2107     Locker py_lock(this,
2108                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2109     ret_val =
2110         SWIGBridge::LLDBSwigPython_UpdateSynthProviderInstance(implementor);
2111   }
2112 
2113   return ret_val;
2114 }
2115 
2116 bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2117     const StructuredData::ObjectSP &implementor_sp) {
2118   bool ret_val = false;
2119 
2120   if (!implementor_sp)
2121     return ret_val;
2122 
2123   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2124   if (!generic)
2125     return ret_val;
2126   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2127   if (!implementor)
2128     return ret_val;
2129 
2130   {
2131     Locker py_lock(this,
2132                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2133     ret_val = SWIGBridge::LLDBSwigPython_MightHaveChildrenSynthProviderInstance(
2134         implementor);
2135   }
2136 
2137   return ret_val;
2138 }
2139 
2140 lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
2141     const StructuredData::ObjectSP &implementor_sp) {
2142   lldb::ValueObjectSP ret_val(nullptr);
2143 
2144   if (!implementor_sp)
2145     return ret_val;
2146 
2147   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2148   if (!generic)
2149     return ret_val;
2150   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2151   if (!implementor)
2152     return ret_val;
2153 
2154   {
2155     Locker py_lock(this,
2156                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2157     PyObject *child_ptr =
2158         SWIGBridge::LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2159     if (child_ptr != nullptr && child_ptr != Py_None) {
2160       lldb::SBValue *sb_value_ptr =
2161           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2162       if (sb_value_ptr == nullptr)
2163         Py_XDECREF(child_ptr);
2164       else
2165         ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
2166             sb_value_ptr);
2167     } else {
2168       Py_XDECREF(child_ptr);
2169     }
2170   }
2171 
2172   return ret_val;
2173 }
2174 
2175 ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2176     const StructuredData::ObjectSP &implementor_sp) {
2177   Locker py_lock(this,
2178                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2179 
2180   if (!implementor_sp)
2181     return {};
2182 
2183   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2184   if (!generic)
2185     return {};
2186 
2187   PythonObject implementor(PyRefType::Borrowed,
2188                            (PyObject *)generic->GetValue());
2189   if (!implementor.IsAllocated())
2190     return {};
2191 
2192   llvm::Expected<PythonObject> expected_py_return =
2193       implementor.CallMethod("get_type_name");
2194 
2195   if (!expected_py_return) {
2196     llvm::consumeError(expected_py_return.takeError());
2197     return {};
2198   }
2199 
2200   PythonObject py_return = std::move(expected_py_return.get());
2201   if (!py_return.IsAllocated() || !PythonString::Check(py_return.get()))
2202     return {};
2203 
2204   PythonString type_name(PyRefType::Borrowed, py_return.get());
2205   return ConstString(type_name.GetString());
2206 }
2207 
2208 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2209     const char *impl_function, Process *process, std::string &output,
2210     Status &error) {
2211   bool ret_val;
2212   if (!process) {
2213     error.SetErrorString("no process");
2214     return false;
2215   }
2216   if (!impl_function || !impl_function[0]) {
2217     error.SetErrorString("no function to execute");
2218     return false;
2219   }
2220 
2221   {
2222     Locker py_lock(this,
2223                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2224     ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordProcess(
2225         impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
2226         output);
2227     if (!ret_val)
2228       error.SetErrorString("python script evaluation failed");
2229   }
2230   return ret_val;
2231 }
2232 
2233 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2234     const char *impl_function, Thread *thread, std::string &output,
2235     Status &error) {
2236   if (!thread) {
2237     error.SetErrorString("no thread");
2238     return false;
2239   }
2240   if (!impl_function || !impl_function[0]) {
2241     error.SetErrorString("no function to execute");
2242     return false;
2243   }
2244 
2245   Locker py_lock(this,
2246                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2247   if (std::optional<std::string> result =
2248           SWIGBridge::LLDBSWIGPythonRunScriptKeywordThread(
2249               impl_function, m_dictionary_name.c_str(),
2250               thread->shared_from_this())) {
2251     output = std::move(*result);
2252     return true;
2253   }
2254   error.SetErrorString("python script evaluation failed");
2255   return false;
2256 }
2257 
2258 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2259     const char *impl_function, Target *target, std::string &output,
2260     Status &error) {
2261   bool ret_val;
2262   if (!target) {
2263     error.SetErrorString("no thread");
2264     return false;
2265   }
2266   if (!impl_function || !impl_function[0]) {
2267     error.SetErrorString("no function to execute");
2268     return false;
2269   }
2270 
2271   {
2272     TargetSP target_sp(target->shared_from_this());
2273     Locker py_lock(this,
2274                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2275     ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordTarget(
2276         impl_function, m_dictionary_name.c_str(), target_sp, output);
2277     if (!ret_val)
2278       error.SetErrorString("python script evaluation failed");
2279   }
2280   return ret_val;
2281 }
2282 
2283 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2284     const char *impl_function, StackFrame *frame, std::string &output,
2285     Status &error) {
2286   if (!frame) {
2287     error.SetErrorString("no frame");
2288     return false;
2289   }
2290   if (!impl_function || !impl_function[0]) {
2291     error.SetErrorString("no function to execute");
2292     return false;
2293   }
2294 
2295   Locker py_lock(this,
2296                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2297   if (std::optional<std::string> result =
2298           SWIGBridge::LLDBSWIGPythonRunScriptKeywordFrame(
2299               impl_function, m_dictionary_name.c_str(),
2300               frame->shared_from_this())) {
2301     output = std::move(*result);
2302     return true;
2303   }
2304   error.SetErrorString("python script evaluation failed");
2305   return false;
2306 }
2307 
2308 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2309     const char *impl_function, ValueObject *value, std::string &output,
2310     Status &error) {
2311   bool ret_val;
2312   if (!value) {
2313     error.SetErrorString("no value");
2314     return false;
2315   }
2316   if (!impl_function || !impl_function[0]) {
2317     error.SetErrorString("no function to execute");
2318     return false;
2319   }
2320 
2321   {
2322     Locker py_lock(this,
2323                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2324     ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordValue(
2325         impl_function, m_dictionary_name.c_str(), value->GetSP(), output);
2326     if (!ret_val)
2327       error.SetErrorString("python script evaluation failed");
2328   }
2329   return ret_val;
2330 }
2331 
2332 uint64_t replace_all(std::string &str, const std::string &oldStr,
2333                      const std::string &newStr) {
2334   size_t pos = 0;
2335   uint64_t matches = 0;
2336   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2337     matches++;
2338     str.replace(pos, oldStr.length(), newStr);
2339     pos += newStr.length();
2340   }
2341   return matches;
2342 }
2343 
2344 bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2345     const char *pathname, const LoadScriptOptions &options,
2346     lldb_private::Status &error, StructuredData::ObjectSP *module_sp,
2347     FileSpec extra_search_dir) {
2348   namespace fs = llvm::sys::fs;
2349   namespace path = llvm::sys::path;
2350 
2351   ExecuteScriptOptions exc_options = ExecuteScriptOptions()
2352                                          .SetEnableIO(!options.GetSilent())
2353                                          .SetSetLLDBGlobals(false);
2354 
2355   if (!pathname || !pathname[0]) {
2356     error.SetErrorString("empty path");
2357     return false;
2358   }
2359 
2360   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2361       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2362           exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2363 
2364   if (!io_redirect_or_error) {
2365     error = io_redirect_or_error.takeError();
2366     return false;
2367   }
2368 
2369   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
2370 
2371   // Before executing Python code, lock the GIL.
2372   Locker py_lock(this,
2373                  Locker::AcquireLock |
2374                      (options.GetInitSession() ? Locker::InitSession : 0) |
2375                      Locker::NoSTDIN,
2376                  Locker::FreeAcquiredLock |
2377                      (options.GetInitSession() ? Locker::TearDownSession : 0),
2378                  io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2379                  io_redirect.GetErrorFile());
2380 
2381   auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2382     if (directory.empty()) {
2383       return llvm::createStringError("invalid directory name");
2384     }
2385 
2386     replace_all(directory, "\\", "\\\\");
2387     replace_all(directory, "'", "\\'");
2388 
2389     // Make sure that Python has "directory" in the search path.
2390     StreamString command_stream;
2391     command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
2392                           "sys.path.insert(1,'%s');\n\n",
2393                           directory.c_str(), directory.c_str());
2394     bool syspath_retval =
2395         ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
2396     if (!syspath_retval)
2397       return llvm::createStringError("Python sys.path handling failed");
2398 
2399     return llvm::Error::success();
2400   };
2401 
2402   std::string module_name(pathname);
2403   bool possible_package = false;
2404 
2405   if (extra_search_dir) {
2406     if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2407       error = std::move(e);
2408       return false;
2409     }
2410   } else {
2411     FileSpec module_file(pathname);
2412     FileSystem::Instance().Resolve(module_file);
2413 
2414     fs::file_status st;
2415     std::error_code ec = status(module_file.GetPath(), st);
2416 
2417     if (ec || st.type() == fs::file_type::status_error ||
2418         st.type() == fs::file_type::type_unknown ||
2419         st.type() == fs::file_type::file_not_found) {
2420       // if not a valid file of any sort, check if it might be a filename still
2421       // dot can't be used but / and \ can, and if either is found, reject
2422       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2423         error.SetErrorStringWithFormatv("invalid pathname '{0}'", pathname);
2424         return false;
2425       }
2426       // Not a filename, probably a package of some sort, let it go through.
2427       possible_package = true;
2428     } else if (is_directory(st) || is_regular_file(st)) {
2429       if (module_file.GetDirectory().IsEmpty()) {
2430         error.SetErrorStringWithFormatv("invalid directory name '{0}'", pathname);
2431         return false;
2432       }
2433       if (llvm::Error e =
2434               ExtendSysPath(module_file.GetDirectory().GetCString())) {
2435         error = std::move(e);
2436         return false;
2437       }
2438       module_name = module_file.GetFilename().GetCString();
2439     } else {
2440       error.SetErrorString("no known way to import this module specification");
2441       return false;
2442     }
2443   }
2444 
2445   // Strip .py or .pyc extension
2446   llvm::StringRef extension = llvm::sys::path::extension(module_name);
2447   if (!extension.empty()) {
2448     if (extension == ".py")
2449       module_name.resize(module_name.length() - 3);
2450     else if (extension == ".pyc")
2451       module_name.resize(module_name.length() - 4);
2452   }
2453 
2454   if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2455     error.SetErrorStringWithFormat(
2456         "Python does not allow dots in module names: %s", module_name.c_str());
2457     return false;
2458   }
2459 
2460   if (module_name.find('-') != llvm::StringRef::npos) {
2461     error.SetErrorStringWithFormat(
2462         "Python discourages dashes in module names: %s", module_name.c_str());
2463     return false;
2464   }
2465 
2466   // Check if the module is already imported.
2467   StreamString command_stream;
2468   command_stream.Clear();
2469   command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
2470   bool does_contain = false;
2471   // This call will succeed if the module was ever imported in any Debugger in
2472   // the lifetime of the process in which this LLDB framework is living.
2473   const bool does_contain_executed = ExecuteOneLineWithReturn(
2474       command_stream.GetData(),
2475       ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options);
2476 
2477   const bool was_imported_globally = does_contain_executed && does_contain;
2478   const bool was_imported_locally =
2479       GetSessionDictionary()
2480           .GetItemForKey(PythonString(module_name))
2481           .IsAllocated();
2482 
2483   // now actually do the import
2484   command_stream.Clear();
2485 
2486   if (was_imported_globally || was_imported_locally) {
2487     if (!was_imported_locally)
2488       command_stream.Printf("import %s ; reload_module(%s)",
2489                             module_name.c_str(), module_name.c_str());
2490     else
2491       command_stream.Printf("reload_module(%s)", module_name.c_str());
2492   } else
2493     command_stream.Printf("import %s", module_name.c_str());
2494 
2495   error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
2496   if (error.Fail())
2497     return false;
2498 
2499   // if we are here, everything worked
2500   // call __lldb_init_module(debugger,dict)
2501   if (!SWIGBridge::LLDBSwigPythonCallModuleInit(
2502           module_name.c_str(), m_dictionary_name.c_str(),
2503           m_debugger.shared_from_this())) {
2504     error.SetErrorString("calling __lldb_init_module failed");
2505     return false;
2506   }
2507 
2508   if (module_sp) {
2509     // everything went just great, now set the module object
2510     command_stream.Clear();
2511     command_stream.Printf("%s", module_name.c_str());
2512     void *module_pyobj = nullptr;
2513     if (ExecuteOneLineWithReturn(
2514             command_stream.GetData(),
2515             ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2516             exc_options) &&
2517         module_pyobj)
2518       *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2519           PyRefType::Owned, static_cast<PyObject *>(module_pyobj)));
2520   }
2521 
2522   return true;
2523 }
2524 
2525 bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
2526   if (!word || !word[0])
2527     return false;
2528 
2529   llvm::StringRef word_sr(word);
2530 
2531   // filter out a few characters that would just confuse us and that are
2532   // clearly not keyword material anyway
2533   if (word_sr.find('"') != llvm::StringRef::npos ||
2534       word_sr.find('\'') != llvm::StringRef::npos)
2535     return false;
2536 
2537   StreamString command_stream;
2538   command_stream.Printf("keyword.iskeyword('%s')", word);
2539   bool result;
2540   ExecuteScriptOptions options;
2541   options.SetEnableIO(false);
2542   options.SetMaskoutErrors(true);
2543   options.SetSetLLDBGlobals(false);
2544   if (ExecuteOneLineWithReturn(command_stream.GetData(),
2545                                ScriptInterpreter::eScriptReturnTypeBool,
2546                                &result, options))
2547     return result;
2548   return false;
2549 }
2550 
2551 ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2552     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2553     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2554       m_old_asynch(debugger_sp->GetAsyncExecution()) {
2555   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2556     m_debugger_sp->SetAsyncExecution(false);
2557   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2558     m_debugger_sp->SetAsyncExecution(true);
2559 }
2560 
2561 ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
2562   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2563     m_debugger_sp->SetAsyncExecution(m_old_asynch);
2564 }
2565 
2566 bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2567     const char *impl_function, llvm::StringRef args,
2568     ScriptedCommandSynchronicity synchronicity,
2569     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2570     const lldb_private::ExecutionContext &exe_ctx) {
2571   if (!impl_function) {
2572     error.SetErrorString("no function to execute");
2573     return false;
2574   }
2575 
2576   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2577   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2578 
2579   if (!debugger_sp.get()) {
2580     error.SetErrorString("invalid Debugger pointer");
2581     return false;
2582   }
2583 
2584   bool ret_val = false;
2585 
2586   std::string err_msg;
2587 
2588   {
2589     Locker py_lock(this,
2590                    Locker::AcquireLock | Locker::InitSession |
2591                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2592                    Locker::FreeLock | Locker::TearDownSession);
2593 
2594     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2595 
2596     std::string args_str = args.str();
2597     ret_val = SWIGBridge::LLDBSwigPythonCallCommand(
2598         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2599         cmd_retobj, exe_ctx_ref_sp);
2600   }
2601 
2602   if (!ret_val)
2603     error.SetErrorString("unable to execute script function");
2604   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2605     return false;
2606 
2607   error.Clear();
2608   return ret_val;
2609 }
2610 
2611 bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2612     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
2613     ScriptedCommandSynchronicity synchronicity,
2614     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2615     const lldb_private::ExecutionContext &exe_ctx) {
2616   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2617     error.SetErrorString("no function to execute");
2618     return false;
2619   }
2620 
2621   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2622   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2623 
2624   if (!debugger_sp.get()) {
2625     error.SetErrorString("invalid Debugger pointer");
2626     return false;
2627   }
2628 
2629   bool ret_val = false;
2630 
2631   std::string err_msg;
2632 
2633   {
2634     Locker py_lock(this,
2635                    Locker::AcquireLock | Locker::InitSession |
2636                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2637                    Locker::FreeLock | Locker::TearDownSession);
2638 
2639     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2640 
2641     std::string args_str = args.str();
2642     ret_val = SWIGBridge::LLDBSwigPythonCallCommandObject(
2643         static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
2644         args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
2645   }
2646 
2647   if (!ret_val)
2648     error.SetErrorString("unable to execute script function");
2649   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2650     return false;
2651 
2652   error.Clear();
2653   return ret_val;
2654 }
2655 
2656 bool ScriptInterpreterPythonImpl::RunScriptBasedParsedCommand(
2657     StructuredData::GenericSP impl_obj_sp, Args &args,
2658     ScriptedCommandSynchronicity synchronicity,
2659     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2660     const lldb_private::ExecutionContext &exe_ctx) {
2661   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2662     error.SetErrorString("no function to execute");
2663     return false;
2664   }
2665 
2666   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2667   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2668 
2669   if (!debugger_sp.get()) {
2670     error.SetErrorString("invalid Debugger pointer");
2671     return false;
2672   }
2673 
2674   bool ret_val = false;
2675 
2676   std::string err_msg;
2677 
2678   {
2679     Locker py_lock(this,
2680                    Locker::AcquireLock | Locker::InitSession |
2681                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2682                    Locker::FreeLock | Locker::TearDownSession);
2683 
2684     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2685 
2686     StructuredData::ArraySP args_arr_sp(new StructuredData::Array());
2687 
2688     for (const Args::ArgEntry &entry : args) {
2689       args_arr_sp->AddStringItem(entry.ref());
2690     }
2691     StructuredDataImpl args_impl(args_arr_sp);
2692 
2693     ret_val = SWIGBridge::LLDBSwigPythonCallParsedCommandObject(
2694         static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
2695         args_impl, cmd_retobj, exe_ctx_ref_sp);
2696   }
2697 
2698   if (!ret_val)
2699     error.SetErrorString("unable to execute script function");
2700   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2701     return false;
2702 
2703   error.Clear();
2704   return ret_val;
2705 }
2706 
2707 std::optional<std::string>
2708 ScriptInterpreterPythonImpl::GetRepeatCommandForScriptedCommand(
2709     StructuredData::GenericSP impl_obj_sp, Args &args) {
2710   if (!impl_obj_sp || !impl_obj_sp->IsValid())
2711     return std::nullopt;
2712 
2713   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2714 
2715   if (!debugger_sp.get())
2716     return std::nullopt;
2717 
2718   std::optional<std::string> ret_val;
2719 
2720   {
2721     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
2722                    Locker::FreeLock);
2723 
2724     StructuredData::ArraySP args_arr_sp(new StructuredData::Array());
2725 
2726     // For scripting commands, we send the command string:
2727     std::string command;
2728     args.GetQuotedCommandString(command);
2729     ret_val = SWIGBridge::LLDBSwigPythonGetRepeatCommandForScriptedCommand(
2730         static_cast<PyObject *>(impl_obj_sp->GetValue()), command);
2731   }
2732   return ret_val;
2733 }
2734 
2735 /// In Python, a special attribute __doc__ contains the docstring for an object
2736 /// (function, method, class, ...) if any is defined Otherwise, the attribute's
2737 /// value is None.
2738 bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
2739                                                           std::string &dest) {
2740   dest.clear();
2741 
2742   if (!item || !*item)
2743     return false;
2744 
2745   std::string command(item);
2746   command += ".__doc__";
2747 
2748   // Python is going to point this to valid data if ExecuteOneLineWithReturn
2749   // returns successfully.
2750   char *result_ptr = nullptr;
2751 
2752   if (ExecuteOneLineWithReturn(
2753           command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
2754           &result_ptr,
2755           ExecuteScriptOptions().SetEnableIO(false))) {
2756     if (result_ptr)
2757       dest.assign(result_ptr);
2758     return true;
2759   }
2760 
2761   StreamString str_stream;
2762   str_stream << "Function " << item
2763              << " was not found. Containing module might be missing.";
2764   dest = std::string(str_stream.GetString());
2765 
2766   return false;
2767 }
2768 
2769 bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
2770     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2771   dest.clear();
2772 
2773   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2774 
2775   if (!cmd_obj_sp)
2776     return false;
2777 
2778   PythonObject implementor(PyRefType::Borrowed,
2779                            (PyObject *)cmd_obj_sp->GetValue());
2780 
2781   if (!implementor.IsAllocated())
2782     return false;
2783 
2784   llvm::Expected<PythonObject> expected_py_return =
2785       implementor.CallMethod("get_short_help");
2786 
2787   if (!expected_py_return) {
2788     llvm::consumeError(expected_py_return.takeError());
2789     return false;
2790   }
2791 
2792   PythonObject py_return = std::move(expected_py_return.get());
2793 
2794   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2795     PythonString py_string(PyRefType::Borrowed, py_return.get());
2796     llvm::StringRef return_data(py_string.GetString());
2797     dest.assign(return_data.data(), return_data.size());
2798     return true;
2799   }
2800 
2801   return false;
2802 }
2803 
2804 uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
2805     StructuredData::GenericSP cmd_obj_sp) {
2806   uint32_t result = 0;
2807 
2808   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2809 
2810   static char callee_name[] = "get_flags";
2811 
2812   if (!cmd_obj_sp)
2813     return result;
2814 
2815   PythonObject implementor(PyRefType::Borrowed,
2816                            (PyObject *)cmd_obj_sp->GetValue());
2817 
2818   if (!implementor.IsAllocated())
2819     return result;
2820 
2821   PythonObject pmeth(PyRefType::Owned,
2822                      PyObject_GetAttrString(implementor.get(), callee_name));
2823 
2824   if (PyErr_Occurred())
2825     PyErr_Clear();
2826 
2827   if (!pmeth.IsAllocated())
2828     return result;
2829 
2830   if (PyCallable_Check(pmeth.get()) == 0) {
2831     if (PyErr_Occurred())
2832       PyErr_Clear();
2833     return result;
2834   }
2835 
2836   if (PyErr_Occurred())
2837     PyErr_Clear();
2838 
2839   long long py_return = unwrapOrSetPythonException(
2840       As<long long>(implementor.CallMethod(callee_name)));
2841 
2842   // if it fails, print the error but otherwise go on
2843   if (PyErr_Occurred()) {
2844     PyErr_Print();
2845     PyErr_Clear();
2846   } else {
2847     result = py_return;
2848   }
2849 
2850   return result;
2851 }
2852 
2853 StructuredData::ObjectSP
2854 ScriptInterpreterPythonImpl::GetOptionsForCommandObject(
2855     StructuredData::GenericSP cmd_obj_sp) {
2856   StructuredData::ObjectSP result = {};
2857 
2858   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2859 
2860   static char callee_name[] = "get_options_definition";
2861 
2862   if (!cmd_obj_sp)
2863     return result;
2864 
2865   PythonObject implementor(PyRefType::Borrowed,
2866                            (PyObject *)cmd_obj_sp->GetValue());
2867 
2868   if (!implementor.IsAllocated())
2869     return result;
2870 
2871   PythonObject pmeth(PyRefType::Owned,
2872                      PyObject_GetAttrString(implementor.get(), callee_name));
2873 
2874   if (PyErr_Occurred())
2875     PyErr_Clear();
2876 
2877   if (!pmeth.IsAllocated())
2878     return result;
2879 
2880   if (PyCallable_Check(pmeth.get()) == 0) {
2881     if (PyErr_Occurred())
2882       PyErr_Clear();
2883     return result;
2884   }
2885 
2886   if (PyErr_Occurred())
2887     PyErr_Clear();
2888 
2889   PythonDictionary py_return = unwrapOrSetPythonException(
2890       As<PythonDictionary>(implementor.CallMethod(callee_name)));
2891 
2892   // if it fails, print the error but otherwise go on
2893   if (PyErr_Occurred()) {
2894     PyErr_Print();
2895     PyErr_Clear();
2896     return {};
2897   }
2898     return py_return.CreateStructuredObject();
2899 }
2900 
2901 StructuredData::ObjectSP
2902 ScriptInterpreterPythonImpl::GetArgumentsForCommandObject(
2903     StructuredData::GenericSP cmd_obj_sp) {
2904   StructuredData::ObjectSP result = {};
2905 
2906   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2907 
2908   static char callee_name[] = "get_args_definition";
2909 
2910   if (!cmd_obj_sp)
2911     return result;
2912 
2913   PythonObject implementor(PyRefType::Borrowed,
2914                            (PyObject *)cmd_obj_sp->GetValue());
2915 
2916   if (!implementor.IsAllocated())
2917     return result;
2918 
2919   PythonObject pmeth(PyRefType::Owned,
2920                      PyObject_GetAttrString(implementor.get(), callee_name));
2921 
2922   if (PyErr_Occurred())
2923     PyErr_Clear();
2924 
2925   if (!pmeth.IsAllocated())
2926     return result;
2927 
2928   if (PyCallable_Check(pmeth.get()) == 0) {
2929     if (PyErr_Occurred())
2930       PyErr_Clear();
2931     return result;
2932   }
2933 
2934   if (PyErr_Occurred())
2935     PyErr_Clear();
2936 
2937   PythonList py_return = unwrapOrSetPythonException(
2938       As<PythonList>(implementor.CallMethod(callee_name)));
2939 
2940   // if it fails, print the error but otherwise go on
2941   if (PyErr_Occurred()) {
2942     PyErr_Print();
2943     PyErr_Clear();
2944     return {};
2945   }
2946     return py_return.CreateStructuredObject();
2947 }
2948 
2949 void
2950 ScriptInterpreterPythonImpl::OptionParsingStartedForCommandObject(
2951     StructuredData::GenericSP cmd_obj_sp) {
2952 
2953   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2954 
2955   static char callee_name[] = "option_parsing_started";
2956 
2957   if (!cmd_obj_sp)
2958     return ;
2959 
2960   PythonObject implementor(PyRefType::Borrowed,
2961                            (PyObject *)cmd_obj_sp->GetValue());
2962 
2963   if (!implementor.IsAllocated())
2964     return;
2965 
2966   PythonObject pmeth(PyRefType::Owned,
2967                      PyObject_GetAttrString(implementor.get(), callee_name));
2968 
2969   if (PyErr_Occurred())
2970     PyErr_Clear();
2971 
2972   if (!pmeth.IsAllocated())
2973     return;
2974 
2975   if (PyCallable_Check(pmeth.get()) == 0) {
2976     if (PyErr_Occurred())
2977       PyErr_Clear();
2978     return;
2979   }
2980 
2981   if (PyErr_Occurred())
2982     PyErr_Clear();
2983 
2984   // option_parsing_starting doesn't return anything, ignore anything but
2985   // python errors.
2986   unwrapOrSetPythonException(
2987       As<bool>(implementor.CallMethod(callee_name)));
2988 
2989   // if it fails, print the error but otherwise go on
2990   if (PyErr_Occurred()) {
2991     PyErr_Print();
2992     PyErr_Clear();
2993     return;
2994   }
2995 }
2996 
2997 bool
2998 ScriptInterpreterPythonImpl::SetOptionValueForCommandObject(
2999     StructuredData::GenericSP cmd_obj_sp, ExecutionContext *exe_ctx,
3000     llvm::StringRef long_option, llvm::StringRef value) {
3001   StructuredData::ObjectSP result = {};
3002 
3003   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3004 
3005   static char callee_name[] = "set_option_value";
3006 
3007   if (!cmd_obj_sp)
3008     return false;
3009 
3010   PythonObject implementor(PyRefType::Borrowed,
3011                            (PyObject *)cmd_obj_sp->GetValue());
3012 
3013   if (!implementor.IsAllocated())
3014     return false;
3015 
3016   PythonObject pmeth(PyRefType::Owned,
3017                      PyObject_GetAttrString(implementor.get(), callee_name));
3018 
3019   if (PyErr_Occurred())
3020     PyErr_Clear();
3021 
3022   if (!pmeth.IsAllocated())
3023     return false;
3024 
3025   if (PyCallable_Check(pmeth.get()) == 0) {
3026     if (PyErr_Occurred())
3027       PyErr_Clear();
3028     return false;
3029   }
3030 
3031   if (PyErr_Occurred())
3032     PyErr_Clear();
3033 
3034   lldb::ExecutionContextRefSP exe_ctx_ref_sp;
3035   if (exe_ctx)
3036     exe_ctx_ref_sp.reset(new ExecutionContextRef(exe_ctx));
3037   PythonObject ctx_ref_obj = SWIGBridge::ToSWIGWrapper(exe_ctx_ref_sp);
3038 
3039   bool py_return = unwrapOrSetPythonException(
3040       As<bool>(implementor.CallMethod(callee_name, ctx_ref_obj, long_option.str().c_str(),
3041                                       value.str().c_str())));
3042 
3043   // if it fails, print the error but otherwise go on
3044   if (PyErr_Occurred()) {
3045     PyErr_Print();
3046     PyErr_Clear();
3047     return false;
3048   }
3049   return py_return;
3050 }
3051 
3052 bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3053     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
3054   dest.clear();
3055 
3056   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3057 
3058   if (!cmd_obj_sp)
3059     return false;
3060 
3061   PythonObject implementor(PyRefType::Borrowed,
3062                            (PyObject *)cmd_obj_sp->GetValue());
3063 
3064   if (!implementor.IsAllocated())
3065     return false;
3066 
3067   llvm::Expected<PythonObject> expected_py_return =
3068       implementor.CallMethod("get_long_help");
3069 
3070   if (!expected_py_return) {
3071     llvm::consumeError(expected_py_return.takeError());
3072     return false;
3073   }
3074 
3075   PythonObject py_return = std::move(expected_py_return.get());
3076 
3077   bool got_string = false;
3078   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3079     PythonString str(PyRefType::Borrowed, py_return.get());
3080     llvm::StringRef str_data(str.GetString());
3081     dest.assign(str_data.data(), str_data.size());
3082     got_string = true;
3083   }
3084 
3085   return got_string;
3086 }
3087 
3088 std::unique_ptr<ScriptInterpreterLocker>
3089 ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3090   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3091       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3092       Locker::FreeLock | Locker::TearDownSession));
3093   return py_lock;
3094 }
3095 
3096 void ScriptInterpreterPythonImpl::Initialize() {
3097   LLDB_SCOPED_TIMER();
3098 
3099   // RAII-based initialization which correctly handles multiple-initialization,
3100   // version- specific differences among Python 2 and Python 3, and saving and
3101   // restoring various other pieces of state that can get mucked with during
3102   // initialization.
3103   InitializePythonRAII initialize_guard;
3104 
3105   LLDBSwigPyInit();
3106 
3107   // Update the path python uses to search for modules to include the current
3108   // directory.
3109 
3110   PyRun_SimpleString("import sys");
3111   AddToSysPath(AddLocation::End, ".");
3112 
3113   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
3114   // that use a backslash as the path separator, this will result in executing
3115   // python code containing paths with unescaped backslashes.  But Python also
3116   // accepts forward slashes, so to make life easier we just use that.
3117   if (FileSpec file_spec = GetPythonDir())
3118     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3119   if (FileSpec file_spec = HostInfo::GetShlibDir())
3120     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3121 
3122   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3123                      "lldb.embedded_interpreter; from "
3124                      "lldb.embedded_interpreter import run_python_interpreter; "
3125                      "from lldb.embedded_interpreter import run_one_line");
3126 
3127 #if LLDB_USE_PYTHON_SET_INTERRUPT
3128   // Python will not just overwrite its internal SIGINT handler but also the
3129   // one from the process. Backup the current SIGINT handler to prevent that
3130   // Python deletes it.
3131   RestoreSignalHandlerScope save_sigint(SIGINT);
3132 
3133   // Setup a default SIGINT signal handler that works the same way as the
3134   // normal Python REPL signal handler which raises a KeyboardInterrupt.
3135   // Also make sure to not pollute the user's REPL with the signal module nor
3136   // our utility function.
3137   PyRun_SimpleString("def lldb_setup_sigint_handler():\n"
3138                      "  import signal;\n"
3139                      "  def signal_handler(sig, frame):\n"
3140                      "    raise KeyboardInterrupt()\n"
3141                      "  signal.signal(signal.SIGINT, signal_handler);\n"
3142                      "lldb_setup_sigint_handler();\n"
3143                      "del lldb_setup_sigint_handler\n");
3144 #endif
3145 }
3146 
3147 void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3148                                                std::string path) {
3149   std::string path_copy;
3150 
3151   std::string statement;
3152   if (location == AddLocation::Beginning) {
3153     statement.assign("sys.path.insert(0,\"");
3154     statement.append(path);
3155     statement.append("\")");
3156   } else {
3157     statement.assign("sys.path.append(\"");
3158     statement.append(path);
3159     statement.append("\")");
3160   }
3161   PyRun_SimpleString(statement.c_str());
3162 }
3163 
3164 // We are intentionally NOT calling Py_Finalize here (this would be the logical
3165 // place to call it).  Calling Py_Finalize here causes test suite runs to seg
3166 // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
3167 // be called 'at_exit'.  When the test suite Python harness finishes up, it
3168 // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3169 // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3170 // which calls ScriptInterpreter::Terminate, which calls
3171 // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
3172 // end up with Py_Finalize being called from within Py_Finalize, which results
3173 // in a seg fault. Since this function only gets called when lldb is shutting
3174 // down and going away anyway, the fact that we don't actually call Py_Finalize
3175 // should not cause any problems (everything should shut down/go away anyway
3176 // when the process exits).
3177 //
3178 // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3179 
3180 #endif
3181