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