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