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