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