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