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