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