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