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