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