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