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