xref: /llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp (revision 9357b5d08497326a1895cab6c1d712bf12a34519)
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 }
1194 
1195 Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1196     const char *in_string, const ExecuteScriptOptions &options) {
1197 
1198   if (in_string == nullptr)
1199     return Status();
1200 
1201   Locker locker(this,
1202                 Locker::AcquireLock | Locker::InitSession |
1203                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1204                     Locker::NoSTDIN,
1205                 Locker::FreeAcquiredLock | Locker::TearDownSession);
1206 
1207   PythonModule &main_module = GetMainModule();
1208   PythonDictionary globals = main_module.GetDictionary();
1209 
1210   PythonDictionary locals = GetSessionDictionary();
1211   if (!locals.IsValid())
1212     locals = unwrapIgnoringErrors(
1213         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1214   if (!locals.IsValid())
1215     locals = globals;
1216 
1217   Expected<PythonObject> return_value =
1218       runStringMultiLine(in_string, globals, locals);
1219 
1220   if (!return_value) {
1221     llvm::Error error =
1222         llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
1223           llvm::Error error = llvm::createStringError(
1224               llvm::inconvertibleErrorCode(), E.ReadBacktrace());
1225           if (!options.GetMaskoutErrors())
1226             E.Restore();
1227           return error;
1228         });
1229     return Status(std::move(error));
1230   }
1231 
1232   return Status();
1233 }
1234 
1235 void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1236     std::vector<BreakpointOptions *> &bp_options_vec,
1237     CommandReturnObject &result) {
1238   m_active_io_handler = eIOHandlerBreakpoint;
1239   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1240       "    ", *this, true, &bp_options_vec);
1241 }
1242 
1243 void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1244     WatchpointOptions *wp_options, CommandReturnObject &result) {
1245   m_active_io_handler = eIOHandlerWatchpoint;
1246   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1247       "    ", *this, true, wp_options);
1248 }
1249 
1250 Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1251     BreakpointOptions *bp_options, const char *function_name,
1252     StructuredData::ObjectSP extra_args_sp) {
1253   Status error;
1254   // For now just cons up a oneliner that calls the provided function.
1255   std::string oneliner("return ");
1256   oneliner += function_name;
1257 
1258   llvm::Expected<unsigned> maybe_args =
1259       GetMaxPositionalArgumentsForCallable(function_name);
1260   if (!maybe_args) {
1261     error.SetErrorStringWithFormat(
1262         "could not get num args: %s",
1263         llvm::toString(maybe_args.takeError()).c_str());
1264     return error;
1265   }
1266   size_t max_args = *maybe_args;
1267 
1268   bool uses_extra_args = false;
1269   if (max_args >= 4) {
1270     uses_extra_args = true;
1271     oneliner += "(frame, bp_loc, extra_args, internal_dict)";
1272   } else if (max_args >= 3) {
1273     if (extra_args_sp) {
1274       error.SetErrorString("cannot pass extra_args to a three argument callback"
1275                           );
1276       return error;
1277     }
1278     uses_extra_args = false;
1279     oneliner += "(frame, bp_loc, internal_dict)";
1280   } else {
1281     error.SetErrorStringWithFormat("expected 3 or 4 argument "
1282                                    "function, %s can only take %zu",
1283                                    function_name, max_args);
1284     return error;
1285   }
1286 
1287   SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp,
1288                                uses_extra_args);
1289   return error;
1290 }
1291 
1292 Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1293     BreakpointOptions *bp_options,
1294     std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
1295   Status error;
1296   error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1297                                                 cmd_data_up->script_source,
1298                                                 false);
1299   if (error.Fail()) {
1300     return error;
1301   }
1302   auto baton_sp =
1303       std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1304   bp_options->SetCallback(
1305       ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1306   return error;
1307 }
1308 
1309 Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1310     BreakpointOptions *bp_options, const char *command_body_text) {
1311   return SetBreakpointCommandCallback(bp_options, command_body_text, {},false);
1312 }
1313 
1314 // Set a Python one-liner as the callback for the breakpoint.
1315 Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1316     BreakpointOptions *bp_options, const char *command_body_text,
1317     StructuredData::ObjectSP extra_args_sp,
1318     bool uses_extra_args) {
1319   auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1320   // Split the command_body_text into lines, and pass that to
1321   // GenerateBreakpointCommandCallbackData.  That will wrap the body in an
1322   // auto-generated function, and return the function name in script_source.
1323   // That is what the callback will actually invoke.
1324 
1325   data_up->user_source.SplitIntoLines(command_body_text);
1326   Status error = GenerateBreakpointCommandCallbackData(data_up->user_source,
1327                                                        data_up->script_source,
1328                                                        uses_extra_args);
1329   if (error.Success()) {
1330     auto baton_sp =
1331         std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1332     bp_options->SetCallback(
1333         ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1334     return error;
1335   } else
1336     return error;
1337 }
1338 
1339 // Set a Python one-liner as the callback for the watchpoint.
1340 void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1341     WatchpointOptions *wp_options, const char *oneliner) {
1342   auto data_up = std::make_unique<WatchpointOptions::CommandData>();
1343 
1344   // It's necessary to set both user_source and script_source to the oneliner.
1345   // The former is used to generate callback description (as in watchpoint
1346   // command list) while the latter is used for Python to interpret during the
1347   // actual callback.
1348 
1349   data_up->user_source.AppendString(oneliner);
1350   data_up->script_source.assign(oneliner);
1351 
1352   if (GenerateWatchpointCommandCallbackData(data_up->user_source,
1353                                             data_up->script_source)) {
1354     auto baton_sp =
1355         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
1356     wp_options->SetCallback(
1357         ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
1358   }
1359 
1360   return;
1361 }
1362 
1363 Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1364     StringList &function_def) {
1365   // Convert StringList to one long, newline delimited, const char *.
1366   std::string function_def_string(function_def.CopyList());
1367 
1368   Status error = ExecuteMultipleLines(
1369       function_def_string.c_str(),
1370       ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false));
1371   return error;
1372 }
1373 
1374 Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature,
1375                                                      const StringList &input) {
1376   Status error;
1377   int num_lines = input.GetSize();
1378   if (num_lines == 0) {
1379     error.SetErrorString("No input data.");
1380     return error;
1381   }
1382 
1383   if (!signature || *signature == 0) {
1384     error.SetErrorString("No output function name.");
1385     return error;
1386   }
1387 
1388   StreamString sstr;
1389   StringList auto_generated_function;
1390   auto_generated_function.AppendString(signature);
1391   auto_generated_function.AppendString(
1392       "     global_dict = globals()"); // Grab the global dictionary
1393   auto_generated_function.AppendString(
1394       "     new_keys = internal_dict.keys()"); // Make a list of keys in the
1395                                                // session dict
1396   auto_generated_function.AppendString(
1397       "     old_keys = global_dict.keys()"); // Save list of keys in global dict
1398   auto_generated_function.AppendString(
1399       "     global_dict.update (internal_dict)"); // Add the session dictionary
1400                                                   // to the
1401   // global dictionary.
1402 
1403   // Wrap everything up inside the function, increasing the indentation.
1404 
1405   auto_generated_function.AppendString("     if True:");
1406   for (int i = 0; i < num_lines; ++i) {
1407     sstr.Clear();
1408     sstr.Printf("       %s", input.GetStringAtIndex(i));
1409     auto_generated_function.AppendString(sstr.GetData());
1410   }
1411   auto_generated_function.AppendString(
1412       "     for key in new_keys:"); // Iterate over all the keys from session
1413                                     // dict
1414   auto_generated_function.AppendString(
1415       "         internal_dict[key] = global_dict[key]"); // Update session dict
1416                                                          // values
1417   auto_generated_function.AppendString(
1418       "         if key not in old_keys:"); // If key was not originally in
1419                                            // global dict
1420   auto_generated_function.AppendString(
1421       "             del global_dict[key]"); //  ...then remove key/value from
1422                                             //  global dict
1423 
1424   // Verify that the results are valid Python.
1425 
1426   error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
1427 
1428   return error;
1429 }
1430 
1431 bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1432     StringList &user_input, std::string &output, const void *name_token) {
1433   static uint32_t num_created_functions = 0;
1434   user_input.RemoveBlankLines();
1435   StreamString sstr;
1436 
1437   // Check to see if we have any data; if not, just return.
1438   if (user_input.GetSize() == 0)
1439     return false;
1440 
1441   // Take what the user wrote, wrap it all up inside one big auto-generated
1442   // Python function, passing in the ValueObject as parameter to the function.
1443 
1444   std::string auto_generated_function_name(
1445       GenerateUniqueName("lldb_autogen_python_type_print_func",
1446                          num_created_functions, name_token));
1447   sstr.Printf("def %s (valobj, internal_dict):",
1448               auto_generated_function_name.c_str());
1449 
1450   if (!GenerateFunction(sstr.GetData(), user_input).Success())
1451     return false;
1452 
1453   // Store the name of the auto-generated function to be called.
1454   output.assign(auto_generated_function_name);
1455   return true;
1456 }
1457 
1458 bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1459     StringList &user_input, std::string &output) {
1460   static uint32_t num_created_functions = 0;
1461   user_input.RemoveBlankLines();
1462   StreamString sstr;
1463 
1464   // Check to see if we have any data; if not, just return.
1465   if (user_input.GetSize() == 0)
1466     return false;
1467 
1468   std::string auto_generated_function_name(GenerateUniqueName(
1469       "lldb_autogen_python_cmd_alias_func", num_created_functions));
1470 
1471   sstr.Printf("def %s (debugger, args, result, internal_dict):",
1472               auto_generated_function_name.c_str());
1473 
1474   if (!GenerateFunction(sstr.GetData(), user_input).Success())
1475     return false;
1476 
1477   // Store the name of the auto-generated function to be called.
1478   output.assign(auto_generated_function_name);
1479   return true;
1480 }
1481 
1482 bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1483     StringList &user_input, std::string &output, const void *name_token) {
1484   static uint32_t num_created_classes = 0;
1485   user_input.RemoveBlankLines();
1486   int num_lines = user_input.GetSize();
1487   StreamString sstr;
1488 
1489   // Check to see if we have any data; if not, just return.
1490   if (user_input.GetSize() == 0)
1491     return false;
1492 
1493   // Wrap all user input into a Python class
1494 
1495   std::string auto_generated_class_name(GenerateUniqueName(
1496       "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1497 
1498   StringList auto_generated_class;
1499 
1500   // Create the function name & definition string.
1501 
1502   sstr.Printf("class %s:", auto_generated_class_name.c_str());
1503   auto_generated_class.AppendString(sstr.GetString());
1504 
1505   // Wrap everything up inside the class, increasing the indentation. we don't
1506   // need to play any fancy indentation tricks here because there is no
1507   // surrounding code whose indentation we need to honor
1508   for (int i = 0; i < num_lines; ++i) {
1509     sstr.Clear();
1510     sstr.Printf("     %s", user_input.GetStringAtIndex(i));
1511     auto_generated_class.AppendString(sstr.GetString());
1512   }
1513 
1514   // Verify that the results are valid Python. (even though the method is
1515   // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1516   // (TODO: rename that method to ExportDefinitionToInterpreter)
1517   if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
1518     return false;
1519 
1520   // Store the name of the auto-generated class
1521 
1522   output.assign(auto_generated_class_name);
1523   return true;
1524 }
1525 
1526 StructuredData::GenericSP
1527 ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
1528   if (class_name == nullptr || class_name[0] == '\0')
1529     return StructuredData::GenericSP();
1530 
1531   void *ret_val;
1532 
1533   {
1534     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
1535                    Locker::FreeLock);
1536     ret_val = LLDBSWIGPython_CreateFrameRecognizer(class_name,
1537                                                    m_dictionary_name.c_str());
1538   }
1539 
1540   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
1541 }
1542 
1543 lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
1544     const StructuredData::ObjectSP &os_plugin_object_sp,
1545     lldb::StackFrameSP frame_sp) {
1546   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1547 
1548   if (!os_plugin_object_sp)
1549     return ValueObjectListSP();
1550 
1551   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1552   if (!generic)
1553     return nullptr;
1554 
1555   PythonObject implementor(PyRefType::Borrowed,
1556                            (PyObject *)generic->GetValue());
1557 
1558   if (!implementor.IsAllocated())
1559     return ValueObjectListSP();
1560 
1561   PythonObject py_return(PyRefType::Owned,
1562                          (PyObject *)LLDBSwigPython_GetRecognizedArguments(
1563                              implementor.get(), frame_sp));
1564 
1565   // if it fails, print the error but otherwise go on
1566   if (PyErr_Occurred()) {
1567     PyErr_Print();
1568     PyErr_Clear();
1569   }
1570   if (py_return.get()) {
1571     PythonList result_list(PyRefType::Borrowed, py_return.get());
1572     ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
1573     for (size_t i = 0; i < result_list.GetSize(); i++) {
1574       PyObject *item = result_list.GetItemAtIndex(i).get();
1575       lldb::SBValue *sb_value_ptr =
1576           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
1577       auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
1578       if (valobj_sp)
1579         result->Append(valobj_sp);
1580     }
1581     return result;
1582   }
1583   return ValueObjectListSP();
1584 }
1585 
1586 StructuredData::GenericSP
1587 ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject(
1588     const char *class_name, lldb::ProcessSP process_sp) {
1589   if (class_name == nullptr || class_name[0] == '\0')
1590     return StructuredData::GenericSP();
1591 
1592   if (!process_sp)
1593     return StructuredData::GenericSP();
1594 
1595   void *ret_val;
1596 
1597   {
1598     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
1599                    Locker::FreeLock);
1600     ret_val = LLDBSWIGPythonCreateOSPlugin(
1601         class_name, m_dictionary_name.c_str(), process_sp);
1602   }
1603 
1604   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
1605 }
1606 
1607 StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo(
1608     StructuredData::ObjectSP os_plugin_object_sp) {
1609   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1610 
1611   static char callee_name[] = "get_register_info";
1612 
1613   if (!os_plugin_object_sp)
1614     return StructuredData::DictionarySP();
1615 
1616   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1617   if (!generic)
1618     return nullptr;
1619 
1620   PythonObject implementor(PyRefType::Borrowed,
1621                            (PyObject *)generic->GetValue());
1622 
1623   if (!implementor.IsAllocated())
1624     return StructuredData::DictionarySP();
1625 
1626   PythonObject pmeth(PyRefType::Owned,
1627                      PyObject_GetAttrString(implementor.get(), callee_name));
1628 
1629   if (PyErr_Occurred())
1630     PyErr_Clear();
1631 
1632   if (!pmeth.IsAllocated())
1633     return StructuredData::DictionarySP();
1634 
1635   if (PyCallable_Check(pmeth.get()) == 0) {
1636     if (PyErr_Occurred())
1637       PyErr_Clear();
1638 
1639     return StructuredData::DictionarySP();
1640   }
1641 
1642   if (PyErr_Occurred())
1643     PyErr_Clear();
1644 
1645   // right now we know this function exists and is callable..
1646   PythonObject py_return(
1647       PyRefType::Owned,
1648       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
1649 
1650   // if it fails, print the error but otherwise go on
1651   if (PyErr_Occurred()) {
1652     PyErr_Print();
1653     PyErr_Clear();
1654   }
1655   if (py_return.get()) {
1656     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1657     return result_dict.CreateStructuredDictionary();
1658   }
1659   return StructuredData::DictionarySP();
1660 }
1661 
1662 StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo(
1663     StructuredData::ObjectSP os_plugin_object_sp) {
1664   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1665 
1666   static char callee_name[] = "get_thread_info";
1667 
1668   if (!os_plugin_object_sp)
1669     return StructuredData::ArraySP();
1670 
1671   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1672   if (!generic)
1673     return nullptr;
1674 
1675   PythonObject implementor(PyRefType::Borrowed,
1676                            (PyObject *)generic->GetValue());
1677 
1678   if (!implementor.IsAllocated())
1679     return StructuredData::ArraySP();
1680 
1681   PythonObject pmeth(PyRefType::Owned,
1682                      PyObject_GetAttrString(implementor.get(), callee_name));
1683 
1684   if (PyErr_Occurred())
1685     PyErr_Clear();
1686 
1687   if (!pmeth.IsAllocated())
1688     return StructuredData::ArraySP();
1689 
1690   if (PyCallable_Check(pmeth.get()) == 0) {
1691     if (PyErr_Occurred())
1692       PyErr_Clear();
1693 
1694     return StructuredData::ArraySP();
1695   }
1696 
1697   if (PyErr_Occurred())
1698     PyErr_Clear();
1699 
1700   // right now we know this function exists and is callable..
1701   PythonObject py_return(
1702       PyRefType::Owned,
1703       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
1704 
1705   // if it fails, print the error but otherwise go on
1706   if (PyErr_Occurred()) {
1707     PyErr_Print();
1708     PyErr_Clear();
1709   }
1710 
1711   if (py_return.get()) {
1712     PythonList result_list(PyRefType::Borrowed, py_return.get());
1713     return result_list.CreateStructuredArray();
1714   }
1715   return StructuredData::ArraySP();
1716 }
1717 
1718 // GetPythonValueFormatString provides a system independent type safe way to
1719 // convert a variable's type into a python value format. Python value formats
1720 // are defined in terms of builtin C types and could change from system to as
1721 // the underlying typedef for uint* types, size_t, off_t and other values
1722 // change.
1723 
1724 template <typename T> const char *GetPythonValueFormatString(T t);
1725 template <> const char *GetPythonValueFormatString(char *) { return "s"; }
1726 template <> const char *GetPythonValueFormatString(char) { return "b"; }
1727 template <> const char *GetPythonValueFormatString(unsigned char) {
1728   return "B";
1729 }
1730 template <> const char *GetPythonValueFormatString(short) { return "h"; }
1731 template <> const char *GetPythonValueFormatString(unsigned short) {
1732   return "H";
1733 }
1734 template <> const char *GetPythonValueFormatString(int) { return "i"; }
1735 template <> const char *GetPythonValueFormatString(unsigned int) { return "I"; }
1736 template <> const char *GetPythonValueFormatString(long) { return "l"; }
1737 template <> const char *GetPythonValueFormatString(unsigned long) {
1738   return "k";
1739 }
1740 template <> const char *GetPythonValueFormatString(long long) { return "L"; }
1741 template <> const char *GetPythonValueFormatString(unsigned long long) {
1742   return "K";
1743 }
1744 template <> const char *GetPythonValueFormatString(float t) { return "f"; }
1745 template <> const char *GetPythonValueFormatString(double t) { return "d"; }
1746 
1747 StructuredData::StringSP
1748 ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData(
1749     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
1750   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1751 
1752   static char callee_name[] = "get_register_data";
1753   static char *param_format =
1754       const_cast<char *>(GetPythonValueFormatString(tid));
1755 
1756   if (!os_plugin_object_sp)
1757     return StructuredData::StringSP();
1758 
1759   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1760   if (!generic)
1761     return nullptr;
1762   PythonObject implementor(PyRefType::Borrowed,
1763                            (PyObject *)generic->GetValue());
1764 
1765   if (!implementor.IsAllocated())
1766     return StructuredData::StringSP();
1767 
1768   PythonObject pmeth(PyRefType::Owned,
1769                      PyObject_GetAttrString(implementor.get(), callee_name));
1770 
1771   if (PyErr_Occurred())
1772     PyErr_Clear();
1773 
1774   if (!pmeth.IsAllocated())
1775     return StructuredData::StringSP();
1776 
1777   if (PyCallable_Check(pmeth.get()) == 0) {
1778     if (PyErr_Occurred())
1779       PyErr_Clear();
1780     return StructuredData::StringSP();
1781   }
1782 
1783   if (PyErr_Occurred())
1784     PyErr_Clear();
1785 
1786   // right now we know this function exists and is callable..
1787   PythonObject py_return(
1788       PyRefType::Owned,
1789       PyObject_CallMethod(implementor.get(), callee_name, param_format, tid));
1790 
1791   // if it fails, print the error but otherwise go on
1792   if (PyErr_Occurred()) {
1793     PyErr_Print();
1794     PyErr_Clear();
1795   }
1796 
1797   if (py_return.get()) {
1798     PythonBytes result(PyRefType::Borrowed, py_return.get());
1799     return result.CreateStructuredString();
1800   }
1801   return StructuredData::StringSP();
1802 }
1803 
1804 StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread(
1805     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
1806     lldb::addr_t context) {
1807   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1808 
1809   static char callee_name[] = "create_thread";
1810   std::string param_format;
1811   param_format += GetPythonValueFormatString(tid);
1812   param_format += GetPythonValueFormatString(context);
1813 
1814   if (!os_plugin_object_sp)
1815     return StructuredData::DictionarySP();
1816 
1817   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1818   if (!generic)
1819     return nullptr;
1820 
1821   PythonObject implementor(PyRefType::Borrowed,
1822                            (PyObject *)generic->GetValue());
1823 
1824   if (!implementor.IsAllocated())
1825     return StructuredData::DictionarySP();
1826 
1827   PythonObject pmeth(PyRefType::Owned,
1828                      PyObject_GetAttrString(implementor.get(), callee_name));
1829 
1830   if (PyErr_Occurred())
1831     PyErr_Clear();
1832 
1833   if (!pmeth.IsAllocated())
1834     return StructuredData::DictionarySP();
1835 
1836   if (PyCallable_Check(pmeth.get()) == 0) {
1837     if (PyErr_Occurred())
1838       PyErr_Clear();
1839     return StructuredData::DictionarySP();
1840   }
1841 
1842   if (PyErr_Occurred())
1843     PyErr_Clear();
1844 
1845   // right now we know this function exists and is callable..
1846   PythonObject py_return(PyRefType::Owned,
1847                          PyObject_CallMethod(implementor.get(), callee_name,
1848                                              &param_format[0], tid, context));
1849 
1850   // if it fails, print the error but otherwise go on
1851   if (PyErr_Occurred()) {
1852     PyErr_Print();
1853     PyErr_Clear();
1854   }
1855 
1856   if (py_return.get()) {
1857     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1858     return result_dict.CreateStructuredDictionary();
1859   }
1860   return StructuredData::DictionarySP();
1861 }
1862 
1863 StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan(
1864     const char *class_name, StructuredDataImpl *args_data,
1865     std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) {
1866   if (class_name == nullptr || class_name[0] == '\0')
1867     return StructuredData::ObjectSP();
1868 
1869   if (!thread_plan_sp.get())
1870     return {};
1871 
1872   Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
1873   ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
1874   ScriptInterpreterPythonImpl *python_interpreter =
1875       static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
1876 
1877   if (!script_interpreter)
1878     return {};
1879 
1880   void *ret_val;
1881 
1882   {
1883     Locker py_lock(this,
1884                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1885     ret_val = LLDBSwigPythonCreateScriptedThreadPlan(
1886         class_name, python_interpreter->m_dictionary_name.c_str(),
1887         args_data, error_str, thread_plan_sp);
1888     if (!ret_val)
1889       return {};
1890   }
1891 
1892   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
1893 }
1894 
1895 bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop(
1896     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1897   bool explains_stop = true;
1898   StructuredData::Generic *generic = nullptr;
1899   if (implementor_sp)
1900     generic = implementor_sp->GetAsGeneric();
1901   if (generic) {
1902     Locker py_lock(this,
1903                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1904     explains_stop = LLDBSWIGPythonCallThreadPlan(
1905         generic->GetValue(), "explains_stop", event, script_error);
1906     if (script_error)
1907       return true;
1908   }
1909   return explains_stop;
1910 }
1911 
1912 bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop(
1913     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1914   bool should_stop = true;
1915   StructuredData::Generic *generic = nullptr;
1916   if (implementor_sp)
1917     generic = implementor_sp->GetAsGeneric();
1918   if (generic) {
1919     Locker py_lock(this,
1920                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1921     should_stop = LLDBSWIGPythonCallThreadPlan(
1922         generic->GetValue(), "should_stop", event, script_error);
1923     if (script_error)
1924       return true;
1925   }
1926   return should_stop;
1927 }
1928 
1929 bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale(
1930     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1931   bool is_stale = true;
1932   StructuredData::Generic *generic = nullptr;
1933   if (implementor_sp)
1934     generic = implementor_sp->GetAsGeneric();
1935   if (generic) {
1936     Locker py_lock(this,
1937                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1938     is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale",
1939                                             nullptr, script_error);
1940     if (script_error)
1941       return true;
1942   }
1943   return is_stale;
1944 }
1945 
1946 lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState(
1947     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1948   bool should_step = false;
1949   StructuredData::Generic *generic = nullptr;
1950   if (implementor_sp)
1951     generic = implementor_sp->GetAsGeneric();
1952   if (generic) {
1953     Locker py_lock(this,
1954                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1955     should_step = LLDBSWIGPythonCallThreadPlan(
1956         generic->GetValue(), "should_step", nullptr, script_error);
1957     if (script_error)
1958       should_step = true;
1959   }
1960   if (should_step)
1961     return lldb::eStateStepping;
1962   else
1963     return lldb::eStateRunning;
1964 }
1965 
1966 StructuredData::GenericSP
1967 ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
1968     const char *class_name, StructuredDataImpl *args_data,
1969     lldb::BreakpointSP &bkpt_sp) {
1970 
1971   if (class_name == nullptr || class_name[0] == '\0')
1972     return StructuredData::GenericSP();
1973 
1974   if (!bkpt_sp.get())
1975     return StructuredData::GenericSP();
1976 
1977   Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
1978   ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
1979   ScriptInterpreterPythonImpl *python_interpreter =
1980       static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
1981 
1982   if (!script_interpreter)
1983     return StructuredData::GenericSP();
1984 
1985   void *ret_val;
1986 
1987   {
1988     Locker py_lock(this,
1989                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1990 
1991     ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver(
1992         class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
1993         bkpt_sp);
1994   }
1995 
1996   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
1997 }
1998 
1999 bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
2000     StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
2001   bool should_continue = false;
2002 
2003   if (implementor_sp) {
2004     Locker py_lock(this,
2005                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2006     should_continue = LLDBSwigPythonCallBreakpointResolver(
2007         implementor_sp->GetValue(), "__callback__", sym_ctx);
2008     if (PyErr_Occurred()) {
2009       PyErr_Print();
2010       PyErr_Clear();
2011     }
2012   }
2013   return should_continue;
2014 }
2015 
2016 lldb::SearchDepth
2017 ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
2018     StructuredData::GenericSP implementor_sp) {
2019   int depth_as_int = lldb::eSearchDepthModule;
2020   if (implementor_sp) {
2021     Locker py_lock(this,
2022                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2023     depth_as_int = LLDBSwigPythonCallBreakpointResolver(
2024         implementor_sp->GetValue(), "__get_depth__", nullptr);
2025     if (PyErr_Occurred()) {
2026       PyErr_Print();
2027       PyErr_Clear();
2028     }
2029   }
2030   if (depth_as_int == lldb::eSearchDepthInvalid)
2031     return lldb::eSearchDepthModule;
2032 
2033   if (depth_as_int <= lldb::kLastSearchDepthKind)
2034     return (lldb::SearchDepth)depth_as_int;
2035   else
2036     return lldb::eSearchDepthModule;
2037 }
2038 
2039 StructuredData::ObjectSP
2040 ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
2041                                               lldb_private::Status &error) {
2042   if (!FileSystem::Instance().Exists(file_spec)) {
2043     error.SetErrorString("no such file");
2044     return StructuredData::ObjectSP();
2045   }
2046 
2047   StructuredData::ObjectSP module_sp;
2048 
2049   if (LoadScriptingModule(file_spec.GetPath().c_str(), true, true, error,
2050                           &module_sp))
2051     return module_sp;
2052 
2053   return StructuredData::ObjectSP();
2054 }
2055 
2056 StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
2057     StructuredData::ObjectSP plugin_module_sp, Target *target,
2058     const char *setting_name, lldb_private::Status &error) {
2059   if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
2060     return StructuredData::DictionarySP();
2061   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
2062   if (!generic)
2063     return StructuredData::DictionarySP();
2064 
2065   Locker py_lock(this,
2066                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2067   TargetSP target_sp(target->shared_from_this());
2068 
2069   auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting(
2070       generic->GetValue(), setting_name, target_sp);
2071 
2072   if (!setting)
2073     return StructuredData::DictionarySP();
2074 
2075   PythonDictionary py_dict =
2076       unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
2077 
2078   if (!py_dict)
2079     return StructuredData::DictionarySP();
2080 
2081   return py_dict.CreateStructuredDictionary();
2082 }
2083 
2084 StructuredData::ObjectSP
2085 ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
2086     const char *class_name, lldb::ValueObjectSP valobj) {
2087   if (class_name == nullptr || class_name[0] == '\0')
2088     return StructuredData::ObjectSP();
2089 
2090   if (!valobj.get())
2091     return StructuredData::ObjectSP();
2092 
2093   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
2094   Target *target = exe_ctx.GetTargetPtr();
2095 
2096   if (!target)
2097     return StructuredData::ObjectSP();
2098 
2099   Debugger &debugger = target->GetDebugger();
2100   ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
2101   ScriptInterpreterPythonImpl *python_interpreter =
2102       (ScriptInterpreterPythonImpl *)script_interpreter;
2103 
2104   if (!script_interpreter)
2105     return StructuredData::ObjectSP();
2106 
2107   void *ret_val = nullptr;
2108 
2109   {
2110     Locker py_lock(this,
2111                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2112     ret_val = LLDBSwigPythonCreateSyntheticProvider(
2113         class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
2114   }
2115 
2116   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
2117 }
2118 
2119 StructuredData::GenericSP
2120 ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
2121   DebuggerSP debugger_sp(m_debugger.shared_from_this());
2122 
2123   if (class_name == nullptr || class_name[0] == '\0')
2124     return StructuredData::GenericSP();
2125 
2126   if (!debugger_sp.get())
2127     return StructuredData::GenericSP();
2128 
2129   void *ret_val;
2130 
2131   {
2132     Locker py_lock(this,
2133                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2134     ret_val = LLDBSwigPythonCreateCommandObject(
2135         class_name, m_dictionary_name.c_str(), debugger_sp);
2136   }
2137 
2138   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
2139 }
2140 
2141 bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
2142     const char *oneliner, std::string &output, const void *name_token) {
2143   StringList input;
2144   input.SplitIntoLines(oneliner, strlen(oneliner));
2145   return GenerateTypeScriptFunction(input, output, name_token);
2146 }
2147 
2148 bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
2149     const char *oneliner, std::string &output, const void *name_token) {
2150   StringList input;
2151   input.SplitIntoLines(oneliner, strlen(oneliner));
2152   return GenerateTypeSynthClass(input, output, name_token);
2153 }
2154 
2155 Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
2156     StringList &user_input, std::string &output,
2157     bool has_extra_args) {
2158   static uint32_t num_created_functions = 0;
2159   user_input.RemoveBlankLines();
2160   StreamString sstr;
2161   Status error;
2162   if (user_input.GetSize() == 0) {
2163     error.SetErrorString("No input data.");
2164     return error;
2165   }
2166 
2167   std::string auto_generated_function_name(GenerateUniqueName(
2168       "lldb_autogen_python_bp_callback_func_", num_created_functions));
2169   if (has_extra_args)
2170     sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
2171                 auto_generated_function_name.c_str());
2172   else
2173     sstr.Printf("def %s (frame, bp_loc, internal_dict):",
2174                 auto_generated_function_name.c_str());
2175 
2176   error = GenerateFunction(sstr.GetData(), user_input);
2177   if (!error.Success())
2178     return error;
2179 
2180   // Store the name of the auto-generated function to be called.
2181   output.assign(auto_generated_function_name);
2182   return error;
2183 }
2184 
2185 bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
2186     StringList &user_input, std::string &output) {
2187   static uint32_t num_created_functions = 0;
2188   user_input.RemoveBlankLines();
2189   StreamString sstr;
2190 
2191   if (user_input.GetSize() == 0)
2192     return false;
2193 
2194   std::string auto_generated_function_name(GenerateUniqueName(
2195       "lldb_autogen_python_wp_callback_func_", num_created_functions));
2196   sstr.Printf("def %s (frame, wp, internal_dict):",
2197               auto_generated_function_name.c_str());
2198 
2199   if (!GenerateFunction(sstr.GetData(), user_input).Success())
2200     return false;
2201 
2202   // Store the name of the auto-generated function to be called.
2203   output.assign(auto_generated_function_name);
2204   return true;
2205 }
2206 
2207 bool ScriptInterpreterPythonImpl::GetScriptedSummary(
2208     const char *python_function_name, lldb::ValueObjectSP valobj,
2209     StructuredData::ObjectSP &callee_wrapper_sp,
2210     const TypeSummaryOptions &options, std::string &retval) {
2211 
2212   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2213   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
2214 
2215   if (!valobj.get()) {
2216     retval.assign("<no object>");
2217     return false;
2218   }
2219 
2220   void *old_callee = nullptr;
2221   StructuredData::Generic *generic = nullptr;
2222   if (callee_wrapper_sp) {
2223     generic = callee_wrapper_sp->GetAsGeneric();
2224     if (generic)
2225       old_callee = generic->GetValue();
2226   }
2227   void *new_callee = old_callee;
2228 
2229   bool ret_val;
2230   if (python_function_name && *python_function_name) {
2231     {
2232       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
2233                                Locker::NoSTDIN);
2234       {
2235         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
2236 
2237         static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
2238         Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
2239         ret_val = LLDBSwigPythonCallTypeScript(
2240             python_function_name, GetSessionDictionary().get(), valobj,
2241             &new_callee, options_sp, retval);
2242       }
2243     }
2244   } else {
2245     retval.assign("<no function name>");
2246     return false;
2247   }
2248 
2249   if (new_callee && old_callee != new_callee)
2250     callee_wrapper_sp = std::make_shared<StructuredPythonObject>(new_callee);
2251 
2252   return ret_val;
2253 }
2254 
2255 bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
2256     void *baton, StoppointCallbackContext *context, user_id_t break_id,
2257     user_id_t break_loc_id) {
2258   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
2259   const char *python_function_name = bp_option_data->script_source.c_str();
2260 
2261   if (!context)
2262     return true;
2263 
2264   ExecutionContext exe_ctx(context->exe_ctx_ref);
2265   Target *target = exe_ctx.GetTargetPtr();
2266 
2267   if (!target)
2268     return true;
2269 
2270   Debugger &debugger = target->GetDebugger();
2271   ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
2272   ScriptInterpreterPythonImpl *python_interpreter =
2273       (ScriptInterpreterPythonImpl *)script_interpreter;
2274 
2275   if (!script_interpreter)
2276     return true;
2277 
2278   if (python_function_name && python_function_name[0]) {
2279     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2280     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2281     if (breakpoint_sp) {
2282       const BreakpointLocationSP bp_loc_sp(
2283           breakpoint_sp->FindLocationByID(break_loc_id));
2284 
2285       if (stop_frame_sp && bp_loc_sp) {
2286         bool ret_val = true;
2287         {
2288           Locker py_lock(python_interpreter, Locker::AcquireLock |
2289                                                  Locker::InitSession |
2290                                                  Locker::NoSTDIN);
2291           Expected<bool> maybe_ret_val =
2292               LLDBSwigPythonBreakpointCallbackFunction(
2293                   python_function_name,
2294                   python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2295                   bp_loc_sp, bp_option_data->m_extra_args_up.get());
2296 
2297           if (!maybe_ret_val) {
2298 
2299             llvm::handleAllErrors(
2300                 maybe_ret_val.takeError(),
2301                 [&](PythonException &E) {
2302                   debugger.GetErrorStream() << E.ReadBacktrace();
2303                 },
2304                 [&](const llvm::ErrorInfoBase &E) {
2305                   debugger.GetErrorStream() << E.message();
2306                 });
2307 
2308           } else {
2309             ret_val = maybe_ret_val.get();
2310           }
2311         }
2312         return ret_val;
2313       }
2314     }
2315   }
2316   // We currently always true so we stop in case anything goes wrong when
2317   // trying to call the script function
2318   return true;
2319 }
2320 
2321 bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
2322     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2323   WatchpointOptions::CommandData *wp_option_data =
2324       (WatchpointOptions::CommandData *)baton;
2325   const char *python_function_name = wp_option_data->script_source.c_str();
2326 
2327   if (!context)
2328     return true;
2329 
2330   ExecutionContext exe_ctx(context->exe_ctx_ref);
2331   Target *target = exe_ctx.GetTargetPtr();
2332 
2333   if (!target)
2334     return true;
2335 
2336   Debugger &debugger = target->GetDebugger();
2337   ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
2338   ScriptInterpreterPythonImpl *python_interpreter =
2339       (ScriptInterpreterPythonImpl *)script_interpreter;
2340 
2341   if (!script_interpreter)
2342     return true;
2343 
2344   if (python_function_name && python_function_name[0]) {
2345     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2346     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2347     if (wp_sp) {
2348       if (stop_frame_sp && wp_sp) {
2349         bool ret_val = true;
2350         {
2351           Locker py_lock(python_interpreter, Locker::AcquireLock |
2352                                                  Locker::InitSession |
2353                                                  Locker::NoSTDIN);
2354           ret_val = LLDBSwigPythonWatchpointCallbackFunction(
2355               python_function_name,
2356               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2357               wp_sp);
2358         }
2359         return ret_val;
2360       }
2361     }
2362   }
2363   // We currently always true so we stop in case anything goes wrong when
2364   // trying to call the script function
2365   return true;
2366 }
2367 
2368 size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2369     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
2370   if (!implementor_sp)
2371     return 0;
2372   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2373   if (!generic)
2374     return 0;
2375   void *implementor = generic->GetValue();
2376   if (!implementor)
2377     return 0;
2378 
2379   size_t ret_val = 0;
2380 
2381   {
2382     Locker py_lock(this,
2383                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2384     ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max);
2385   }
2386 
2387   return ret_val;
2388 }
2389 
2390 lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
2391     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
2392   if (!implementor_sp)
2393     return lldb::ValueObjectSP();
2394 
2395   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2396   if (!generic)
2397     return lldb::ValueObjectSP();
2398   void *implementor = generic->GetValue();
2399   if (!implementor)
2400     return lldb::ValueObjectSP();
2401 
2402   lldb::ValueObjectSP ret_val;
2403   {
2404     Locker py_lock(this,
2405                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2406     void *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx);
2407     if (child_ptr != nullptr && child_ptr != Py_None) {
2408       lldb::SBValue *sb_value_ptr =
2409           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2410       if (sb_value_ptr == nullptr)
2411         Py_XDECREF(child_ptr);
2412       else
2413         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2414     } else {
2415       Py_XDECREF(child_ptr);
2416     }
2417   }
2418 
2419   return ret_val;
2420 }
2421 
2422 int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2423     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
2424   if (!implementor_sp)
2425     return UINT32_MAX;
2426 
2427   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2428   if (!generic)
2429     return UINT32_MAX;
2430   void *implementor = generic->GetValue();
2431   if (!implementor)
2432     return UINT32_MAX;
2433 
2434   int ret_val = UINT32_MAX;
2435 
2436   {
2437     Locker py_lock(this,
2438                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2439     ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
2440   }
2441 
2442   return ret_val;
2443 }
2444 
2445 bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2446     const StructuredData::ObjectSP &implementor_sp) {
2447   bool ret_val = false;
2448 
2449   if (!implementor_sp)
2450     return ret_val;
2451 
2452   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2453   if (!generic)
2454     return ret_val;
2455   void *implementor = generic->GetValue();
2456   if (!implementor)
2457     return ret_val;
2458 
2459   {
2460     Locker py_lock(this,
2461                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2462     ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor);
2463   }
2464 
2465   return ret_val;
2466 }
2467 
2468 bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2469     const StructuredData::ObjectSP &implementor_sp) {
2470   bool ret_val = false;
2471 
2472   if (!implementor_sp)
2473     return ret_val;
2474 
2475   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2476   if (!generic)
2477     return ret_val;
2478   void *implementor = generic->GetValue();
2479   if (!implementor)
2480     return ret_val;
2481 
2482   {
2483     Locker py_lock(this,
2484                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2485     ret_val =
2486         LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor);
2487   }
2488 
2489   return ret_val;
2490 }
2491 
2492 lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
2493     const StructuredData::ObjectSP &implementor_sp) {
2494   lldb::ValueObjectSP ret_val(nullptr);
2495 
2496   if (!implementor_sp)
2497     return ret_val;
2498 
2499   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2500   if (!generic)
2501     return ret_val;
2502   void *implementor = generic->GetValue();
2503   if (!implementor)
2504     return ret_val;
2505 
2506   {
2507     Locker py_lock(this,
2508                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2509     void *child_ptr = LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2510     if (child_ptr != nullptr && child_ptr != Py_None) {
2511       lldb::SBValue *sb_value_ptr =
2512           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2513       if (sb_value_ptr == nullptr)
2514         Py_XDECREF(child_ptr);
2515       else
2516         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2517     } else {
2518       Py_XDECREF(child_ptr);
2519     }
2520   }
2521 
2522   return ret_val;
2523 }
2524 
2525 ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2526     const StructuredData::ObjectSP &implementor_sp) {
2527   Locker py_lock(this,
2528                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2529 
2530   static char callee_name[] = "get_type_name";
2531 
2532   ConstString ret_val;
2533   bool got_string = false;
2534   std::string buffer;
2535 
2536   if (!implementor_sp)
2537     return ret_val;
2538 
2539   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2540   if (!generic)
2541     return ret_val;
2542   PythonObject implementor(PyRefType::Borrowed,
2543                            (PyObject *)generic->GetValue());
2544   if (!implementor.IsAllocated())
2545     return ret_val;
2546 
2547   PythonObject pmeth(PyRefType::Owned,
2548                      PyObject_GetAttrString(implementor.get(), callee_name));
2549 
2550   if (PyErr_Occurred())
2551     PyErr_Clear();
2552 
2553   if (!pmeth.IsAllocated())
2554     return ret_val;
2555 
2556   if (PyCallable_Check(pmeth.get()) == 0) {
2557     if (PyErr_Occurred())
2558       PyErr_Clear();
2559     return ret_val;
2560   }
2561 
2562   if (PyErr_Occurred())
2563     PyErr_Clear();
2564 
2565   // right now we know this function exists and is callable..
2566   PythonObject py_return(
2567       PyRefType::Owned,
2568       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
2569 
2570   // if it fails, print the error but otherwise go on
2571   if (PyErr_Occurred()) {
2572     PyErr_Print();
2573     PyErr_Clear();
2574   }
2575 
2576   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2577     PythonString py_string(PyRefType::Borrowed, py_return.get());
2578     llvm::StringRef return_data(py_string.GetString());
2579     if (!return_data.empty()) {
2580       buffer.assign(return_data.data(), return_data.size());
2581       got_string = true;
2582     }
2583   }
2584 
2585   if (got_string)
2586     ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
2587 
2588   return ret_val;
2589 }
2590 
2591 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2592     const char *impl_function, Process *process, std::string &output,
2593     Status &error) {
2594   bool ret_val;
2595   if (!process) {
2596     error.SetErrorString("no process");
2597     return false;
2598   }
2599   if (!impl_function || !impl_function[0]) {
2600     error.SetErrorString("no function to execute");
2601     return false;
2602   }
2603 
2604   {
2605     ProcessSP process_sp(process->shared_from_this());
2606     Locker py_lock(this,
2607                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2608     ret_val = LLDBSWIGPythonRunScriptKeywordProcess(
2609         impl_function, m_dictionary_name.c_str(), process_sp, output);
2610     if (!ret_val)
2611       error.SetErrorString("python script evaluation failed");
2612   }
2613   return ret_val;
2614 }
2615 
2616 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2617     const char *impl_function, Thread *thread, std::string &output,
2618     Status &error) {
2619   bool ret_val;
2620   if (!thread) {
2621     error.SetErrorString("no thread");
2622     return false;
2623   }
2624   if (!impl_function || !impl_function[0]) {
2625     error.SetErrorString("no function to execute");
2626     return false;
2627   }
2628 
2629   {
2630     ThreadSP thread_sp(thread->shared_from_this());
2631     Locker py_lock(this,
2632                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2633     ret_val = LLDBSWIGPythonRunScriptKeywordThread(
2634         impl_function, m_dictionary_name.c_str(), thread_sp, output);
2635     if (!ret_val)
2636       error.SetErrorString("python script evaluation failed");
2637   }
2638   return ret_val;
2639 }
2640 
2641 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2642     const char *impl_function, Target *target, std::string &output,
2643     Status &error) {
2644   bool ret_val;
2645   if (!target) {
2646     error.SetErrorString("no thread");
2647     return false;
2648   }
2649   if (!impl_function || !impl_function[0]) {
2650     error.SetErrorString("no function to execute");
2651     return false;
2652   }
2653 
2654   {
2655     TargetSP target_sp(target->shared_from_this());
2656     Locker py_lock(this,
2657                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2658     ret_val = LLDBSWIGPythonRunScriptKeywordTarget(
2659         impl_function, m_dictionary_name.c_str(), target_sp, output);
2660     if (!ret_val)
2661       error.SetErrorString("python script evaluation failed");
2662   }
2663   return ret_val;
2664 }
2665 
2666 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2667     const char *impl_function, StackFrame *frame, std::string &output,
2668     Status &error) {
2669   bool ret_val;
2670   if (!frame) {
2671     error.SetErrorString("no frame");
2672     return false;
2673   }
2674   if (!impl_function || !impl_function[0]) {
2675     error.SetErrorString("no function to execute");
2676     return false;
2677   }
2678 
2679   {
2680     StackFrameSP frame_sp(frame->shared_from_this());
2681     Locker py_lock(this,
2682                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2683     ret_val = LLDBSWIGPythonRunScriptKeywordFrame(
2684         impl_function, m_dictionary_name.c_str(), frame_sp, output);
2685     if (!ret_val)
2686       error.SetErrorString("python script evaluation failed");
2687   }
2688   return ret_val;
2689 }
2690 
2691 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2692     const char *impl_function, ValueObject *value, std::string &output,
2693     Status &error) {
2694   bool ret_val;
2695   if (!value) {
2696     error.SetErrorString("no value");
2697     return false;
2698   }
2699   if (!impl_function || !impl_function[0]) {
2700     error.SetErrorString("no function to execute");
2701     return false;
2702   }
2703 
2704   {
2705     ValueObjectSP value_sp(value->GetSP());
2706     Locker py_lock(this,
2707                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2708     ret_val = LLDBSWIGPythonRunScriptKeywordValue(
2709         impl_function, m_dictionary_name.c_str(), value_sp, output);
2710     if (!ret_val)
2711       error.SetErrorString("python script evaluation failed");
2712   }
2713   return ret_val;
2714 }
2715 
2716 uint64_t replace_all(std::string &str, const std::string &oldStr,
2717                      const std::string &newStr) {
2718   size_t pos = 0;
2719   uint64_t matches = 0;
2720   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2721     matches++;
2722     str.replace(pos, oldStr.length(), newStr);
2723     pos += newStr.length();
2724   }
2725   return matches;
2726 }
2727 
2728 bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2729     const char *pathname, bool can_reload, bool init_session,
2730     lldb_private::Status &error, StructuredData::ObjectSP *module_sp) {
2731   if (!pathname || !pathname[0]) {
2732     error.SetErrorString("invalid pathname");
2733     return false;
2734   }
2735 
2736   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2737 
2738   {
2739     FileSpec target_file(pathname);
2740     FileSystem::Instance().Resolve(target_file);
2741     std::string basename(target_file.GetFilename().GetCString());
2742 
2743     StreamString command_stream;
2744 
2745     // Before executing Python code, lock the GIL.
2746     Locker py_lock(this,
2747                    Locker::AcquireLock |
2748                        (init_session ? Locker::InitSession : 0) |
2749                        Locker::NoSTDIN,
2750                    Locker::FreeAcquiredLock |
2751                        (init_session ? Locker::TearDownSession : 0));
2752     namespace fs = llvm::sys::fs;
2753     fs::file_status st;
2754     std::error_code ec = status(target_file.GetPath(), st);
2755 
2756     if (ec || st.type() == fs::file_type::status_error ||
2757         st.type() == fs::file_type::type_unknown ||
2758         st.type() == fs::file_type::file_not_found) {
2759       // if not a valid file of any sort, check if it might be a filename still
2760       // dot can't be used but / and \ can, and if either is found, reject
2761       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2762         error.SetErrorString("invalid pathname");
2763         return false;
2764       }
2765       basename = pathname; // not a filename, probably a package of some sort,
2766                            // let it go through
2767     } else if (is_directory(st) || is_regular_file(st)) {
2768       if (target_file.GetDirectory().IsEmpty()) {
2769         error.SetErrorString("invalid directory name");
2770         return false;
2771       }
2772 
2773       std::string directory = target_file.GetDirectory().GetCString();
2774       replace_all(directory, "\\", "\\\\");
2775       replace_all(directory, "'", "\\'");
2776 
2777       // now make sure that Python has "directory" in the search path
2778       StreamString command_stream;
2779       command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
2780                             "sys.path.insert(1,'%s');\n\n",
2781                             directory.c_str(), directory.c_str());
2782       bool syspath_retval =
2783           ExecuteMultipleLines(command_stream.GetData(),
2784                                ScriptInterpreter::ExecuteScriptOptions()
2785                                    .SetEnableIO(false)
2786                                    .SetSetLLDBGlobals(false))
2787               .Success();
2788       if (!syspath_retval) {
2789         error.SetErrorString("Python sys.path handling failed");
2790         return false;
2791       }
2792 
2793       // strip .py or .pyc extension
2794       ConstString extension = target_file.GetFileNameExtension();
2795       if (extension) {
2796         if (llvm::StringRef(extension.GetCString()) == ".py")
2797           basename.resize(basename.length() - 3);
2798         else if (llvm::StringRef(extension.GetCString()) == ".pyc")
2799           basename.resize(basename.length() - 4);
2800       }
2801     } else {
2802       error.SetErrorString("no known way to import this module specification");
2803       return false;
2804     }
2805 
2806     // check if the module is already import-ed
2807     command_stream.Clear();
2808     command_stream.Printf("sys.modules.__contains__('%s')", basename.c_str());
2809     bool does_contain = false;
2810     // this call will succeed if the module was ever imported in any Debugger
2811     // in the lifetime of the process in which this LLDB framework is living
2812     bool was_imported_globally =
2813         (ExecuteOneLineWithReturn(
2814              command_stream.GetData(),
2815              ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain,
2816              ScriptInterpreter::ExecuteScriptOptions()
2817                  .SetEnableIO(false)
2818                  .SetSetLLDBGlobals(false)) &&
2819          does_contain);
2820     // this call will fail if the module was not imported in this Debugger
2821     // before
2822     command_stream.Clear();
2823     command_stream.Printf("sys.getrefcount(%s)", basename.c_str());
2824     bool was_imported_locally = GetSessionDictionary()
2825                                     .GetItemForKey(PythonString(basename))
2826                                     .IsAllocated();
2827 
2828     bool was_imported = (was_imported_globally || was_imported_locally);
2829 
2830     if (was_imported && !can_reload) {
2831       error.SetErrorString("module already imported");
2832       return false;
2833     }
2834 
2835     // now actually do the import
2836     command_stream.Clear();
2837 
2838     if (was_imported) {
2839       if (!was_imported_locally)
2840         command_stream.Printf("import %s ; reload_module(%s)", basename.c_str(),
2841                               basename.c_str());
2842       else
2843         command_stream.Printf("reload_module(%s)", basename.c_str());
2844     } else
2845       command_stream.Printf("import %s", basename.c_str());
2846 
2847     error = ExecuteMultipleLines(command_stream.GetData(),
2848                                  ScriptInterpreter::ExecuteScriptOptions()
2849                                      .SetEnableIO(false)
2850                                      .SetSetLLDBGlobals(false));
2851     if (error.Fail())
2852       return false;
2853 
2854     // if we are here, everything worked
2855     // call __lldb_init_module(debugger,dict)
2856     if (!LLDBSwigPythonCallModuleInit(basename.c_str(),
2857                                       m_dictionary_name.c_str(), debugger_sp)) {
2858       error.SetErrorString("calling __lldb_init_module failed");
2859       return false;
2860     }
2861 
2862     if (module_sp) {
2863       // everything went just great, now set the module object
2864       command_stream.Clear();
2865       command_stream.Printf("%s", basename.c_str());
2866       void *module_pyobj = nullptr;
2867       if (ExecuteOneLineWithReturn(
2868               command_stream.GetData(),
2869               ScriptInterpreter::eScriptReturnTypeOpaqueObject,
2870               &module_pyobj) &&
2871           module_pyobj)
2872         *module_sp = std::make_shared<StructuredPythonObject>(module_pyobj);
2873     }
2874 
2875     return true;
2876   }
2877 }
2878 
2879 bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
2880   if (!word || !word[0])
2881     return false;
2882 
2883   llvm::StringRef word_sr(word);
2884 
2885   // filter out a few characters that would just confuse us and that are
2886   // clearly not keyword material anyway
2887   if (word_sr.find('"') != llvm::StringRef::npos ||
2888       word_sr.find('\'') != llvm::StringRef::npos)
2889     return false;
2890 
2891   StreamString command_stream;
2892   command_stream.Printf("keyword.iskeyword('%s')", word);
2893   bool result;
2894   ExecuteScriptOptions options;
2895   options.SetEnableIO(false);
2896   options.SetMaskoutErrors(true);
2897   options.SetSetLLDBGlobals(false);
2898   if (ExecuteOneLineWithReturn(command_stream.GetData(),
2899                                ScriptInterpreter::eScriptReturnTypeBool,
2900                                &result, options))
2901     return result;
2902   return false;
2903 }
2904 
2905 ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2906     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2907     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2908       m_old_asynch(debugger_sp->GetAsyncExecution()) {
2909   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2910     m_debugger_sp->SetAsyncExecution(false);
2911   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2912     m_debugger_sp->SetAsyncExecution(true);
2913 }
2914 
2915 ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
2916   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2917     m_debugger_sp->SetAsyncExecution(m_old_asynch);
2918 }
2919 
2920 bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2921     const char *impl_function, llvm::StringRef args,
2922     ScriptedCommandSynchronicity synchronicity,
2923     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2924     const lldb_private::ExecutionContext &exe_ctx) {
2925   if (!impl_function) {
2926     error.SetErrorString("no function to execute");
2927     return false;
2928   }
2929 
2930   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2931   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2932 
2933   if (!debugger_sp.get()) {
2934     error.SetErrorString("invalid Debugger pointer");
2935     return false;
2936   }
2937 
2938   bool ret_val = false;
2939 
2940   std::string err_msg;
2941 
2942   {
2943     Locker py_lock(this,
2944                    Locker::AcquireLock | Locker::InitSession |
2945                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2946                    Locker::FreeLock | Locker::TearDownSession);
2947 
2948     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2949 
2950     std::string args_str = args.str();
2951     ret_val = LLDBSwigPythonCallCommand(
2952         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2953         cmd_retobj, exe_ctx_ref_sp);
2954   }
2955 
2956   if (!ret_val)
2957     error.SetErrorString("unable to execute script function");
2958   else
2959     error.Clear();
2960 
2961   return ret_val;
2962 }
2963 
2964 bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2965     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
2966     ScriptedCommandSynchronicity synchronicity,
2967     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2968     const lldb_private::ExecutionContext &exe_ctx) {
2969   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2970     error.SetErrorString("no function to execute");
2971     return false;
2972   }
2973 
2974   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2975   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2976 
2977   if (!debugger_sp.get()) {
2978     error.SetErrorString("invalid Debugger pointer");
2979     return false;
2980   }
2981 
2982   bool ret_val = false;
2983 
2984   std::string err_msg;
2985 
2986   {
2987     Locker py_lock(this,
2988                    Locker::AcquireLock | Locker::InitSession |
2989                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2990                    Locker::FreeLock | Locker::TearDownSession);
2991 
2992     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2993 
2994     std::string args_str = args.str();
2995     ret_val = LLDBSwigPythonCallCommandObject(impl_obj_sp->GetValue(),
2996                                               debugger_sp, args_str.c_str(),
2997                                               cmd_retobj, exe_ctx_ref_sp);
2998   }
2999 
3000   if (!ret_val)
3001     error.SetErrorString("unable to execute script function");
3002   else
3003     error.Clear();
3004 
3005   return ret_val;
3006 }
3007 
3008 // in Python, a special attribute __doc__ contains the docstring for an object
3009 // (function, method, class, ...) if any is defined Otherwise, the attribute's
3010 // value is None
3011 bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
3012                                                           std::string &dest) {
3013   dest.clear();
3014   if (!item || !*item)
3015     return false;
3016   std::string command(item);
3017   command += ".__doc__";
3018 
3019   char *result_ptr = nullptr; // Python is going to point this to valid data if
3020                               // ExecuteOneLineWithReturn returns successfully
3021 
3022   if (ExecuteOneLineWithReturn(
3023           command.c_str(), ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
3024           &result_ptr,
3025           ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false))) {
3026     if (result_ptr)
3027       dest.assign(result_ptr);
3028     return true;
3029   } else {
3030     StreamString str_stream;
3031     str_stream.Printf(
3032         "Function %s was not found. Containing module might be missing.", item);
3033     dest = str_stream.GetString();
3034     return false;
3035   }
3036 }
3037 
3038 bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
3039     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
3040   bool got_string = false;
3041   dest.clear();
3042 
3043   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3044 
3045   static char callee_name[] = "get_short_help";
3046 
3047   if (!cmd_obj_sp)
3048     return false;
3049 
3050   PythonObject implementor(PyRefType::Borrowed,
3051                            (PyObject *)cmd_obj_sp->GetValue());
3052 
3053   if (!implementor.IsAllocated())
3054     return false;
3055 
3056   PythonObject pmeth(PyRefType::Owned,
3057                      PyObject_GetAttrString(implementor.get(), callee_name));
3058 
3059   if (PyErr_Occurred())
3060     PyErr_Clear();
3061 
3062   if (!pmeth.IsAllocated())
3063     return false;
3064 
3065   if (PyCallable_Check(pmeth.get()) == 0) {
3066     if (PyErr_Occurred())
3067       PyErr_Clear();
3068     return false;
3069   }
3070 
3071   if (PyErr_Occurred())
3072     PyErr_Clear();
3073 
3074   // right now we know this function exists and is callable..
3075   PythonObject py_return(
3076       PyRefType::Owned,
3077       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3078 
3079   // if it fails, print the error but otherwise go on
3080   if (PyErr_Occurred()) {
3081     PyErr_Print();
3082     PyErr_Clear();
3083   }
3084 
3085   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3086     PythonString py_string(PyRefType::Borrowed, py_return.get());
3087     llvm::StringRef return_data(py_string.GetString());
3088     dest.assign(return_data.data(), return_data.size());
3089     got_string = true;
3090   }
3091   return got_string;
3092 }
3093 
3094 uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
3095     StructuredData::GenericSP cmd_obj_sp) {
3096   uint32_t result = 0;
3097 
3098   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3099 
3100   static char callee_name[] = "get_flags";
3101 
3102   if (!cmd_obj_sp)
3103     return result;
3104 
3105   PythonObject implementor(PyRefType::Borrowed,
3106                            (PyObject *)cmd_obj_sp->GetValue());
3107 
3108   if (!implementor.IsAllocated())
3109     return result;
3110 
3111   PythonObject pmeth(PyRefType::Owned,
3112                      PyObject_GetAttrString(implementor.get(), callee_name));
3113 
3114   if (PyErr_Occurred())
3115     PyErr_Clear();
3116 
3117   if (!pmeth.IsAllocated())
3118     return result;
3119 
3120   if (PyCallable_Check(pmeth.get()) == 0) {
3121     if (PyErr_Occurred())
3122       PyErr_Clear();
3123     return result;
3124   }
3125 
3126   if (PyErr_Occurred())
3127     PyErr_Clear();
3128 
3129   // right now we know this function exists and is callable..
3130   PythonObject py_return(
3131       PyRefType::Owned,
3132       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3133 
3134   // if it fails, print the error but otherwise go on
3135   if (PyErr_Occurred()) {
3136     PyErr_Print();
3137     PyErr_Clear();
3138   }
3139 
3140   if (py_return.IsAllocated() && PythonInteger::Check(py_return.get())) {
3141     PythonInteger int_value(PyRefType::Borrowed, py_return.get());
3142     result = int_value.GetInteger();
3143   }
3144 
3145   return result;
3146 }
3147 
3148 bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3149     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
3150   bool got_string = false;
3151   dest.clear();
3152 
3153   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3154 
3155   static char callee_name[] = "get_long_help";
3156 
3157   if (!cmd_obj_sp)
3158     return false;
3159 
3160   PythonObject implementor(PyRefType::Borrowed,
3161                            (PyObject *)cmd_obj_sp->GetValue());
3162 
3163   if (!implementor.IsAllocated())
3164     return false;
3165 
3166   PythonObject pmeth(PyRefType::Owned,
3167                      PyObject_GetAttrString(implementor.get(), callee_name));
3168 
3169   if (PyErr_Occurred())
3170     PyErr_Clear();
3171 
3172   if (!pmeth.IsAllocated())
3173     return false;
3174 
3175   if (PyCallable_Check(pmeth.get()) == 0) {
3176     if (PyErr_Occurred())
3177       PyErr_Clear();
3178 
3179     return false;
3180   }
3181 
3182   if (PyErr_Occurred())
3183     PyErr_Clear();
3184 
3185   // right now we know this function exists and is callable..
3186   PythonObject py_return(
3187       PyRefType::Owned,
3188       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3189 
3190   // if it fails, print the error but otherwise go on
3191   if (PyErr_Occurred()) {
3192     PyErr_Print();
3193     PyErr_Clear();
3194   }
3195 
3196   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3197     PythonString str(PyRefType::Borrowed, py_return.get());
3198     llvm::StringRef str_data(str.GetString());
3199     dest.assign(str_data.data(), str_data.size());
3200     got_string = true;
3201   }
3202 
3203   return got_string;
3204 }
3205 
3206 std::unique_ptr<ScriptInterpreterLocker>
3207 ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3208   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3209       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3210       Locker::FreeLock | Locker::TearDownSession));
3211   return py_lock;
3212 }
3213 
3214 void ScriptInterpreterPythonImpl::InitializePrivate() {
3215   if (g_initialized)
3216     return;
3217 
3218   g_initialized = true;
3219 
3220   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
3221   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
3222 
3223   // RAII-based initialization which correctly handles multiple-initialization,
3224   // version- specific differences among Python 2 and Python 3, and saving and
3225   // restoring various other pieces of state that can get mucked with during
3226   // initialization.
3227   InitializePythonRAII initialize_guard;
3228 
3229   LLDBSwigPyInit();
3230 
3231   // Update the path python uses to search for modules to include the current
3232   // directory.
3233 
3234   PyRun_SimpleString("import sys");
3235   AddToSysPath(AddLocation::End, ".");
3236 
3237   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
3238   // that use a backslash as the path separator, this will result in executing
3239   // python code containing paths with unescaped backslashes.  But Python also
3240   // accepts forward slashes, so to make life easier we just use that.
3241   if (FileSpec file_spec = GetPythonDir())
3242     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3243   if (FileSpec file_spec = HostInfo::GetShlibDir())
3244     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3245 
3246   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3247                      "lldb.embedded_interpreter; from "
3248                      "lldb.embedded_interpreter import run_python_interpreter; "
3249                      "from lldb.embedded_interpreter import run_one_line");
3250 }
3251 
3252 void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3253                                                std::string path) {
3254   std::string path_copy;
3255 
3256   std::string statement;
3257   if (location == AddLocation::Beginning) {
3258     statement.assign("sys.path.insert(0,\"");
3259     statement.append(path);
3260     statement.append("\")");
3261   } else {
3262     statement.assign("sys.path.append(\"");
3263     statement.append(path);
3264     statement.append("\")");
3265   }
3266   PyRun_SimpleString(statement.c_str());
3267 }
3268 
3269 // We are intentionally NOT calling Py_Finalize here (this would be the logical
3270 // place to call it).  Calling Py_Finalize here causes test suite runs to seg
3271 // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
3272 // be called 'at_exit'.  When the test suite Python harness finishes up, it
3273 // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3274 // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3275 // which calls ScriptInterpreter::Terminate, which calls
3276 // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
3277 // end up with Py_Finalize being called from within Py_Finalize, which results
3278 // in a seg fault. Since this function only gets called when lldb is shutting
3279 // down and going away anyway, the fact that we don't actually call Py_Finalize
3280 // should not cause any problems (everything should shut down/go away anyway
3281 // when the process exits).
3282 //
3283 // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3284 
3285 #endif // LLDB_DISABLE_PYTHON
3286