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