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