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   // PyErr_SetInterrupt was introduced in 3.2.
1071 #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
1072   // If the interpreter isn't evaluating any Python at the moment then return
1073   // false to signal that this function didn't handle the interrupt and the
1074   // next component should try handling it.
1075   if (!IsExecutingPython())
1076     return false;
1077 
1078   // Tell Python that it should pretend to have received a SIGINT.
1079   PyErr_SetInterrupt();
1080   // PyErr_SetInterrupt has no way to return an error so we can only pretend the
1081   // signal got successfully handled and return true.
1082   // Python 3.10 introduces PyErr_SetInterruptEx that could return an error, but
1083   // the error handling is limited to checking the arguments which would be
1084   // just our (hardcoded) input signal code SIGINT, so that's not useful at all.
1085   return true;
1086 #else
1087   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
1088 
1089   if (IsExecutingPython()) {
1090     PyThreadState *state = PyThreadState_GET();
1091     if (!state)
1092       state = GetThreadState();
1093     if (state) {
1094       long tid = state->thread_id;
1095       PyThreadState_Swap(state);
1096       int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
1097       LLDB_LOGF(log,
1098                 "ScriptInterpreterPythonImpl::Interrupt() sending "
1099                 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
1100                 tid, num_threads);
1101       return true;
1102     }
1103   }
1104   LLDB_LOGF(log,
1105             "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
1106             "can't interrupt");
1107   return false;
1108 #endif
1109 }
1110 
1111 bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
1112     llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
1113     void *ret_value, const ExecuteScriptOptions &options) {
1114 
1115   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1116       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1117           options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1118 
1119   if (!io_redirect_or_error) {
1120     llvm::consumeError(io_redirect_or_error.takeError());
1121     return false;
1122   }
1123 
1124   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1125 
1126   Locker locker(this,
1127                 Locker::AcquireLock | Locker::InitSession |
1128                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1129                     Locker::NoSTDIN,
1130                 Locker::FreeAcquiredLock | Locker::TearDownSession,
1131                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1132                 io_redirect.GetErrorFile());
1133 
1134   PythonModule &main_module = GetMainModule();
1135   PythonDictionary globals = main_module.GetDictionary();
1136 
1137   PythonDictionary locals = GetSessionDictionary();
1138   if (!locals.IsValid())
1139     locals = unwrapIgnoringErrors(
1140         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1141   if (!locals.IsValid())
1142     locals = globals;
1143 
1144   Expected<PythonObject> maybe_py_return =
1145       runStringOneLine(in_string, globals, locals);
1146 
1147   if (!maybe_py_return) {
1148     llvm::handleAllErrors(
1149         maybe_py_return.takeError(),
1150         [&](PythonException &E) {
1151           E.Restore();
1152           if (options.GetMaskoutErrors()) {
1153             if (E.Matches(PyExc_SyntaxError)) {
1154               PyErr_Print();
1155             }
1156             PyErr_Clear();
1157           }
1158         },
1159         [](const llvm::ErrorInfoBase &E) {});
1160     return false;
1161   }
1162 
1163   PythonObject py_return = std::move(maybe_py_return.get());
1164   assert(py_return.IsValid());
1165 
1166   switch (return_type) {
1167   case eScriptReturnTypeCharPtr: // "char *"
1168   {
1169     const char format[3] = "s#";
1170     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
1171   }
1172   case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
1173                                        // Py_None
1174   {
1175     const char format[3] = "z";
1176     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
1177   }
1178   case eScriptReturnTypeBool: {
1179     const char format[2] = "b";
1180     return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
1181   }
1182   case eScriptReturnTypeShortInt: {
1183     const char format[2] = "h";
1184     return PyArg_Parse(py_return.get(), format, (short *)ret_value);
1185   }
1186   case eScriptReturnTypeShortIntUnsigned: {
1187     const char format[2] = "H";
1188     return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
1189   }
1190   case eScriptReturnTypeInt: {
1191     const char format[2] = "i";
1192     return PyArg_Parse(py_return.get(), format, (int *)ret_value);
1193   }
1194   case eScriptReturnTypeIntUnsigned: {
1195     const char format[2] = "I";
1196     return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
1197   }
1198   case eScriptReturnTypeLongInt: {
1199     const char format[2] = "l";
1200     return PyArg_Parse(py_return.get(), format, (long *)ret_value);
1201   }
1202   case eScriptReturnTypeLongIntUnsigned: {
1203     const char format[2] = "k";
1204     return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
1205   }
1206   case eScriptReturnTypeLongLong: {
1207     const char format[2] = "L";
1208     return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
1209   }
1210   case eScriptReturnTypeLongLongUnsigned: {
1211     const char format[2] = "K";
1212     return PyArg_Parse(py_return.get(), format,
1213                        (unsigned long long *)ret_value);
1214   }
1215   case eScriptReturnTypeFloat: {
1216     const char format[2] = "f";
1217     return PyArg_Parse(py_return.get(), format, (float *)ret_value);
1218   }
1219   case eScriptReturnTypeDouble: {
1220     const char format[2] = "d";
1221     return PyArg_Parse(py_return.get(), format, (double *)ret_value);
1222   }
1223   case eScriptReturnTypeChar: {
1224     const char format[2] = "c";
1225     return PyArg_Parse(py_return.get(), format, (char *)ret_value);
1226   }
1227   case eScriptReturnTypeOpaqueObject: {
1228     *((PyObject **)ret_value) = py_return.release();
1229     return true;
1230   }
1231   }
1232   llvm_unreachable("Fully covered switch!");
1233 }
1234 
1235 Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1236     const char *in_string, const ExecuteScriptOptions &options) {
1237 
1238   if (in_string == nullptr)
1239     return Status();
1240 
1241   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1242       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1243           options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1244 
1245   if (!io_redirect_or_error)
1246     return Status(io_redirect_or_error.takeError());
1247 
1248   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1249 
1250   Locker locker(this,
1251                 Locker::AcquireLock | Locker::InitSession |
1252                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1253                     Locker::NoSTDIN,
1254                 Locker::FreeAcquiredLock | Locker::TearDownSession,
1255                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1256                 io_redirect.GetErrorFile());
1257 
1258   PythonModule &main_module = GetMainModule();
1259   PythonDictionary globals = main_module.GetDictionary();
1260 
1261   PythonDictionary locals = GetSessionDictionary();
1262   if (!locals.IsValid())
1263     locals = unwrapIgnoringErrors(
1264         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1265   if (!locals.IsValid())
1266     locals = globals;
1267 
1268   Expected<PythonObject> return_value =
1269       runStringMultiLine(in_string, globals, locals);
1270 
1271   if (!return_value) {
1272     llvm::Error error =
1273         llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
1274           llvm::Error error = llvm::createStringError(
1275               llvm::inconvertibleErrorCode(), E.ReadBacktrace());
1276           if (!options.GetMaskoutErrors())
1277             E.Restore();
1278           return error;
1279         });
1280     return Status(std::move(error));
1281   }
1282 
1283   return Status();
1284 }
1285 
1286 void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1287     std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1288     CommandReturnObject &result) {
1289   m_active_io_handler = eIOHandlerBreakpoint;
1290   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1291       "    ", *this, &bp_options_vec);
1292 }
1293 
1294 void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1295     WatchpointOptions *wp_options, CommandReturnObject &result) {
1296   m_active_io_handler = eIOHandlerWatchpoint;
1297   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1298       "    ", *this, wp_options);
1299 }
1300 
1301 Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1302     BreakpointOptions &bp_options, const char *function_name,
1303     StructuredData::ObjectSP extra_args_sp) {
1304   Status error;
1305   // For now just cons up a oneliner that calls the provided function.
1306   std::string oneliner("return ");
1307   oneliner += function_name;
1308 
1309   llvm::Expected<unsigned> maybe_args =
1310       GetMaxPositionalArgumentsForCallable(function_name);
1311   if (!maybe_args) {
1312     error.SetErrorStringWithFormat(
1313         "could not get num args: %s",
1314         llvm::toString(maybe_args.takeError()).c_str());
1315     return error;
1316   }
1317   size_t max_args = *maybe_args;
1318 
1319   bool uses_extra_args = false;
1320   if (max_args >= 4) {
1321     uses_extra_args = true;
1322     oneliner += "(frame, bp_loc, extra_args, internal_dict)";
1323   } else if (max_args >= 3) {
1324     if (extra_args_sp) {
1325       error.SetErrorString("cannot pass extra_args to a three argument callback"
1326                           );
1327       return error;
1328     }
1329     uses_extra_args = false;
1330     oneliner += "(frame, bp_loc, internal_dict)";
1331   } else {
1332     error.SetErrorStringWithFormat("expected 3 or 4 argument "
1333                                    "function, %s can only take %zu",
1334                                    function_name, max_args);
1335     return error;
1336   }
1337 
1338   SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp,
1339                                uses_extra_args);
1340   return error;
1341 }
1342 
1343 Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1344     BreakpointOptions &bp_options,
1345     std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
1346   Status error;
1347   error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1348                                                 cmd_data_up->script_source,
1349                                                 false);
1350   if (error.Fail()) {
1351     return error;
1352   }
1353   auto baton_sp =
1354       std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1355   bp_options.SetCallback(
1356       ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1357   return error;
1358 }
1359 
1360 Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1361     BreakpointOptions &bp_options, const char *command_body_text) {
1362   return SetBreakpointCommandCallback(bp_options, command_body_text, {},false);
1363 }
1364 
1365 // Set a Python one-liner as the callback for the breakpoint.
1366 Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1367     BreakpointOptions &bp_options, const char *command_body_text,
1368     StructuredData::ObjectSP extra_args_sp, bool uses_extra_args) {
1369   auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1370   // Split the command_body_text into lines, and pass that to
1371   // GenerateBreakpointCommandCallbackData.  That will wrap the body in an
1372   // auto-generated function, and return the function name in script_source.
1373   // That is what the callback will actually invoke.
1374 
1375   data_up->user_source.SplitIntoLines(command_body_text);
1376   Status error = GenerateBreakpointCommandCallbackData(data_up->user_source,
1377                                                        data_up->script_source,
1378                                                        uses_extra_args);
1379   if (error.Success()) {
1380     auto baton_sp =
1381         std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1382     bp_options.SetCallback(
1383         ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1384     return error;
1385   }
1386   return error;
1387 }
1388 
1389 // Set a Python one-liner as the callback for the watchpoint.
1390 void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1391     WatchpointOptions *wp_options, const char *oneliner) {
1392   auto data_up = std::make_unique<WatchpointOptions::CommandData>();
1393 
1394   // It's necessary to set both user_source and script_source to the oneliner.
1395   // The former is used to generate callback description (as in watchpoint
1396   // command list) while the latter is used for Python to interpret during the
1397   // actual callback.
1398 
1399   data_up->user_source.AppendString(oneliner);
1400   data_up->script_source.assign(oneliner);
1401 
1402   if (GenerateWatchpointCommandCallbackData(data_up->user_source,
1403                                             data_up->script_source)) {
1404     auto baton_sp =
1405         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
1406     wp_options->SetCallback(
1407         ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
1408   }
1409 
1410   return;
1411 }
1412 
1413 Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1414     StringList &function_def) {
1415   // Convert StringList to one long, newline delimited, const char *.
1416   std::string function_def_string(function_def.CopyList());
1417 
1418   Status error = ExecuteMultipleLines(
1419       function_def_string.c_str(),
1420       ExecuteScriptOptions().SetEnableIO(false));
1421   return error;
1422 }
1423 
1424 Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature,
1425                                                      const StringList &input) {
1426   Status error;
1427   int num_lines = input.GetSize();
1428   if (num_lines == 0) {
1429     error.SetErrorString("No input data.");
1430     return error;
1431   }
1432 
1433   if (!signature || *signature == 0) {
1434     error.SetErrorString("No output function name.");
1435     return error;
1436   }
1437 
1438   StreamString sstr;
1439   StringList auto_generated_function;
1440   auto_generated_function.AppendString(signature);
1441   auto_generated_function.AppendString(
1442       "     global_dict = globals()"); // Grab the global dictionary
1443   auto_generated_function.AppendString(
1444       "     new_keys = internal_dict.keys()"); // Make a list of keys in the
1445                                                // session dict
1446   auto_generated_function.AppendString(
1447       "     old_keys = global_dict.keys()"); // Save list of keys in global dict
1448   auto_generated_function.AppendString(
1449       "     global_dict.update (internal_dict)"); // Add the session dictionary
1450                                                   // to the
1451   // global dictionary.
1452 
1453   // Wrap everything up inside the function, increasing the indentation.
1454 
1455   auto_generated_function.AppendString("     if True:");
1456   for (int i = 0; i < num_lines; ++i) {
1457     sstr.Clear();
1458     sstr.Printf("       %s", input.GetStringAtIndex(i));
1459     auto_generated_function.AppendString(sstr.GetData());
1460   }
1461   auto_generated_function.AppendString(
1462       "     for key in new_keys:"); // Iterate over all the keys from session
1463                                     // dict
1464   auto_generated_function.AppendString(
1465       "         internal_dict[key] = global_dict[key]"); // Update session dict
1466                                                          // values
1467   auto_generated_function.AppendString(
1468       "         if key not in old_keys:"); // If key was not originally in
1469                                            // global dict
1470   auto_generated_function.AppendString(
1471       "             del global_dict[key]"); //  ...then remove key/value from
1472                                             //  global dict
1473 
1474   // Verify that the results are valid Python.
1475 
1476   error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
1477 
1478   return error;
1479 }
1480 
1481 bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1482     StringList &user_input, std::string &output, const void *name_token) {
1483   static uint32_t num_created_functions = 0;
1484   user_input.RemoveBlankLines();
1485   StreamString sstr;
1486 
1487   // Check to see if we have any data; if not, just return.
1488   if (user_input.GetSize() == 0)
1489     return false;
1490 
1491   // Take what the user wrote, wrap it all up inside one big auto-generated
1492   // Python function, passing in the ValueObject as parameter to the function.
1493 
1494   std::string auto_generated_function_name(
1495       GenerateUniqueName("lldb_autogen_python_type_print_func",
1496                          num_created_functions, name_token));
1497   sstr.Printf("def %s (valobj, internal_dict):",
1498               auto_generated_function_name.c_str());
1499 
1500   if (!GenerateFunction(sstr.GetData(), user_input).Success())
1501     return false;
1502 
1503   // Store the name of the auto-generated function to be called.
1504   output.assign(auto_generated_function_name);
1505   return true;
1506 }
1507 
1508 bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1509     StringList &user_input, std::string &output) {
1510   static uint32_t num_created_functions = 0;
1511   user_input.RemoveBlankLines();
1512   StreamString sstr;
1513 
1514   // Check to see if we have any data; if not, just return.
1515   if (user_input.GetSize() == 0)
1516     return false;
1517 
1518   std::string auto_generated_function_name(GenerateUniqueName(
1519       "lldb_autogen_python_cmd_alias_func", num_created_functions));
1520 
1521   sstr.Printf("def %s (debugger, args, result, internal_dict):",
1522               auto_generated_function_name.c_str());
1523 
1524   if (!GenerateFunction(sstr.GetData(), user_input).Success())
1525     return false;
1526 
1527   // Store the name of the auto-generated function to be called.
1528   output.assign(auto_generated_function_name);
1529   return true;
1530 }
1531 
1532 bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1533     StringList &user_input, std::string &output, const void *name_token) {
1534   static uint32_t num_created_classes = 0;
1535   user_input.RemoveBlankLines();
1536   int num_lines = user_input.GetSize();
1537   StreamString sstr;
1538 
1539   // Check to see if we have any data; if not, just return.
1540   if (user_input.GetSize() == 0)
1541     return false;
1542 
1543   // Wrap all user input into a Python class
1544 
1545   std::string auto_generated_class_name(GenerateUniqueName(
1546       "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1547 
1548   StringList auto_generated_class;
1549 
1550   // Create the function name & definition string.
1551 
1552   sstr.Printf("class %s:", auto_generated_class_name.c_str());
1553   auto_generated_class.AppendString(sstr.GetString());
1554 
1555   // Wrap everything up inside the class, increasing the indentation. we don't
1556   // need to play any fancy indentation tricks here because there is no
1557   // surrounding code whose indentation we need to honor
1558   for (int i = 0; i < num_lines; ++i) {
1559     sstr.Clear();
1560     sstr.Printf("     %s", user_input.GetStringAtIndex(i));
1561     auto_generated_class.AppendString(sstr.GetString());
1562   }
1563 
1564   // Verify that the results are valid Python. (even though the method is
1565   // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1566   // (TODO: rename that method to ExportDefinitionToInterpreter)
1567   if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
1568     return false;
1569 
1570   // Store the name of the auto-generated class
1571 
1572   output.assign(auto_generated_class_name);
1573   return true;
1574 }
1575 
1576 StructuredData::GenericSP
1577 ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
1578   if (class_name == nullptr || class_name[0] == '\0')
1579     return StructuredData::GenericSP();
1580 
1581   void *ret_val;
1582 
1583   {
1584     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
1585                    Locker::FreeLock);
1586     ret_val = LLDBSWIGPython_CreateFrameRecognizer(class_name,
1587                                                    m_dictionary_name.c_str());
1588   }
1589 
1590   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
1591 }
1592 
1593 lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
1594     const StructuredData::ObjectSP &os_plugin_object_sp,
1595     lldb::StackFrameSP frame_sp) {
1596   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1597 
1598   if (!os_plugin_object_sp)
1599     return ValueObjectListSP();
1600 
1601   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1602   if (!generic)
1603     return nullptr;
1604 
1605   PythonObject implementor(PyRefType::Borrowed,
1606                            (PyObject *)generic->GetValue());
1607 
1608   if (!implementor.IsAllocated())
1609     return ValueObjectListSP();
1610 
1611   PythonObject py_return(PyRefType::Owned,
1612                          (PyObject *)LLDBSwigPython_GetRecognizedArguments(
1613                              implementor.get(), frame_sp));
1614 
1615   // if it fails, print the error but otherwise go on
1616   if (PyErr_Occurred()) {
1617     PyErr_Print();
1618     PyErr_Clear();
1619   }
1620   if (py_return.get()) {
1621     PythonList result_list(PyRefType::Borrowed, py_return.get());
1622     ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
1623     for (size_t i = 0; i < result_list.GetSize(); i++) {
1624       PyObject *item = result_list.GetItemAtIndex(i).get();
1625       lldb::SBValue *sb_value_ptr =
1626           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
1627       auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
1628       if (valobj_sp)
1629         result->Append(valobj_sp);
1630     }
1631     return result;
1632   }
1633   return ValueObjectListSP();
1634 }
1635 
1636 StructuredData::GenericSP
1637 ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject(
1638     const char *class_name, lldb::ProcessSP process_sp) {
1639   if (class_name == nullptr || class_name[0] == '\0')
1640     return StructuredData::GenericSP();
1641 
1642   if (!process_sp)
1643     return StructuredData::GenericSP();
1644 
1645   void *ret_val;
1646 
1647   {
1648     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
1649                    Locker::FreeLock);
1650     ret_val = LLDBSWIGPythonCreateOSPlugin(
1651         class_name, m_dictionary_name.c_str(), process_sp);
1652   }
1653 
1654   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
1655 }
1656 
1657 StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo(
1658     StructuredData::ObjectSP os_plugin_object_sp) {
1659   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1660 
1661   static char callee_name[] = "get_register_info";
1662 
1663   if (!os_plugin_object_sp)
1664     return StructuredData::DictionarySP();
1665 
1666   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1667   if (!generic)
1668     return nullptr;
1669 
1670   PythonObject implementor(PyRefType::Borrowed,
1671                            (PyObject *)generic->GetValue());
1672 
1673   if (!implementor.IsAllocated())
1674     return StructuredData::DictionarySP();
1675 
1676   PythonObject pmeth(PyRefType::Owned,
1677                      PyObject_GetAttrString(implementor.get(), callee_name));
1678 
1679   if (PyErr_Occurred())
1680     PyErr_Clear();
1681 
1682   if (!pmeth.IsAllocated())
1683     return StructuredData::DictionarySP();
1684 
1685   if (PyCallable_Check(pmeth.get()) == 0) {
1686     if (PyErr_Occurred())
1687       PyErr_Clear();
1688 
1689     return StructuredData::DictionarySP();
1690   }
1691 
1692   if (PyErr_Occurred())
1693     PyErr_Clear();
1694 
1695   // right now we know this function exists and is callable..
1696   PythonObject py_return(
1697       PyRefType::Owned,
1698       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
1699 
1700   // if it fails, print the error but otherwise go on
1701   if (PyErr_Occurred()) {
1702     PyErr_Print();
1703     PyErr_Clear();
1704   }
1705   if (py_return.get()) {
1706     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1707     return result_dict.CreateStructuredDictionary();
1708   }
1709   return StructuredData::DictionarySP();
1710 }
1711 
1712 StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo(
1713     StructuredData::ObjectSP os_plugin_object_sp) {
1714   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1715 
1716   static char callee_name[] = "get_thread_info";
1717 
1718   if (!os_plugin_object_sp)
1719     return StructuredData::ArraySP();
1720 
1721   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1722   if (!generic)
1723     return nullptr;
1724 
1725   PythonObject implementor(PyRefType::Borrowed,
1726                            (PyObject *)generic->GetValue());
1727 
1728   if (!implementor.IsAllocated())
1729     return StructuredData::ArraySP();
1730 
1731   PythonObject pmeth(PyRefType::Owned,
1732                      PyObject_GetAttrString(implementor.get(), callee_name));
1733 
1734   if (PyErr_Occurred())
1735     PyErr_Clear();
1736 
1737   if (!pmeth.IsAllocated())
1738     return StructuredData::ArraySP();
1739 
1740   if (PyCallable_Check(pmeth.get()) == 0) {
1741     if (PyErr_Occurred())
1742       PyErr_Clear();
1743 
1744     return StructuredData::ArraySP();
1745   }
1746 
1747   if (PyErr_Occurred())
1748     PyErr_Clear();
1749 
1750   // right now we know this function exists and is callable..
1751   PythonObject py_return(
1752       PyRefType::Owned,
1753       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
1754 
1755   // if it fails, print the error but otherwise go on
1756   if (PyErr_Occurred()) {
1757     PyErr_Print();
1758     PyErr_Clear();
1759   }
1760 
1761   if (py_return.get()) {
1762     PythonList result_list(PyRefType::Borrowed, py_return.get());
1763     return result_list.CreateStructuredArray();
1764   }
1765   return StructuredData::ArraySP();
1766 }
1767 
1768 StructuredData::StringSP
1769 ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData(
1770     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
1771   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1772 
1773   static char callee_name[] = "get_register_data";
1774   static char *param_format =
1775       const_cast<char *>(GetPythonValueFormatString(tid));
1776 
1777   if (!os_plugin_object_sp)
1778     return StructuredData::StringSP();
1779 
1780   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1781   if (!generic)
1782     return nullptr;
1783   PythonObject implementor(PyRefType::Borrowed,
1784                            (PyObject *)generic->GetValue());
1785 
1786   if (!implementor.IsAllocated())
1787     return StructuredData::StringSP();
1788 
1789   PythonObject pmeth(PyRefType::Owned,
1790                      PyObject_GetAttrString(implementor.get(), callee_name));
1791 
1792   if (PyErr_Occurred())
1793     PyErr_Clear();
1794 
1795   if (!pmeth.IsAllocated())
1796     return StructuredData::StringSP();
1797 
1798   if (PyCallable_Check(pmeth.get()) == 0) {
1799     if (PyErr_Occurred())
1800       PyErr_Clear();
1801     return StructuredData::StringSP();
1802   }
1803 
1804   if (PyErr_Occurred())
1805     PyErr_Clear();
1806 
1807   // right now we know this function exists and is callable..
1808   PythonObject py_return(
1809       PyRefType::Owned,
1810       PyObject_CallMethod(implementor.get(), callee_name, param_format, tid));
1811 
1812   // if it fails, print the error but otherwise go on
1813   if (PyErr_Occurred()) {
1814     PyErr_Print();
1815     PyErr_Clear();
1816   }
1817 
1818   if (py_return.get()) {
1819     PythonBytes result(PyRefType::Borrowed, py_return.get());
1820     return result.CreateStructuredString();
1821   }
1822   return StructuredData::StringSP();
1823 }
1824 
1825 StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread(
1826     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
1827     lldb::addr_t context) {
1828   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1829 
1830   static char callee_name[] = "create_thread";
1831   std::string param_format;
1832   param_format += GetPythonValueFormatString(tid);
1833   param_format += GetPythonValueFormatString(context);
1834 
1835   if (!os_plugin_object_sp)
1836     return StructuredData::DictionarySP();
1837 
1838   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1839   if (!generic)
1840     return nullptr;
1841 
1842   PythonObject implementor(PyRefType::Borrowed,
1843                            (PyObject *)generic->GetValue());
1844 
1845   if (!implementor.IsAllocated())
1846     return StructuredData::DictionarySP();
1847 
1848   PythonObject pmeth(PyRefType::Owned,
1849                      PyObject_GetAttrString(implementor.get(), callee_name));
1850 
1851   if (PyErr_Occurred())
1852     PyErr_Clear();
1853 
1854   if (!pmeth.IsAllocated())
1855     return StructuredData::DictionarySP();
1856 
1857   if (PyCallable_Check(pmeth.get()) == 0) {
1858     if (PyErr_Occurred())
1859       PyErr_Clear();
1860     return StructuredData::DictionarySP();
1861   }
1862 
1863   if (PyErr_Occurred())
1864     PyErr_Clear();
1865 
1866   // right now we know this function exists and is callable..
1867   PythonObject py_return(PyRefType::Owned,
1868                          PyObject_CallMethod(implementor.get(), callee_name,
1869                                              &param_format[0], tid, context));
1870 
1871   // if it fails, print the error but otherwise go on
1872   if (PyErr_Occurred()) {
1873     PyErr_Print();
1874     PyErr_Clear();
1875   }
1876 
1877   if (py_return.get()) {
1878     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1879     return result_dict.CreateStructuredDictionary();
1880   }
1881   return StructuredData::DictionarySP();
1882 }
1883 
1884 StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan(
1885     const char *class_name, StructuredDataImpl *args_data,
1886     std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) {
1887   if (class_name == nullptr || class_name[0] == '\0')
1888     return StructuredData::ObjectSP();
1889 
1890   if (!thread_plan_sp.get())
1891     return {};
1892 
1893   Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
1894   ScriptInterpreterPythonImpl *python_interpreter =
1895       GetPythonInterpreter(debugger);
1896 
1897   if (!python_interpreter)
1898     return {};
1899 
1900   void *ret_val;
1901 
1902   {
1903     Locker py_lock(this,
1904                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1905     ret_val = LLDBSwigPythonCreateScriptedThreadPlan(
1906         class_name, python_interpreter->m_dictionary_name.c_str(),
1907         args_data, error_str, thread_plan_sp);
1908     if (!ret_val)
1909       return {};
1910   }
1911 
1912   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
1913 }
1914 
1915 bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop(
1916     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1917   bool explains_stop = true;
1918   StructuredData::Generic *generic = nullptr;
1919   if (implementor_sp)
1920     generic = implementor_sp->GetAsGeneric();
1921   if (generic) {
1922     Locker py_lock(this,
1923                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1924     explains_stop = LLDBSWIGPythonCallThreadPlan(
1925         generic->GetValue(), "explains_stop", event, script_error);
1926     if (script_error)
1927       return true;
1928   }
1929   return explains_stop;
1930 }
1931 
1932 bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop(
1933     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1934   bool should_stop = true;
1935   StructuredData::Generic *generic = nullptr;
1936   if (implementor_sp)
1937     generic = implementor_sp->GetAsGeneric();
1938   if (generic) {
1939     Locker py_lock(this,
1940                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1941     should_stop = LLDBSWIGPythonCallThreadPlan(
1942         generic->GetValue(), "should_stop", event, script_error);
1943     if (script_error)
1944       return true;
1945   }
1946   return should_stop;
1947 }
1948 
1949 bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale(
1950     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1951   bool is_stale = true;
1952   StructuredData::Generic *generic = nullptr;
1953   if (implementor_sp)
1954     generic = implementor_sp->GetAsGeneric();
1955   if (generic) {
1956     Locker py_lock(this,
1957                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1958     is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale",
1959                                             nullptr, script_error);
1960     if (script_error)
1961       return true;
1962   }
1963   return is_stale;
1964 }
1965 
1966 lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState(
1967     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1968   bool should_step = false;
1969   StructuredData::Generic *generic = nullptr;
1970   if (implementor_sp)
1971     generic = implementor_sp->GetAsGeneric();
1972   if (generic) {
1973     Locker py_lock(this,
1974                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1975     should_step = LLDBSWIGPythonCallThreadPlan(
1976         generic->GetValue(), "should_step", nullptr, script_error);
1977     if (script_error)
1978       should_step = true;
1979   }
1980   if (should_step)
1981     return lldb::eStateStepping;
1982   return lldb::eStateRunning;
1983 }
1984 
1985 StructuredData::GenericSP
1986 ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
1987     const char *class_name, StructuredDataImpl *args_data,
1988     lldb::BreakpointSP &bkpt_sp) {
1989 
1990   if (class_name == nullptr || class_name[0] == '\0')
1991     return StructuredData::GenericSP();
1992 
1993   if (!bkpt_sp.get())
1994     return StructuredData::GenericSP();
1995 
1996   Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
1997   ScriptInterpreterPythonImpl *python_interpreter =
1998       GetPythonInterpreter(debugger);
1999 
2000   if (!python_interpreter)
2001     return StructuredData::GenericSP();
2002 
2003   void *ret_val;
2004 
2005   {
2006     Locker py_lock(this,
2007                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2008 
2009     ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver(
2010         class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
2011         bkpt_sp);
2012   }
2013 
2014   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
2015 }
2016 
2017 bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
2018     StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
2019   bool should_continue = false;
2020 
2021   if (implementor_sp) {
2022     Locker py_lock(this,
2023                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2024     should_continue = LLDBSwigPythonCallBreakpointResolver(
2025         implementor_sp->GetValue(), "__callback__", sym_ctx);
2026     if (PyErr_Occurred()) {
2027       PyErr_Print();
2028       PyErr_Clear();
2029     }
2030   }
2031   return should_continue;
2032 }
2033 
2034 lldb::SearchDepth
2035 ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
2036     StructuredData::GenericSP implementor_sp) {
2037   int depth_as_int = lldb::eSearchDepthModule;
2038   if (implementor_sp) {
2039     Locker py_lock(this,
2040                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2041     depth_as_int = LLDBSwigPythonCallBreakpointResolver(
2042         implementor_sp->GetValue(), "__get_depth__", nullptr);
2043     if (PyErr_Occurred()) {
2044       PyErr_Print();
2045       PyErr_Clear();
2046     }
2047   }
2048   if (depth_as_int == lldb::eSearchDepthInvalid)
2049     return lldb::eSearchDepthModule;
2050 
2051   if (depth_as_int <= lldb::kLastSearchDepthKind)
2052     return (lldb::SearchDepth)depth_as_int;
2053   return lldb::eSearchDepthModule;
2054 }
2055 
2056 StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
2057     TargetSP target_sp, const char *class_name, StructuredDataImpl *args_data,
2058     Status &error) {
2059 
2060   if (!target_sp) {
2061     error.SetErrorString("No target for scripted stop-hook.");
2062     return StructuredData::GenericSP();
2063   }
2064 
2065   if (class_name == nullptr || class_name[0] == '\0') {
2066     error.SetErrorString("No class name for scripted stop-hook.");
2067     return StructuredData::GenericSP();
2068   }
2069 
2070   ScriptInterpreterPythonImpl *python_interpreter =
2071       GetPythonInterpreter(m_debugger);
2072 
2073   if (!python_interpreter) {
2074     error.SetErrorString("No script interpreter for scripted stop-hook.");
2075     return StructuredData::GenericSP();
2076   }
2077 
2078   void *ret_val;
2079 
2080   {
2081     Locker py_lock(this,
2082                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2083 
2084     ret_val = LLDBSwigPythonCreateScriptedStopHook(
2085         target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
2086         args_data, error);
2087   }
2088 
2089   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
2090 }
2091 
2092 bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
2093     StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
2094     lldb::StreamSP stream_sp) {
2095   assert(implementor_sp &&
2096          "can't call a stop hook with an invalid implementor");
2097   assert(stream_sp && "can't call a stop hook with an invalid stream");
2098 
2099   Locker py_lock(this,
2100                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2101 
2102   lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
2103 
2104   bool ret_val = LLDBSwigPythonStopHookCallHandleStop(
2105       implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
2106   return ret_val;
2107 }
2108 
2109 StructuredData::ObjectSP
2110 ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
2111                                               lldb_private::Status &error) {
2112   if (!FileSystem::Instance().Exists(file_spec)) {
2113     error.SetErrorString("no such file");
2114     return StructuredData::ObjectSP();
2115   }
2116 
2117   StructuredData::ObjectSP module_sp;
2118 
2119   LoadScriptOptions load_script_options =
2120       LoadScriptOptions().SetInitSession(true).SetSilent(false);
2121   if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
2122                           error, &module_sp))
2123     return module_sp;
2124 
2125   return StructuredData::ObjectSP();
2126 }
2127 
2128 StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
2129     StructuredData::ObjectSP plugin_module_sp, Target *target,
2130     const char *setting_name, lldb_private::Status &error) {
2131   if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
2132     return StructuredData::DictionarySP();
2133   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
2134   if (!generic)
2135     return StructuredData::DictionarySP();
2136 
2137   Locker py_lock(this,
2138                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2139   TargetSP target_sp(target->shared_from_this());
2140 
2141   auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting(
2142       generic->GetValue(), setting_name, target_sp);
2143 
2144   if (!setting)
2145     return StructuredData::DictionarySP();
2146 
2147   PythonDictionary py_dict =
2148       unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
2149 
2150   if (!py_dict)
2151     return StructuredData::DictionarySP();
2152 
2153   return py_dict.CreateStructuredDictionary();
2154 }
2155 
2156 StructuredData::ObjectSP
2157 ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
2158     const char *class_name, lldb::ValueObjectSP valobj) {
2159   if (class_name == nullptr || class_name[0] == '\0')
2160     return StructuredData::ObjectSP();
2161 
2162   if (!valobj.get())
2163     return StructuredData::ObjectSP();
2164 
2165   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
2166   Target *target = exe_ctx.GetTargetPtr();
2167 
2168   if (!target)
2169     return StructuredData::ObjectSP();
2170 
2171   Debugger &debugger = target->GetDebugger();
2172   ScriptInterpreterPythonImpl *python_interpreter =
2173       GetPythonInterpreter(debugger);
2174 
2175   if (!python_interpreter)
2176     return StructuredData::ObjectSP();
2177 
2178   void *ret_val = nullptr;
2179 
2180   {
2181     Locker py_lock(this,
2182                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2183     ret_val = LLDBSwigPythonCreateSyntheticProvider(
2184         class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
2185   }
2186 
2187   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
2188 }
2189 
2190 StructuredData::GenericSP
2191 ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
2192   DebuggerSP debugger_sp(m_debugger.shared_from_this());
2193 
2194   if (class_name == nullptr || class_name[0] == '\0')
2195     return StructuredData::GenericSP();
2196 
2197   if (!debugger_sp.get())
2198     return StructuredData::GenericSP();
2199 
2200   void *ret_val;
2201 
2202   {
2203     Locker py_lock(this,
2204                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2205     ret_val = LLDBSwigPythonCreateCommandObject(
2206         class_name, m_dictionary_name.c_str(), debugger_sp);
2207   }
2208 
2209   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
2210 }
2211 
2212 bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
2213     const char *oneliner, std::string &output, const void *name_token) {
2214   StringList input;
2215   input.SplitIntoLines(oneliner, strlen(oneliner));
2216   return GenerateTypeScriptFunction(input, output, name_token);
2217 }
2218 
2219 bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
2220     const char *oneliner, std::string &output, const void *name_token) {
2221   StringList input;
2222   input.SplitIntoLines(oneliner, strlen(oneliner));
2223   return GenerateTypeSynthClass(input, output, name_token);
2224 }
2225 
2226 Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
2227     StringList &user_input, std::string &output,
2228     bool has_extra_args) {
2229   static uint32_t num_created_functions = 0;
2230   user_input.RemoveBlankLines();
2231   StreamString sstr;
2232   Status error;
2233   if (user_input.GetSize() == 0) {
2234     error.SetErrorString("No input data.");
2235     return error;
2236   }
2237 
2238   std::string auto_generated_function_name(GenerateUniqueName(
2239       "lldb_autogen_python_bp_callback_func_", num_created_functions));
2240   if (has_extra_args)
2241     sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
2242                 auto_generated_function_name.c_str());
2243   else
2244     sstr.Printf("def %s (frame, bp_loc, internal_dict):",
2245                 auto_generated_function_name.c_str());
2246 
2247   error = GenerateFunction(sstr.GetData(), user_input);
2248   if (!error.Success())
2249     return error;
2250 
2251   // Store the name of the auto-generated function to be called.
2252   output.assign(auto_generated_function_name);
2253   return error;
2254 }
2255 
2256 bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
2257     StringList &user_input, std::string &output) {
2258   static uint32_t num_created_functions = 0;
2259   user_input.RemoveBlankLines();
2260   StreamString sstr;
2261 
2262   if (user_input.GetSize() == 0)
2263     return false;
2264 
2265   std::string auto_generated_function_name(GenerateUniqueName(
2266       "lldb_autogen_python_wp_callback_func_", num_created_functions));
2267   sstr.Printf("def %s (frame, wp, internal_dict):",
2268               auto_generated_function_name.c_str());
2269 
2270   if (!GenerateFunction(sstr.GetData(), user_input).Success())
2271     return false;
2272 
2273   // Store the name of the auto-generated function to be called.
2274   output.assign(auto_generated_function_name);
2275   return true;
2276 }
2277 
2278 bool ScriptInterpreterPythonImpl::GetScriptedSummary(
2279     const char *python_function_name, lldb::ValueObjectSP valobj,
2280     StructuredData::ObjectSP &callee_wrapper_sp,
2281     const TypeSummaryOptions &options, std::string &retval) {
2282 
2283   LLDB_SCOPED_TIMER();
2284 
2285   if (!valobj.get()) {
2286     retval.assign("<no object>");
2287     return false;
2288   }
2289 
2290   void *old_callee = nullptr;
2291   StructuredData::Generic *generic = nullptr;
2292   if (callee_wrapper_sp) {
2293     generic = callee_wrapper_sp->GetAsGeneric();
2294     if (generic)
2295       old_callee = generic->GetValue();
2296   }
2297   void *new_callee = old_callee;
2298 
2299   bool ret_val;
2300   if (python_function_name && *python_function_name) {
2301     {
2302       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
2303                                Locker::NoSTDIN);
2304       {
2305         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
2306 
2307         static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
2308         Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
2309         ret_val = LLDBSwigPythonCallTypeScript(
2310             python_function_name, GetSessionDictionary().get(), valobj,
2311             &new_callee, options_sp, retval);
2312       }
2313     }
2314   } else {
2315     retval.assign("<no function name>");
2316     return false;
2317   }
2318 
2319   if (new_callee && old_callee != new_callee)
2320     callee_wrapper_sp = std::make_shared<StructuredPythonObject>(new_callee);
2321 
2322   return ret_val;
2323 }
2324 
2325 bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
2326     void *baton, StoppointCallbackContext *context, user_id_t break_id,
2327     user_id_t break_loc_id) {
2328   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
2329   const char *python_function_name = bp_option_data->script_source.c_str();
2330 
2331   if (!context)
2332     return true;
2333 
2334   ExecutionContext exe_ctx(context->exe_ctx_ref);
2335   Target *target = exe_ctx.GetTargetPtr();
2336 
2337   if (!target)
2338     return true;
2339 
2340   Debugger &debugger = target->GetDebugger();
2341   ScriptInterpreterPythonImpl *python_interpreter =
2342       GetPythonInterpreter(debugger);
2343 
2344   if (!python_interpreter)
2345     return true;
2346 
2347   if (python_function_name && python_function_name[0]) {
2348     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2349     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2350     if (breakpoint_sp) {
2351       const BreakpointLocationSP bp_loc_sp(
2352           breakpoint_sp->FindLocationByID(break_loc_id));
2353 
2354       if (stop_frame_sp && bp_loc_sp) {
2355         bool ret_val = true;
2356         {
2357           Locker py_lock(python_interpreter, Locker::AcquireLock |
2358                                                  Locker::InitSession |
2359                                                  Locker::NoSTDIN);
2360           Expected<bool> maybe_ret_val =
2361               LLDBSwigPythonBreakpointCallbackFunction(
2362                   python_function_name,
2363                   python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2364                   bp_loc_sp, bp_option_data->m_extra_args_up.get());
2365 
2366           if (!maybe_ret_val) {
2367 
2368             llvm::handleAllErrors(
2369                 maybe_ret_val.takeError(),
2370                 [&](PythonException &E) {
2371                   debugger.GetErrorStream() << E.ReadBacktrace();
2372                 },
2373                 [&](const llvm::ErrorInfoBase &E) {
2374                   debugger.GetErrorStream() << E.message();
2375                 });
2376 
2377           } else {
2378             ret_val = maybe_ret_val.get();
2379           }
2380         }
2381         return ret_val;
2382       }
2383     }
2384   }
2385   // We currently always true so we stop in case anything goes wrong when
2386   // trying to call the script function
2387   return true;
2388 }
2389 
2390 bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
2391     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2392   WatchpointOptions::CommandData *wp_option_data =
2393       (WatchpointOptions::CommandData *)baton;
2394   const char *python_function_name = wp_option_data->script_source.c_str();
2395 
2396   if (!context)
2397     return true;
2398 
2399   ExecutionContext exe_ctx(context->exe_ctx_ref);
2400   Target *target = exe_ctx.GetTargetPtr();
2401 
2402   if (!target)
2403     return true;
2404 
2405   Debugger &debugger = target->GetDebugger();
2406   ScriptInterpreterPythonImpl *python_interpreter =
2407       GetPythonInterpreter(debugger);
2408 
2409   if (!python_interpreter)
2410     return true;
2411 
2412   if (python_function_name && python_function_name[0]) {
2413     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2414     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2415     if (wp_sp) {
2416       if (stop_frame_sp && wp_sp) {
2417         bool ret_val = true;
2418         {
2419           Locker py_lock(python_interpreter, Locker::AcquireLock |
2420                                                  Locker::InitSession |
2421                                                  Locker::NoSTDIN);
2422           ret_val = LLDBSwigPythonWatchpointCallbackFunction(
2423               python_function_name,
2424               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2425               wp_sp);
2426         }
2427         return ret_val;
2428       }
2429     }
2430   }
2431   // We currently always true so we stop in case anything goes wrong when
2432   // trying to call the script function
2433   return true;
2434 }
2435 
2436 size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2437     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
2438   if (!implementor_sp)
2439     return 0;
2440   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2441   if (!generic)
2442     return 0;
2443   void *implementor = generic->GetValue();
2444   if (!implementor)
2445     return 0;
2446 
2447   size_t ret_val = 0;
2448 
2449   {
2450     Locker py_lock(this,
2451                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2452     ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max);
2453   }
2454 
2455   return ret_val;
2456 }
2457 
2458 lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
2459     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
2460   if (!implementor_sp)
2461     return lldb::ValueObjectSP();
2462 
2463   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2464   if (!generic)
2465     return lldb::ValueObjectSP();
2466   void *implementor = generic->GetValue();
2467   if (!implementor)
2468     return lldb::ValueObjectSP();
2469 
2470   lldb::ValueObjectSP ret_val;
2471   {
2472     Locker py_lock(this,
2473                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2474     void *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx);
2475     if (child_ptr != nullptr && child_ptr != Py_None) {
2476       lldb::SBValue *sb_value_ptr =
2477           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2478       if (sb_value_ptr == nullptr)
2479         Py_XDECREF(child_ptr);
2480       else
2481         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2482     } else {
2483       Py_XDECREF(child_ptr);
2484     }
2485   }
2486 
2487   return ret_val;
2488 }
2489 
2490 int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2491     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
2492   if (!implementor_sp)
2493     return UINT32_MAX;
2494 
2495   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2496   if (!generic)
2497     return UINT32_MAX;
2498   void *implementor = generic->GetValue();
2499   if (!implementor)
2500     return UINT32_MAX;
2501 
2502   int ret_val = UINT32_MAX;
2503 
2504   {
2505     Locker py_lock(this,
2506                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2507     ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
2508   }
2509 
2510   return ret_val;
2511 }
2512 
2513 bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2514     const StructuredData::ObjectSP &implementor_sp) {
2515   bool ret_val = false;
2516 
2517   if (!implementor_sp)
2518     return ret_val;
2519 
2520   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2521   if (!generic)
2522     return ret_val;
2523   void *implementor = generic->GetValue();
2524   if (!implementor)
2525     return ret_val;
2526 
2527   {
2528     Locker py_lock(this,
2529                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2530     ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor);
2531   }
2532 
2533   return ret_val;
2534 }
2535 
2536 bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2537     const StructuredData::ObjectSP &implementor_sp) {
2538   bool ret_val = false;
2539 
2540   if (!implementor_sp)
2541     return ret_val;
2542 
2543   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2544   if (!generic)
2545     return ret_val;
2546   void *implementor = generic->GetValue();
2547   if (!implementor)
2548     return ret_val;
2549 
2550   {
2551     Locker py_lock(this,
2552                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2553     ret_val =
2554         LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor);
2555   }
2556 
2557   return ret_val;
2558 }
2559 
2560 lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
2561     const StructuredData::ObjectSP &implementor_sp) {
2562   lldb::ValueObjectSP ret_val(nullptr);
2563 
2564   if (!implementor_sp)
2565     return ret_val;
2566 
2567   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2568   if (!generic)
2569     return ret_val;
2570   void *implementor = generic->GetValue();
2571   if (!implementor)
2572     return ret_val;
2573 
2574   {
2575     Locker py_lock(this,
2576                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2577     void *child_ptr = LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2578     if (child_ptr != nullptr && child_ptr != Py_None) {
2579       lldb::SBValue *sb_value_ptr =
2580           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2581       if (sb_value_ptr == nullptr)
2582         Py_XDECREF(child_ptr);
2583       else
2584         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2585     } else {
2586       Py_XDECREF(child_ptr);
2587     }
2588   }
2589 
2590   return ret_val;
2591 }
2592 
2593 ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2594     const StructuredData::ObjectSP &implementor_sp) {
2595   Locker py_lock(this,
2596                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2597 
2598   static char callee_name[] = "get_type_name";
2599 
2600   ConstString ret_val;
2601   bool got_string = false;
2602   std::string buffer;
2603 
2604   if (!implementor_sp)
2605     return ret_val;
2606 
2607   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2608   if (!generic)
2609     return ret_val;
2610   PythonObject implementor(PyRefType::Borrowed,
2611                            (PyObject *)generic->GetValue());
2612   if (!implementor.IsAllocated())
2613     return ret_val;
2614 
2615   PythonObject pmeth(PyRefType::Owned,
2616                      PyObject_GetAttrString(implementor.get(), callee_name));
2617 
2618   if (PyErr_Occurred())
2619     PyErr_Clear();
2620 
2621   if (!pmeth.IsAllocated())
2622     return ret_val;
2623 
2624   if (PyCallable_Check(pmeth.get()) == 0) {
2625     if (PyErr_Occurred())
2626       PyErr_Clear();
2627     return ret_val;
2628   }
2629 
2630   if (PyErr_Occurred())
2631     PyErr_Clear();
2632 
2633   // right now we know this function exists and is callable..
2634   PythonObject py_return(
2635       PyRefType::Owned,
2636       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
2637 
2638   // if it fails, print the error but otherwise go on
2639   if (PyErr_Occurred()) {
2640     PyErr_Print();
2641     PyErr_Clear();
2642   }
2643 
2644   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2645     PythonString py_string(PyRefType::Borrowed, py_return.get());
2646     llvm::StringRef return_data(py_string.GetString());
2647     if (!return_data.empty()) {
2648       buffer.assign(return_data.data(), return_data.size());
2649       got_string = true;
2650     }
2651   }
2652 
2653   if (got_string)
2654     ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
2655 
2656   return ret_val;
2657 }
2658 
2659 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2660     const char *impl_function, Process *process, std::string &output,
2661     Status &error) {
2662   bool ret_val;
2663   if (!process) {
2664     error.SetErrorString("no process");
2665     return false;
2666   }
2667   if (!impl_function || !impl_function[0]) {
2668     error.SetErrorString("no function to execute");
2669     return false;
2670   }
2671 
2672   {
2673     ProcessSP process_sp(process->shared_from_this());
2674     Locker py_lock(this,
2675                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2676     ret_val = LLDBSWIGPythonRunScriptKeywordProcess(
2677         impl_function, m_dictionary_name.c_str(), process_sp, output);
2678     if (!ret_val)
2679       error.SetErrorString("python script evaluation failed");
2680   }
2681   return ret_val;
2682 }
2683 
2684 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2685     const char *impl_function, Thread *thread, std::string &output,
2686     Status &error) {
2687   bool ret_val;
2688   if (!thread) {
2689     error.SetErrorString("no thread");
2690     return false;
2691   }
2692   if (!impl_function || !impl_function[0]) {
2693     error.SetErrorString("no function to execute");
2694     return false;
2695   }
2696 
2697   {
2698     ThreadSP thread_sp(thread->shared_from_this());
2699     Locker py_lock(this,
2700                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2701     ret_val = LLDBSWIGPythonRunScriptKeywordThread(
2702         impl_function, m_dictionary_name.c_str(), thread_sp, output);
2703     if (!ret_val)
2704       error.SetErrorString("python script evaluation failed");
2705   }
2706   return ret_val;
2707 }
2708 
2709 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2710     const char *impl_function, Target *target, std::string &output,
2711     Status &error) {
2712   bool ret_val;
2713   if (!target) {
2714     error.SetErrorString("no thread");
2715     return false;
2716   }
2717   if (!impl_function || !impl_function[0]) {
2718     error.SetErrorString("no function to execute");
2719     return false;
2720   }
2721 
2722   {
2723     TargetSP target_sp(target->shared_from_this());
2724     Locker py_lock(this,
2725                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2726     ret_val = LLDBSWIGPythonRunScriptKeywordTarget(
2727         impl_function, m_dictionary_name.c_str(), target_sp, output);
2728     if (!ret_val)
2729       error.SetErrorString("python script evaluation failed");
2730   }
2731   return ret_val;
2732 }
2733 
2734 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2735     const char *impl_function, StackFrame *frame, std::string &output,
2736     Status &error) {
2737   bool ret_val;
2738   if (!frame) {
2739     error.SetErrorString("no frame");
2740     return false;
2741   }
2742   if (!impl_function || !impl_function[0]) {
2743     error.SetErrorString("no function to execute");
2744     return false;
2745   }
2746 
2747   {
2748     StackFrameSP frame_sp(frame->shared_from_this());
2749     Locker py_lock(this,
2750                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2751     ret_val = LLDBSWIGPythonRunScriptKeywordFrame(
2752         impl_function, m_dictionary_name.c_str(), frame_sp, output);
2753     if (!ret_val)
2754       error.SetErrorString("python script evaluation failed");
2755   }
2756   return ret_val;
2757 }
2758 
2759 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2760     const char *impl_function, ValueObject *value, std::string &output,
2761     Status &error) {
2762   bool ret_val;
2763   if (!value) {
2764     error.SetErrorString("no value");
2765     return false;
2766   }
2767   if (!impl_function || !impl_function[0]) {
2768     error.SetErrorString("no function to execute");
2769     return false;
2770   }
2771 
2772   {
2773     ValueObjectSP value_sp(value->GetSP());
2774     Locker py_lock(this,
2775                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2776     ret_val = LLDBSWIGPythonRunScriptKeywordValue(
2777         impl_function, m_dictionary_name.c_str(), value_sp, output);
2778     if (!ret_val)
2779       error.SetErrorString("python script evaluation failed");
2780   }
2781   return ret_val;
2782 }
2783 
2784 uint64_t replace_all(std::string &str, const std::string &oldStr,
2785                      const std::string &newStr) {
2786   size_t pos = 0;
2787   uint64_t matches = 0;
2788   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2789     matches++;
2790     str.replace(pos, oldStr.length(), newStr);
2791     pos += newStr.length();
2792   }
2793   return matches;
2794 }
2795 
2796 bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2797     const char *pathname, const LoadScriptOptions &options,
2798     lldb_private::Status &error, StructuredData::ObjectSP *module_sp,
2799     FileSpec extra_search_dir) {
2800   namespace fs = llvm::sys::fs;
2801   namespace path = llvm::sys::path;
2802 
2803   ExecuteScriptOptions exc_options = ExecuteScriptOptions()
2804                                          .SetEnableIO(!options.GetSilent())
2805                                          .SetSetLLDBGlobals(false);
2806 
2807   if (!pathname || !pathname[0]) {
2808     error.SetErrorString("invalid pathname");
2809     return false;
2810   }
2811 
2812   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2813       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2814           exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2815 
2816   if (!io_redirect_or_error) {
2817     error = io_redirect_or_error.takeError();
2818     return false;
2819   }
2820 
2821   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
2822   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2823 
2824   // Before executing Python code, lock the GIL.
2825   Locker py_lock(this,
2826                  Locker::AcquireLock |
2827                      (options.GetInitSession() ? Locker::InitSession : 0) |
2828                      Locker::NoSTDIN,
2829                  Locker::FreeAcquiredLock |
2830                      (options.GetInitSession() ? Locker::TearDownSession : 0),
2831                  io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2832                  io_redirect.GetErrorFile());
2833 
2834   auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2835     if (directory.empty()) {
2836       return llvm::make_error<llvm::StringError>(
2837           "invalid directory name", llvm::inconvertibleErrorCode());
2838     }
2839 
2840     replace_all(directory, "\\", "\\\\");
2841     replace_all(directory, "'", "\\'");
2842 
2843     // Make sure that Python has "directory" in the search path.
2844     StreamString command_stream;
2845     command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
2846                           "sys.path.insert(1,'%s');\n\n",
2847                           directory.c_str(), directory.c_str());
2848     bool syspath_retval =
2849         ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
2850     if (!syspath_retval) {
2851       return llvm::make_error<llvm::StringError>(
2852           "Python sys.path handling failed", llvm::inconvertibleErrorCode());
2853     }
2854 
2855     return llvm::Error::success();
2856   };
2857 
2858   std::string module_name(pathname);
2859   bool possible_package = false;
2860 
2861   if (extra_search_dir) {
2862     if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2863       error = std::move(e);
2864       return false;
2865     }
2866   } else {
2867     FileSpec module_file(pathname);
2868     FileSystem::Instance().Resolve(module_file);
2869     FileSystem::Instance().Collect(module_file);
2870 
2871     fs::file_status st;
2872     std::error_code ec = status(module_file.GetPath(), st);
2873 
2874     if (ec || st.type() == fs::file_type::status_error ||
2875         st.type() == fs::file_type::type_unknown ||
2876         st.type() == fs::file_type::file_not_found) {
2877       // if not a valid file of any sort, check if it might be a filename still
2878       // dot can't be used but / and \ can, and if either is found, reject
2879       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2880         error.SetErrorString("invalid pathname");
2881         return false;
2882       }
2883       // Not a filename, probably a package of some sort, let it go through.
2884       possible_package = true;
2885     } else if (is_directory(st) || is_regular_file(st)) {
2886       if (module_file.GetDirectory().IsEmpty()) {
2887         error.SetErrorString("invalid directory name");
2888         return false;
2889       }
2890       if (llvm::Error e =
2891               ExtendSysPath(module_file.GetDirectory().GetCString())) {
2892         error = std::move(e);
2893         return false;
2894       }
2895       module_name = module_file.GetFilename().GetCString();
2896     } else {
2897       error.SetErrorString("no known way to import this module specification");
2898       return false;
2899     }
2900   }
2901 
2902   // Strip .py or .pyc extension
2903   llvm::StringRef extension = llvm::sys::path::extension(module_name);
2904   if (!extension.empty()) {
2905     if (extension == ".py")
2906       module_name.resize(module_name.length() - 3);
2907     else if (extension == ".pyc")
2908       module_name.resize(module_name.length() - 4);
2909   }
2910 
2911   if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2912     error.SetErrorStringWithFormat(
2913         "Python does not allow dots in module names: %s", module_name.c_str());
2914     return false;
2915   }
2916 
2917   if (module_name.find('-') != llvm::StringRef::npos) {
2918     error.SetErrorStringWithFormat(
2919         "Python discourages dashes in module names: %s", module_name.c_str());
2920     return false;
2921   }
2922 
2923   // Check if the module is already imported.
2924   StreamString command_stream;
2925   command_stream.Clear();
2926   command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
2927   bool does_contain = false;
2928   // This call will succeed if the module was ever imported in any Debugger in
2929   // the lifetime of the process in which this LLDB framework is living.
2930   const bool does_contain_executed = ExecuteOneLineWithReturn(
2931       command_stream.GetData(),
2932       ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options);
2933 
2934   const bool was_imported_globally = does_contain_executed && does_contain;
2935   const bool was_imported_locally =
2936       GetSessionDictionary()
2937           .GetItemForKey(PythonString(module_name))
2938           .IsAllocated();
2939 
2940   // now actually do the import
2941   command_stream.Clear();
2942 
2943   if (was_imported_globally || was_imported_locally) {
2944     if (!was_imported_locally)
2945       command_stream.Printf("import %s ; reload_module(%s)",
2946                             module_name.c_str(), module_name.c_str());
2947     else
2948       command_stream.Printf("reload_module(%s)", module_name.c_str());
2949   } else
2950     command_stream.Printf("import %s", module_name.c_str());
2951 
2952   error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
2953   if (error.Fail())
2954     return false;
2955 
2956   // if we are here, everything worked
2957   // call __lldb_init_module(debugger,dict)
2958   if (!LLDBSwigPythonCallModuleInit(module_name.c_str(),
2959                                     m_dictionary_name.c_str(), debugger_sp)) {
2960     error.SetErrorString("calling __lldb_init_module failed");
2961     return false;
2962   }
2963 
2964   if (module_sp) {
2965     // everything went just great, now set the module object
2966     command_stream.Clear();
2967     command_stream.Printf("%s", module_name.c_str());
2968     void *module_pyobj = nullptr;
2969     if (ExecuteOneLineWithReturn(
2970             command_stream.GetData(),
2971             ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2972             exc_options) &&
2973         module_pyobj)
2974       *module_sp = std::make_shared<StructuredPythonObject>(module_pyobj);
2975   }
2976 
2977   return true;
2978 }
2979 
2980 bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
2981   if (!word || !word[0])
2982     return false;
2983 
2984   llvm::StringRef word_sr(word);
2985 
2986   // filter out a few characters that would just confuse us and that are
2987   // clearly not keyword material anyway
2988   if (word_sr.find('"') != llvm::StringRef::npos ||
2989       word_sr.find('\'') != llvm::StringRef::npos)
2990     return false;
2991 
2992   StreamString command_stream;
2993   command_stream.Printf("keyword.iskeyword('%s')", word);
2994   bool result;
2995   ExecuteScriptOptions options;
2996   options.SetEnableIO(false);
2997   options.SetMaskoutErrors(true);
2998   options.SetSetLLDBGlobals(false);
2999   if (ExecuteOneLineWithReturn(command_stream.GetData(),
3000                                ScriptInterpreter::eScriptReturnTypeBool,
3001                                &result, options))
3002     return result;
3003   return false;
3004 }
3005 
3006 ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
3007     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
3008     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
3009       m_old_asynch(debugger_sp->GetAsyncExecution()) {
3010   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
3011     m_debugger_sp->SetAsyncExecution(false);
3012   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
3013     m_debugger_sp->SetAsyncExecution(true);
3014 }
3015 
3016 ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
3017   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
3018     m_debugger_sp->SetAsyncExecution(m_old_asynch);
3019 }
3020 
3021 bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
3022     const char *impl_function, llvm::StringRef args,
3023     ScriptedCommandSynchronicity synchronicity,
3024     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
3025     const lldb_private::ExecutionContext &exe_ctx) {
3026   if (!impl_function) {
3027     error.SetErrorString("no function to execute");
3028     return false;
3029   }
3030 
3031   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
3032   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
3033 
3034   if (!debugger_sp.get()) {
3035     error.SetErrorString("invalid Debugger pointer");
3036     return false;
3037   }
3038 
3039   bool ret_val = false;
3040 
3041   std::string err_msg;
3042 
3043   {
3044     Locker py_lock(this,
3045                    Locker::AcquireLock | Locker::InitSession |
3046                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
3047                    Locker::FreeLock | Locker::TearDownSession);
3048 
3049     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
3050 
3051     std::string args_str = args.str();
3052     ret_val = LLDBSwigPythonCallCommand(
3053         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
3054         cmd_retobj, exe_ctx_ref_sp);
3055   }
3056 
3057   if (!ret_val)
3058     error.SetErrorString("unable to execute script function");
3059   else
3060     error.Clear();
3061 
3062   return ret_val;
3063 }
3064 
3065 bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
3066     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
3067     ScriptedCommandSynchronicity synchronicity,
3068     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
3069     const lldb_private::ExecutionContext &exe_ctx) {
3070   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
3071     error.SetErrorString("no function to execute");
3072     return false;
3073   }
3074 
3075   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
3076   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
3077 
3078   if (!debugger_sp.get()) {
3079     error.SetErrorString("invalid Debugger pointer");
3080     return false;
3081   }
3082 
3083   bool ret_val = false;
3084 
3085   std::string err_msg;
3086 
3087   {
3088     Locker py_lock(this,
3089                    Locker::AcquireLock | Locker::InitSession |
3090                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
3091                    Locker::FreeLock | Locker::TearDownSession);
3092 
3093     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
3094 
3095     std::string args_str = args.str();
3096     ret_val = LLDBSwigPythonCallCommandObject(impl_obj_sp->GetValue(),
3097                                               debugger_sp, args_str.c_str(),
3098                                               cmd_retobj, exe_ctx_ref_sp);
3099   }
3100 
3101   if (!ret_val)
3102     error.SetErrorString("unable to execute script function");
3103   else
3104     error.Clear();
3105 
3106   return ret_val;
3107 }
3108 
3109 /// In Python, a special attribute __doc__ contains the docstring for an object
3110 /// (function, method, class, ...) if any is defined Otherwise, the attribute's
3111 /// value is None.
3112 bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
3113                                                           std::string &dest) {
3114   dest.clear();
3115 
3116   if (!item || !*item)
3117     return false;
3118 
3119   std::string command(item);
3120   command += ".__doc__";
3121 
3122   // Python is going to point this to valid data if ExecuteOneLineWithReturn
3123   // returns successfully.
3124   char *result_ptr = nullptr;
3125 
3126   if (ExecuteOneLineWithReturn(
3127           command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
3128           &result_ptr,
3129           ExecuteScriptOptions().SetEnableIO(false))) {
3130     if (result_ptr)
3131       dest.assign(result_ptr);
3132     return true;
3133   }
3134 
3135   StreamString str_stream;
3136   str_stream << "Function " << item
3137              << " was not found. Containing module might be missing.";
3138   dest = std::string(str_stream.GetString());
3139 
3140   return false;
3141 }
3142 
3143 bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
3144     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
3145   dest.clear();
3146 
3147   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3148 
3149   static char callee_name[] = "get_short_help";
3150 
3151   if (!cmd_obj_sp)
3152     return false;
3153 
3154   PythonObject implementor(PyRefType::Borrowed,
3155                            (PyObject *)cmd_obj_sp->GetValue());
3156 
3157   if (!implementor.IsAllocated())
3158     return false;
3159 
3160   PythonObject pmeth(PyRefType::Owned,
3161                      PyObject_GetAttrString(implementor.get(), callee_name));
3162 
3163   if (PyErr_Occurred())
3164     PyErr_Clear();
3165 
3166   if (!pmeth.IsAllocated())
3167     return false;
3168 
3169   if (PyCallable_Check(pmeth.get()) == 0) {
3170     if (PyErr_Occurred())
3171       PyErr_Clear();
3172     return false;
3173   }
3174 
3175   if (PyErr_Occurred())
3176     PyErr_Clear();
3177 
3178   // Right now we know this function exists and is callable.
3179   PythonObject py_return(
3180       PyRefType::Owned,
3181       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3182 
3183   // If it fails, print the error but otherwise go on.
3184   if (PyErr_Occurred()) {
3185     PyErr_Print();
3186     PyErr_Clear();
3187   }
3188 
3189   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3190     PythonString py_string(PyRefType::Borrowed, py_return.get());
3191     llvm::StringRef return_data(py_string.GetString());
3192     dest.assign(return_data.data(), return_data.size());
3193     return true;
3194   }
3195 
3196   return false;
3197 }
3198 
3199 uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
3200     StructuredData::GenericSP cmd_obj_sp) {
3201   uint32_t result = 0;
3202 
3203   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3204 
3205   static char callee_name[] = "get_flags";
3206 
3207   if (!cmd_obj_sp)
3208     return result;
3209 
3210   PythonObject implementor(PyRefType::Borrowed,
3211                            (PyObject *)cmd_obj_sp->GetValue());
3212 
3213   if (!implementor.IsAllocated())
3214     return result;
3215 
3216   PythonObject pmeth(PyRefType::Owned,
3217                      PyObject_GetAttrString(implementor.get(), callee_name));
3218 
3219   if (PyErr_Occurred())
3220     PyErr_Clear();
3221 
3222   if (!pmeth.IsAllocated())
3223     return result;
3224 
3225   if (PyCallable_Check(pmeth.get()) == 0) {
3226     if (PyErr_Occurred())
3227       PyErr_Clear();
3228     return result;
3229   }
3230 
3231   if (PyErr_Occurred())
3232     PyErr_Clear();
3233 
3234   long long py_return = unwrapOrSetPythonException(
3235       As<long long>(implementor.CallMethod(callee_name)));
3236 
3237   // if it fails, print the error but otherwise go on
3238   if (PyErr_Occurred()) {
3239     PyErr_Print();
3240     PyErr_Clear();
3241   } else {
3242     result = py_return;
3243   }
3244 
3245   return result;
3246 }
3247 
3248 bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3249     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
3250   bool got_string = false;
3251   dest.clear();
3252 
3253   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3254 
3255   static char callee_name[] = "get_long_help";
3256 
3257   if (!cmd_obj_sp)
3258     return false;
3259 
3260   PythonObject implementor(PyRefType::Borrowed,
3261                            (PyObject *)cmd_obj_sp->GetValue());
3262 
3263   if (!implementor.IsAllocated())
3264     return false;
3265 
3266   PythonObject pmeth(PyRefType::Owned,
3267                      PyObject_GetAttrString(implementor.get(), callee_name));
3268 
3269   if (PyErr_Occurred())
3270     PyErr_Clear();
3271 
3272   if (!pmeth.IsAllocated())
3273     return false;
3274 
3275   if (PyCallable_Check(pmeth.get()) == 0) {
3276     if (PyErr_Occurred())
3277       PyErr_Clear();
3278 
3279     return false;
3280   }
3281 
3282   if (PyErr_Occurred())
3283     PyErr_Clear();
3284 
3285   // right now we know this function exists and is callable..
3286   PythonObject py_return(
3287       PyRefType::Owned,
3288       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3289 
3290   // if it fails, print the error but otherwise go on
3291   if (PyErr_Occurred()) {
3292     PyErr_Print();
3293     PyErr_Clear();
3294   }
3295 
3296   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3297     PythonString str(PyRefType::Borrowed, py_return.get());
3298     llvm::StringRef str_data(str.GetString());
3299     dest.assign(str_data.data(), str_data.size());
3300     got_string = true;
3301   }
3302 
3303   return got_string;
3304 }
3305 
3306 std::unique_ptr<ScriptInterpreterLocker>
3307 ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3308   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3309       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3310       Locker::FreeLock | Locker::TearDownSession));
3311   return py_lock;
3312 }
3313 
3314 namespace {
3315 /// Saves the current signal handler for the specified signal and restores
3316 /// it at the end of the current scope.
3317 struct RestoreSignalHandlerScope {
3318   /// The signal handler.
3319   struct sigaction m_prev_handler;
3320   int m_signal_code;
3321   RestoreSignalHandlerScope(int signal_code) : m_signal_code(signal_code) {
3322     // Initialize sigaction to their default state.
3323     std::memset(&m_prev_handler, 0, sizeof(m_prev_handler));
3324     // Don't install a new handler, just read back the old one.
3325     struct sigaction *new_handler = nullptr;
3326     int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler);
3327     lldbassert(signal_err == 0 && "sigaction failed to read handler");
3328   }
3329   ~RestoreSignalHandlerScope() {
3330     int signal_err = ::sigaction(m_signal_code, &m_prev_handler, nullptr);
3331     lldbassert(signal_err == 0 && "sigaction failed to restore old handler");
3332   }
3333 };
3334 } // namespace
3335 
3336 void ScriptInterpreterPythonImpl::InitializePrivate() {
3337   if (g_initialized)
3338     return;
3339 
3340   g_initialized = true;
3341 
3342   LLDB_SCOPED_TIMER();
3343 
3344   // RAII-based initialization which correctly handles multiple-initialization,
3345   // version- specific differences among Python 2 and Python 3, and saving and
3346   // restoring various other pieces of state that can get mucked with during
3347   // initialization.
3348   InitializePythonRAII initialize_guard;
3349 
3350   LLDBSwigPyInit();
3351 
3352   // Update the path python uses to search for modules to include the current
3353   // directory.
3354 
3355   PyRun_SimpleString("import sys");
3356   AddToSysPath(AddLocation::End, ".");
3357 
3358   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
3359   // that use a backslash as the path separator, this will result in executing
3360   // python code containing paths with unescaped backslashes.  But Python also
3361   // accepts forward slashes, so to make life easier we just use that.
3362   if (FileSpec file_spec = GetPythonDir())
3363     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3364   if (FileSpec file_spec = HostInfo::GetShlibDir())
3365     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3366 
3367   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3368                      "lldb.embedded_interpreter; from "
3369                      "lldb.embedded_interpreter import run_python_interpreter; "
3370                      "from lldb.embedded_interpreter import run_one_line");
3371 
3372 #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
3373   // Python will not just overwrite its internal SIGINT handler but also the
3374   // one from the process. Backup the current SIGINT handler to prevent that
3375   // Python deletes it.
3376   RestoreSignalHandlerScope save_sigint(SIGINT);
3377 
3378   // Setup a default SIGINT signal handler that works the same way as the
3379   // normal Python REPL signal handler which raises a KeyboardInterrupt.
3380   // Also make sure to not pollute the user's REPL with the signal module nor
3381   // our utility function.
3382   PyRun_SimpleString("def lldb_setup_sigint_handler():\n"
3383                      "  import signal;\n"
3384                      "  def signal_handler(sig, frame):\n"
3385                      "    raise KeyboardInterrupt()\n"
3386                      "  signal.signal(signal.SIGINT, signal_handler);\n"
3387                      "lldb_setup_sigint_handler();\n"
3388                      "del lldb_setup_sigint_handler\n");
3389 #endif
3390 }
3391 
3392 void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3393                                                std::string path) {
3394   std::string path_copy;
3395 
3396   std::string statement;
3397   if (location == AddLocation::Beginning) {
3398     statement.assign("sys.path.insert(0,\"");
3399     statement.append(path);
3400     statement.append("\")");
3401   } else {
3402     statement.assign("sys.path.append(\"");
3403     statement.append(path);
3404     statement.append("\")");
3405   }
3406   PyRun_SimpleString(statement.c_str());
3407 }
3408 
3409 // We are intentionally NOT calling Py_Finalize here (this would be the logical
3410 // place to call it).  Calling Py_Finalize here causes test suite runs to seg
3411 // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
3412 // be called 'at_exit'.  When the test suite Python harness finishes up, it
3413 // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3414 // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3415 // which calls ScriptInterpreter::Terminate, which calls
3416 // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
3417 // end up with Py_Finalize being called from within Py_Finalize, which results
3418 // in a seg fault. Since this function only gets called when lldb is shutting
3419 // down and going away anyway, the fact that we don't actually call Py_Finalize
3420 // should not cause any problems (everything should shut down/go away anyway
3421 // when the process exits).
3422 //
3423 // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3424 
3425 #endif
3426