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