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