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