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