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