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