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