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