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