xref: /llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp (revision c2be702104284cb3facf31124494b9a400296179)
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                                             (Event *) 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", (Event *) 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 bool
1773 ScriptInterpreterPythonImpl::ScriptedThreadPlanGetStopDescription(
1774     StructuredData::ObjectSP implementor_sp, lldb_private::Stream *stream,
1775     bool &script_error) {
1776   StructuredData::Generic *generic = nullptr;
1777   if (implementor_sp)
1778     generic = implementor_sp->GetAsGeneric();
1779   if (!generic) {
1780     script_error = true;
1781     return false;
1782   }
1783   Locker py_lock(this,
1784                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1785   return LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "stop_description",
1786       stream, script_error);
1787 }
1788 
1789 
1790 StructuredData::GenericSP
1791 ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
1792     const char *class_name, const StructuredDataImpl &args_data,
1793     lldb::BreakpointSP &bkpt_sp) {
1794 
1795   if (class_name == nullptr || class_name[0] == '\0')
1796     return StructuredData::GenericSP();
1797 
1798   if (!bkpt_sp.get())
1799     return StructuredData::GenericSP();
1800 
1801   Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
1802   ScriptInterpreterPythonImpl *python_interpreter =
1803       GetPythonInterpreter(debugger);
1804 
1805   if (!python_interpreter)
1806     return StructuredData::GenericSP();
1807 
1808   Locker py_lock(this,
1809                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1810 
1811   PythonObject ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver(
1812       class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
1813       bkpt_sp);
1814 
1815   return StructuredData::GenericSP(
1816       new StructuredPythonObject(std::move(ret_val)));
1817 }
1818 
1819 bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
1820     StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
1821   bool should_continue = false;
1822 
1823   if (implementor_sp) {
1824     Locker py_lock(this,
1825                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1826     should_continue = LLDBSwigPythonCallBreakpointResolver(
1827         implementor_sp->GetValue(), "__callback__", sym_ctx);
1828     if (PyErr_Occurred()) {
1829       PyErr_Print();
1830       PyErr_Clear();
1831     }
1832   }
1833   return should_continue;
1834 }
1835 
1836 lldb::SearchDepth
1837 ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
1838     StructuredData::GenericSP implementor_sp) {
1839   int depth_as_int = lldb::eSearchDepthModule;
1840   if (implementor_sp) {
1841     Locker py_lock(this,
1842                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1843     depth_as_int = LLDBSwigPythonCallBreakpointResolver(
1844         implementor_sp->GetValue(), "__get_depth__", nullptr);
1845     if (PyErr_Occurred()) {
1846       PyErr_Print();
1847       PyErr_Clear();
1848     }
1849   }
1850   if (depth_as_int == lldb::eSearchDepthInvalid)
1851     return lldb::eSearchDepthModule;
1852 
1853   if (depth_as_int <= lldb::kLastSearchDepthKind)
1854     return (lldb::SearchDepth)depth_as_int;
1855   return lldb::eSearchDepthModule;
1856 }
1857 
1858 StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
1859     TargetSP target_sp, const char *class_name,
1860     const StructuredDataImpl &args_data, Status &error) {
1861 
1862   if (!target_sp) {
1863     error.SetErrorString("No target for scripted stop-hook.");
1864     return StructuredData::GenericSP();
1865   }
1866 
1867   if (class_name == nullptr || class_name[0] == '\0') {
1868     error.SetErrorString("No class name for scripted stop-hook.");
1869     return StructuredData::GenericSP();
1870   }
1871 
1872   ScriptInterpreterPythonImpl *python_interpreter =
1873       GetPythonInterpreter(m_debugger);
1874 
1875   if (!python_interpreter) {
1876     error.SetErrorString("No script interpreter for scripted stop-hook.");
1877     return StructuredData::GenericSP();
1878   }
1879 
1880   Locker py_lock(this,
1881                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1882 
1883   PythonObject ret_val = LLDBSwigPythonCreateScriptedStopHook(
1884       target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
1885       args_data, error);
1886 
1887   return StructuredData::GenericSP(
1888       new StructuredPythonObject(std::move(ret_val)));
1889 }
1890 
1891 bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
1892     StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
1893     lldb::StreamSP stream_sp) {
1894   assert(implementor_sp &&
1895          "can't call a stop hook with an invalid implementor");
1896   assert(stream_sp && "can't call a stop hook with an invalid stream");
1897 
1898   Locker py_lock(this,
1899                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1900 
1901   lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
1902 
1903   bool ret_val = LLDBSwigPythonStopHookCallHandleStop(
1904       implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
1905   return ret_val;
1906 }
1907 
1908 StructuredData::ObjectSP
1909 ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
1910                                               lldb_private::Status &error) {
1911   if (!FileSystem::Instance().Exists(file_spec)) {
1912     error.SetErrorString("no such file");
1913     return StructuredData::ObjectSP();
1914   }
1915 
1916   StructuredData::ObjectSP module_sp;
1917 
1918   LoadScriptOptions load_script_options =
1919       LoadScriptOptions().SetInitSession(true).SetSilent(false);
1920   if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1921                           error, &module_sp))
1922     return module_sp;
1923 
1924   return StructuredData::ObjectSP();
1925 }
1926 
1927 StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
1928     StructuredData::ObjectSP plugin_module_sp, Target *target,
1929     const char *setting_name, lldb_private::Status &error) {
1930   if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
1931     return StructuredData::DictionarySP();
1932   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
1933   if (!generic)
1934     return StructuredData::DictionarySP();
1935 
1936   Locker py_lock(this,
1937                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1938   TargetSP target_sp(target->shared_from_this());
1939 
1940   auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting(
1941       generic->GetValue(), setting_name, target_sp);
1942 
1943   if (!setting)
1944     return StructuredData::DictionarySP();
1945 
1946   PythonDictionary py_dict =
1947       unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
1948 
1949   if (!py_dict)
1950     return StructuredData::DictionarySP();
1951 
1952   return py_dict.CreateStructuredDictionary();
1953 }
1954 
1955 StructuredData::ObjectSP
1956 ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
1957     const char *class_name, lldb::ValueObjectSP valobj) {
1958   if (class_name == nullptr || class_name[0] == '\0')
1959     return StructuredData::ObjectSP();
1960 
1961   if (!valobj.get())
1962     return StructuredData::ObjectSP();
1963 
1964   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
1965   Target *target = exe_ctx.GetTargetPtr();
1966 
1967   if (!target)
1968     return StructuredData::ObjectSP();
1969 
1970   Debugger &debugger = target->GetDebugger();
1971   ScriptInterpreterPythonImpl *python_interpreter =
1972       GetPythonInterpreter(debugger);
1973 
1974   if (!python_interpreter)
1975     return StructuredData::ObjectSP();
1976 
1977   Locker py_lock(this,
1978                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1979   PythonObject ret_val = LLDBSwigPythonCreateSyntheticProvider(
1980       class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
1981 
1982   return StructuredData::ObjectSP(
1983       new StructuredPythonObject(std::move(ret_val)));
1984 }
1985 
1986 StructuredData::GenericSP
1987 ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
1988   DebuggerSP debugger_sp(m_debugger.shared_from_this());
1989 
1990   if (class_name == nullptr || class_name[0] == '\0')
1991     return StructuredData::GenericSP();
1992 
1993   if (!debugger_sp.get())
1994     return StructuredData::GenericSP();
1995 
1996   Locker py_lock(this,
1997                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1998   PythonObject ret_val = LLDBSwigPythonCreateCommandObject(
1999       class_name, m_dictionary_name.c_str(), debugger_sp);
2000 
2001   if (ret_val.IsValid())
2002     return StructuredData::GenericSP(
2003         new StructuredPythonObject(std::move(ret_val)));
2004   else
2005     return {};
2006 }
2007 
2008 bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
2009     const char *oneliner, std::string &output, const void *name_token) {
2010   StringList input;
2011   input.SplitIntoLines(oneliner, strlen(oneliner));
2012   return GenerateTypeScriptFunction(input, output, name_token);
2013 }
2014 
2015 bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
2016     const char *oneliner, std::string &output, const void *name_token) {
2017   StringList input;
2018   input.SplitIntoLines(oneliner, strlen(oneliner));
2019   return GenerateTypeSynthClass(input, output, name_token);
2020 }
2021 
2022 Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
2023     StringList &user_input, std::string &output, bool has_extra_args,
2024     bool is_callback) {
2025   static uint32_t num_created_functions = 0;
2026   user_input.RemoveBlankLines();
2027   StreamString sstr;
2028   Status error;
2029   if (user_input.GetSize() == 0) {
2030     error.SetErrorString("No input data.");
2031     return error;
2032   }
2033 
2034   std::string auto_generated_function_name(GenerateUniqueName(
2035       "lldb_autogen_python_bp_callback_func_", num_created_functions));
2036   if (has_extra_args)
2037     sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
2038                 auto_generated_function_name.c_str());
2039   else
2040     sstr.Printf("def %s (frame, bp_loc, internal_dict):",
2041                 auto_generated_function_name.c_str());
2042 
2043   error = GenerateFunction(sstr.GetData(), user_input, is_callback);
2044   if (!error.Success())
2045     return error;
2046 
2047   // Store the name of the auto-generated function to be called.
2048   output.assign(auto_generated_function_name);
2049   return error;
2050 }
2051 
2052 bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
2053     StringList &user_input, std::string &output, bool is_callback) {
2054   static uint32_t num_created_functions = 0;
2055   user_input.RemoveBlankLines();
2056   StreamString sstr;
2057 
2058   if (user_input.GetSize() == 0)
2059     return false;
2060 
2061   std::string auto_generated_function_name(GenerateUniqueName(
2062       "lldb_autogen_python_wp_callback_func_", num_created_functions));
2063   sstr.Printf("def %s (frame, wp, internal_dict):",
2064               auto_generated_function_name.c_str());
2065 
2066   if (!GenerateFunction(sstr.GetData(), user_input, is_callback).Success())
2067     return false;
2068 
2069   // Store the name of the auto-generated function to be called.
2070   output.assign(auto_generated_function_name);
2071   return true;
2072 }
2073 
2074 bool ScriptInterpreterPythonImpl::GetScriptedSummary(
2075     const char *python_function_name, lldb::ValueObjectSP valobj,
2076     StructuredData::ObjectSP &callee_wrapper_sp,
2077     const TypeSummaryOptions &options, std::string &retval) {
2078 
2079   LLDB_SCOPED_TIMER();
2080 
2081   if (!valobj.get()) {
2082     retval.assign("<no object>");
2083     return false;
2084   }
2085 
2086   void *old_callee = nullptr;
2087   StructuredData::Generic *generic = nullptr;
2088   if (callee_wrapper_sp) {
2089     generic = callee_wrapper_sp->GetAsGeneric();
2090     if (generic)
2091       old_callee = generic->GetValue();
2092   }
2093   void *new_callee = old_callee;
2094 
2095   bool ret_val;
2096   if (python_function_name && *python_function_name) {
2097     {
2098       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
2099                                Locker::NoSTDIN);
2100       {
2101         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
2102 
2103         static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
2104         Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
2105         ret_val = LLDBSwigPythonCallTypeScript(
2106             python_function_name, GetSessionDictionary().get(), valobj,
2107             &new_callee, options_sp, retval);
2108       }
2109     }
2110   } else {
2111     retval.assign("<no function name>");
2112     return false;
2113   }
2114 
2115   if (new_callee && old_callee != new_callee) {
2116     Locker py_lock(this,
2117                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2118     callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
2119         PythonObject(PyRefType::Borrowed, static_cast<PyObject *>(new_callee)));
2120   }
2121 
2122   return ret_val;
2123 }
2124 
2125 bool ScriptInterpreterPythonImpl::FormatterCallbackFunction(
2126     const char *python_function_name, TypeImplSP type_impl_sp) {
2127   Locker py_lock(this,
2128                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2129   return LLDBSwigPythonFormatterCallbackFunction(
2130       python_function_name, m_dictionary_name.c_str(), type_impl_sp);
2131 }
2132 
2133 bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
2134     void *baton, StoppointCallbackContext *context, user_id_t break_id,
2135     user_id_t break_loc_id) {
2136   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
2137   const char *python_function_name = bp_option_data->script_source.c_str();
2138 
2139   if (!context)
2140     return true;
2141 
2142   ExecutionContext exe_ctx(context->exe_ctx_ref);
2143   Target *target = exe_ctx.GetTargetPtr();
2144 
2145   if (!target)
2146     return true;
2147 
2148   Debugger &debugger = target->GetDebugger();
2149   ScriptInterpreterPythonImpl *python_interpreter =
2150       GetPythonInterpreter(debugger);
2151 
2152   if (!python_interpreter)
2153     return true;
2154 
2155   if (python_function_name && python_function_name[0]) {
2156     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2157     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2158     if (breakpoint_sp) {
2159       const BreakpointLocationSP bp_loc_sp(
2160           breakpoint_sp->FindLocationByID(break_loc_id));
2161 
2162       if (stop_frame_sp && bp_loc_sp) {
2163         bool ret_val = true;
2164         {
2165           Locker py_lock(python_interpreter, Locker::AcquireLock |
2166                                                  Locker::InitSession |
2167                                                  Locker::NoSTDIN);
2168           Expected<bool> maybe_ret_val =
2169               LLDBSwigPythonBreakpointCallbackFunction(
2170                   python_function_name,
2171                   python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2172                   bp_loc_sp, bp_option_data->m_extra_args);
2173 
2174           if (!maybe_ret_val) {
2175 
2176             llvm::handleAllErrors(
2177                 maybe_ret_val.takeError(),
2178                 [&](PythonException &E) {
2179                   debugger.GetErrorStream() << E.ReadBacktrace();
2180                 },
2181                 [&](const llvm::ErrorInfoBase &E) {
2182                   debugger.GetErrorStream() << E.message();
2183                 });
2184 
2185           } else {
2186             ret_val = maybe_ret_val.get();
2187           }
2188         }
2189         return ret_val;
2190       }
2191     }
2192   }
2193   // We currently always true so we stop in case anything goes wrong when
2194   // trying to call the script function
2195   return true;
2196 }
2197 
2198 bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
2199     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2200   WatchpointOptions::CommandData *wp_option_data =
2201       (WatchpointOptions::CommandData *)baton;
2202   const char *python_function_name = wp_option_data->script_source.c_str();
2203 
2204   if (!context)
2205     return true;
2206 
2207   ExecutionContext exe_ctx(context->exe_ctx_ref);
2208   Target *target = exe_ctx.GetTargetPtr();
2209 
2210   if (!target)
2211     return true;
2212 
2213   Debugger &debugger = target->GetDebugger();
2214   ScriptInterpreterPythonImpl *python_interpreter =
2215       GetPythonInterpreter(debugger);
2216 
2217   if (!python_interpreter)
2218     return true;
2219 
2220   if (python_function_name && python_function_name[0]) {
2221     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2222     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2223     if (wp_sp) {
2224       if (stop_frame_sp && wp_sp) {
2225         bool ret_val = true;
2226         {
2227           Locker py_lock(python_interpreter, Locker::AcquireLock |
2228                                                  Locker::InitSession |
2229                                                  Locker::NoSTDIN);
2230           ret_val = LLDBSwigPythonWatchpointCallbackFunction(
2231               python_function_name,
2232               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2233               wp_sp);
2234         }
2235         return ret_val;
2236       }
2237     }
2238   }
2239   // We currently always true so we stop in case anything goes wrong when
2240   // trying to call the script function
2241   return true;
2242 }
2243 
2244 size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2245     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
2246   if (!implementor_sp)
2247     return 0;
2248   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2249   if (!generic)
2250     return 0;
2251   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2252   if (!implementor)
2253     return 0;
2254 
2255   size_t ret_val = 0;
2256 
2257   {
2258     Locker py_lock(this,
2259                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2260     ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max);
2261   }
2262 
2263   return ret_val;
2264 }
2265 
2266 lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
2267     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
2268   if (!implementor_sp)
2269     return lldb::ValueObjectSP();
2270 
2271   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2272   if (!generic)
2273     return lldb::ValueObjectSP();
2274   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2275   if (!implementor)
2276     return lldb::ValueObjectSP();
2277 
2278   lldb::ValueObjectSP ret_val;
2279   {
2280     Locker py_lock(this,
2281                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2282     PyObject *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx);
2283     if (child_ptr != nullptr && child_ptr != Py_None) {
2284       lldb::SBValue *sb_value_ptr =
2285           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2286       if (sb_value_ptr == nullptr)
2287         Py_XDECREF(child_ptr);
2288       else
2289         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2290     } else {
2291       Py_XDECREF(child_ptr);
2292     }
2293   }
2294 
2295   return ret_val;
2296 }
2297 
2298 int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2299     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
2300   if (!implementor_sp)
2301     return UINT32_MAX;
2302 
2303   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2304   if (!generic)
2305     return UINT32_MAX;
2306   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2307   if (!implementor)
2308     return UINT32_MAX;
2309 
2310   int ret_val = UINT32_MAX;
2311 
2312   {
2313     Locker py_lock(this,
2314                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2315     ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
2316   }
2317 
2318   return ret_val;
2319 }
2320 
2321 bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2322     const StructuredData::ObjectSP &implementor_sp) {
2323   bool ret_val = false;
2324 
2325   if (!implementor_sp)
2326     return ret_val;
2327 
2328   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2329   if (!generic)
2330     return ret_val;
2331   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2332   if (!implementor)
2333     return ret_val;
2334 
2335   {
2336     Locker py_lock(this,
2337                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2338     ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor);
2339   }
2340 
2341   return ret_val;
2342 }
2343 
2344 bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2345     const StructuredData::ObjectSP &implementor_sp) {
2346   bool ret_val = false;
2347 
2348   if (!implementor_sp)
2349     return ret_val;
2350 
2351   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2352   if (!generic)
2353     return ret_val;
2354   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2355   if (!implementor)
2356     return ret_val;
2357 
2358   {
2359     Locker py_lock(this,
2360                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2361     ret_val =
2362         LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor);
2363   }
2364 
2365   return ret_val;
2366 }
2367 
2368 lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
2369     const StructuredData::ObjectSP &implementor_sp) {
2370   lldb::ValueObjectSP ret_val(nullptr);
2371 
2372   if (!implementor_sp)
2373     return ret_val;
2374 
2375   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2376   if (!generic)
2377     return ret_val;
2378   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2379   if (!implementor)
2380     return ret_val;
2381 
2382   {
2383     Locker py_lock(this,
2384                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2385     PyObject *child_ptr =
2386         LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2387     if (child_ptr != nullptr && child_ptr != Py_None) {
2388       lldb::SBValue *sb_value_ptr =
2389           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2390       if (sb_value_ptr == nullptr)
2391         Py_XDECREF(child_ptr);
2392       else
2393         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2394     } else {
2395       Py_XDECREF(child_ptr);
2396     }
2397   }
2398 
2399   return ret_val;
2400 }
2401 
2402 ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2403     const StructuredData::ObjectSP &implementor_sp) {
2404   Locker py_lock(this,
2405                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2406 
2407   if (!implementor_sp)
2408     return {};
2409 
2410   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2411   if (!generic)
2412     return {};
2413 
2414   PythonObject implementor(PyRefType::Borrowed,
2415                            (PyObject *)generic->GetValue());
2416   if (!implementor.IsAllocated())
2417     return {};
2418 
2419   llvm::Expected<PythonObject> expected_py_return =
2420       implementor.CallMethod("get_type_name");
2421 
2422   if (!expected_py_return) {
2423     llvm::consumeError(expected_py_return.takeError());
2424     return {};
2425   }
2426 
2427   PythonObject py_return = std::move(expected_py_return.get());
2428 
2429   ConstString ret_val;
2430   bool got_string = false;
2431   std::string buffer;
2432 
2433   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2434     PythonString py_string(PyRefType::Borrowed, py_return.get());
2435     llvm::StringRef return_data(py_string.GetString());
2436     if (!return_data.empty()) {
2437       buffer.assign(return_data.data(), return_data.size());
2438       got_string = true;
2439     }
2440   }
2441 
2442   if (got_string)
2443     ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
2444 
2445   return ret_val;
2446 }
2447 
2448 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2449     const char *impl_function, Process *process, std::string &output,
2450     Status &error) {
2451   bool ret_val;
2452   if (!process) {
2453     error.SetErrorString("no process");
2454     return false;
2455   }
2456   if (!impl_function || !impl_function[0]) {
2457     error.SetErrorString("no function to execute");
2458     return false;
2459   }
2460 
2461   {
2462     Locker py_lock(this,
2463                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2464     ret_val = LLDBSWIGPythonRunScriptKeywordProcess(
2465         impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
2466         output);
2467     if (!ret_val)
2468       error.SetErrorString("python script evaluation failed");
2469   }
2470   return ret_val;
2471 }
2472 
2473 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2474     const char *impl_function, Thread *thread, std::string &output,
2475     Status &error) {
2476   if (!thread) {
2477     error.SetErrorString("no thread");
2478     return false;
2479   }
2480   if (!impl_function || !impl_function[0]) {
2481     error.SetErrorString("no function to execute");
2482     return false;
2483   }
2484 
2485   Locker py_lock(this,
2486                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2487   if (std::optional<std::string> result = LLDBSWIGPythonRunScriptKeywordThread(
2488           impl_function, m_dictionary_name.c_str(),
2489           thread->shared_from_this())) {
2490     output = std::move(*result);
2491     return true;
2492   }
2493   error.SetErrorString("python script evaluation failed");
2494   return false;
2495 }
2496 
2497 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2498     const char *impl_function, Target *target, std::string &output,
2499     Status &error) {
2500   bool ret_val;
2501   if (!target) {
2502     error.SetErrorString("no thread");
2503     return false;
2504   }
2505   if (!impl_function || !impl_function[0]) {
2506     error.SetErrorString("no function to execute");
2507     return false;
2508   }
2509 
2510   {
2511     TargetSP target_sp(target->shared_from_this());
2512     Locker py_lock(this,
2513                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2514     ret_val = LLDBSWIGPythonRunScriptKeywordTarget(
2515         impl_function, m_dictionary_name.c_str(), target_sp, output);
2516     if (!ret_val)
2517       error.SetErrorString("python script evaluation failed");
2518   }
2519   return ret_val;
2520 }
2521 
2522 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2523     const char *impl_function, StackFrame *frame, std::string &output,
2524     Status &error) {
2525   if (!frame) {
2526     error.SetErrorString("no frame");
2527     return false;
2528   }
2529   if (!impl_function || !impl_function[0]) {
2530     error.SetErrorString("no function to execute");
2531     return false;
2532   }
2533 
2534   Locker py_lock(this,
2535                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2536   if (std::optional<std::string> result = LLDBSWIGPythonRunScriptKeywordFrame(
2537           impl_function, m_dictionary_name.c_str(),
2538           frame->shared_from_this())) {
2539     output = std::move(*result);
2540     return true;
2541   }
2542   error.SetErrorString("python script evaluation failed");
2543   return false;
2544 }
2545 
2546 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2547     const char *impl_function, ValueObject *value, std::string &output,
2548     Status &error) {
2549   bool ret_val;
2550   if (!value) {
2551     error.SetErrorString("no value");
2552     return false;
2553   }
2554   if (!impl_function || !impl_function[0]) {
2555     error.SetErrorString("no function to execute");
2556     return false;
2557   }
2558 
2559   {
2560     Locker py_lock(this,
2561                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2562     ret_val = LLDBSWIGPythonRunScriptKeywordValue(
2563         impl_function, m_dictionary_name.c_str(), value->GetSP(), output);
2564     if (!ret_val)
2565       error.SetErrorString("python script evaluation failed");
2566   }
2567   return ret_val;
2568 }
2569 
2570 uint64_t replace_all(std::string &str, const std::string &oldStr,
2571                      const std::string &newStr) {
2572   size_t pos = 0;
2573   uint64_t matches = 0;
2574   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2575     matches++;
2576     str.replace(pos, oldStr.length(), newStr);
2577     pos += newStr.length();
2578   }
2579   return matches;
2580 }
2581 
2582 bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2583     const char *pathname, const LoadScriptOptions &options,
2584     lldb_private::Status &error, StructuredData::ObjectSP *module_sp,
2585     FileSpec extra_search_dir) {
2586   namespace fs = llvm::sys::fs;
2587   namespace path = llvm::sys::path;
2588 
2589   ExecuteScriptOptions exc_options = ExecuteScriptOptions()
2590                                          .SetEnableIO(!options.GetSilent())
2591                                          .SetSetLLDBGlobals(false);
2592 
2593   if (!pathname || !pathname[0]) {
2594     error.SetErrorString("empty path");
2595     return false;
2596   }
2597 
2598   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2599       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2600           exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2601 
2602   if (!io_redirect_or_error) {
2603     error = io_redirect_or_error.takeError();
2604     return false;
2605   }
2606 
2607   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
2608 
2609   // Before executing Python code, lock the GIL.
2610   Locker py_lock(this,
2611                  Locker::AcquireLock |
2612                      (options.GetInitSession() ? Locker::InitSession : 0) |
2613                      Locker::NoSTDIN,
2614                  Locker::FreeAcquiredLock |
2615                      (options.GetInitSession() ? Locker::TearDownSession : 0),
2616                  io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2617                  io_redirect.GetErrorFile());
2618 
2619   auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2620     if (directory.empty()) {
2621       return llvm::make_error<llvm::StringError>(
2622           "invalid directory name", llvm::inconvertibleErrorCode());
2623     }
2624 
2625     replace_all(directory, "\\", "\\\\");
2626     replace_all(directory, "'", "\\'");
2627 
2628     // Make sure that Python has "directory" in the search path.
2629     StreamString command_stream;
2630     command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
2631                           "sys.path.insert(1,'%s');\n\n",
2632                           directory.c_str(), directory.c_str());
2633     bool syspath_retval =
2634         ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
2635     if (!syspath_retval) {
2636       return llvm::make_error<llvm::StringError>(
2637           "Python sys.path handling failed", llvm::inconvertibleErrorCode());
2638     }
2639 
2640     return llvm::Error::success();
2641   };
2642 
2643   std::string module_name(pathname);
2644   bool possible_package = false;
2645 
2646   if (extra_search_dir) {
2647     if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2648       error = std::move(e);
2649       return false;
2650     }
2651   } else {
2652     FileSpec module_file(pathname);
2653     FileSystem::Instance().Resolve(module_file);
2654 
2655     fs::file_status st;
2656     std::error_code ec = status(module_file.GetPath(), st);
2657 
2658     if (ec || st.type() == fs::file_type::status_error ||
2659         st.type() == fs::file_type::type_unknown ||
2660         st.type() == fs::file_type::file_not_found) {
2661       // if not a valid file of any sort, check if it might be a filename still
2662       // dot can't be used but / and \ can, and if either is found, reject
2663       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2664         error.SetErrorStringWithFormatv("invalid pathname '{0}'", pathname);
2665         return false;
2666       }
2667       // Not a filename, probably a package of some sort, let it go through.
2668       possible_package = true;
2669     } else if (is_directory(st) || is_regular_file(st)) {
2670       if (module_file.GetDirectory().IsEmpty()) {
2671         error.SetErrorStringWithFormatv("invalid directory name '{0}'", pathname);
2672         return false;
2673       }
2674       if (llvm::Error e =
2675               ExtendSysPath(module_file.GetDirectory().GetCString())) {
2676         error = std::move(e);
2677         return false;
2678       }
2679       module_name = module_file.GetFilename().GetCString();
2680     } else {
2681       error.SetErrorString("no known way to import this module specification");
2682       return false;
2683     }
2684   }
2685 
2686   // Strip .py or .pyc extension
2687   llvm::StringRef extension = llvm::sys::path::extension(module_name);
2688   if (!extension.empty()) {
2689     if (extension == ".py")
2690       module_name.resize(module_name.length() - 3);
2691     else if (extension == ".pyc")
2692       module_name.resize(module_name.length() - 4);
2693   }
2694 
2695   if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2696     error.SetErrorStringWithFormat(
2697         "Python does not allow dots in module names: %s", module_name.c_str());
2698     return false;
2699   }
2700 
2701   if (module_name.find('-') != llvm::StringRef::npos) {
2702     error.SetErrorStringWithFormat(
2703         "Python discourages dashes in module names: %s", module_name.c_str());
2704     return false;
2705   }
2706 
2707   // Check if the module is already imported.
2708   StreamString command_stream;
2709   command_stream.Clear();
2710   command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
2711   bool does_contain = false;
2712   // This call will succeed if the module was ever imported in any Debugger in
2713   // the lifetime of the process in which this LLDB framework is living.
2714   const bool does_contain_executed = ExecuteOneLineWithReturn(
2715       command_stream.GetData(),
2716       ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options);
2717 
2718   const bool was_imported_globally = does_contain_executed && does_contain;
2719   const bool was_imported_locally =
2720       GetSessionDictionary()
2721           .GetItemForKey(PythonString(module_name))
2722           .IsAllocated();
2723 
2724   // now actually do the import
2725   command_stream.Clear();
2726 
2727   if (was_imported_globally || was_imported_locally) {
2728     if (!was_imported_locally)
2729       command_stream.Printf("import %s ; reload_module(%s)",
2730                             module_name.c_str(), module_name.c_str());
2731     else
2732       command_stream.Printf("reload_module(%s)", module_name.c_str());
2733   } else
2734     command_stream.Printf("import %s", module_name.c_str());
2735 
2736   error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
2737   if (error.Fail())
2738     return false;
2739 
2740   // if we are here, everything worked
2741   // call __lldb_init_module(debugger,dict)
2742   if (!LLDBSwigPythonCallModuleInit(module_name.c_str(),
2743                                     m_dictionary_name.c_str(),
2744                                     m_debugger.shared_from_this())) {
2745     error.SetErrorString("calling __lldb_init_module failed");
2746     return false;
2747   }
2748 
2749   if (module_sp) {
2750     // everything went just great, now set the module object
2751     command_stream.Clear();
2752     command_stream.Printf("%s", module_name.c_str());
2753     void *module_pyobj = nullptr;
2754     if (ExecuteOneLineWithReturn(
2755             command_stream.GetData(),
2756             ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2757             exc_options) &&
2758         module_pyobj)
2759       *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2760           PyRefType::Owned, static_cast<PyObject *>(module_pyobj)));
2761   }
2762 
2763   return true;
2764 }
2765 
2766 bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
2767   if (!word || !word[0])
2768     return false;
2769 
2770   llvm::StringRef word_sr(word);
2771 
2772   // filter out a few characters that would just confuse us and that are
2773   // clearly not keyword material anyway
2774   if (word_sr.find('"') != llvm::StringRef::npos ||
2775       word_sr.find('\'') != llvm::StringRef::npos)
2776     return false;
2777 
2778   StreamString command_stream;
2779   command_stream.Printf("keyword.iskeyword('%s')", word);
2780   bool result;
2781   ExecuteScriptOptions options;
2782   options.SetEnableIO(false);
2783   options.SetMaskoutErrors(true);
2784   options.SetSetLLDBGlobals(false);
2785   if (ExecuteOneLineWithReturn(command_stream.GetData(),
2786                                ScriptInterpreter::eScriptReturnTypeBool,
2787                                &result, options))
2788     return result;
2789   return false;
2790 }
2791 
2792 ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2793     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2794     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2795       m_old_asynch(debugger_sp->GetAsyncExecution()) {
2796   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2797     m_debugger_sp->SetAsyncExecution(false);
2798   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2799     m_debugger_sp->SetAsyncExecution(true);
2800 }
2801 
2802 ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
2803   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2804     m_debugger_sp->SetAsyncExecution(m_old_asynch);
2805 }
2806 
2807 bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2808     const char *impl_function, llvm::StringRef args,
2809     ScriptedCommandSynchronicity synchronicity,
2810     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2811     const lldb_private::ExecutionContext &exe_ctx) {
2812   if (!impl_function) {
2813     error.SetErrorString("no function to execute");
2814     return false;
2815   }
2816 
2817   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2818   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2819 
2820   if (!debugger_sp.get()) {
2821     error.SetErrorString("invalid Debugger pointer");
2822     return false;
2823   }
2824 
2825   bool ret_val = false;
2826 
2827   std::string err_msg;
2828 
2829   {
2830     Locker py_lock(this,
2831                    Locker::AcquireLock | Locker::InitSession |
2832                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2833                    Locker::FreeLock | Locker::TearDownSession);
2834 
2835     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2836 
2837     std::string args_str = args.str();
2838     ret_val = LLDBSwigPythonCallCommand(
2839         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2840         cmd_retobj, exe_ctx_ref_sp);
2841   }
2842 
2843   if (!ret_val)
2844     error.SetErrorString("unable to execute script function");
2845   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2846     return false;
2847 
2848   error.Clear();
2849   return ret_val;
2850 }
2851 
2852 bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2853     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
2854     ScriptedCommandSynchronicity synchronicity,
2855     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2856     const lldb_private::ExecutionContext &exe_ctx) {
2857   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2858     error.SetErrorString("no function to execute");
2859     return false;
2860   }
2861 
2862   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2863   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2864 
2865   if (!debugger_sp.get()) {
2866     error.SetErrorString("invalid Debugger pointer");
2867     return false;
2868   }
2869 
2870   bool ret_val = false;
2871 
2872   std::string err_msg;
2873 
2874   {
2875     Locker py_lock(this,
2876                    Locker::AcquireLock | Locker::InitSession |
2877                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2878                    Locker::FreeLock | Locker::TearDownSession);
2879 
2880     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2881 
2882     std::string args_str = args.str();
2883     ret_val = LLDBSwigPythonCallCommandObject(
2884         static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
2885         args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
2886   }
2887 
2888   if (!ret_val)
2889     error.SetErrorString("unable to execute script function");
2890   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2891     return false;
2892 
2893   error.Clear();
2894   return ret_val;
2895 }
2896 
2897 /// In Python, a special attribute __doc__ contains the docstring for an object
2898 /// (function, method, class, ...) if any is defined Otherwise, the attribute's
2899 /// value is None.
2900 bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
2901                                                           std::string &dest) {
2902   dest.clear();
2903 
2904   if (!item || !*item)
2905     return false;
2906 
2907   std::string command(item);
2908   command += ".__doc__";
2909 
2910   // Python is going to point this to valid data if ExecuteOneLineWithReturn
2911   // returns successfully.
2912   char *result_ptr = nullptr;
2913 
2914   if (ExecuteOneLineWithReturn(
2915           command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
2916           &result_ptr,
2917           ExecuteScriptOptions().SetEnableIO(false))) {
2918     if (result_ptr)
2919       dest.assign(result_ptr);
2920     return true;
2921   }
2922 
2923   StreamString str_stream;
2924   str_stream << "Function " << item
2925              << " was not found. Containing module might be missing.";
2926   dest = std::string(str_stream.GetString());
2927 
2928   return false;
2929 }
2930 
2931 bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
2932     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2933   dest.clear();
2934 
2935   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2936 
2937   if (!cmd_obj_sp)
2938     return false;
2939 
2940   PythonObject implementor(PyRefType::Borrowed,
2941                            (PyObject *)cmd_obj_sp->GetValue());
2942 
2943   if (!implementor.IsAllocated())
2944     return false;
2945 
2946   llvm::Expected<PythonObject> expected_py_return =
2947       implementor.CallMethod("get_short_help");
2948 
2949   if (!expected_py_return) {
2950     llvm::consumeError(expected_py_return.takeError());
2951     return false;
2952   }
2953 
2954   PythonObject py_return = std::move(expected_py_return.get());
2955 
2956   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2957     PythonString py_string(PyRefType::Borrowed, py_return.get());
2958     llvm::StringRef return_data(py_string.GetString());
2959     dest.assign(return_data.data(), return_data.size());
2960     return true;
2961   }
2962 
2963   return false;
2964 }
2965 
2966 uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
2967     StructuredData::GenericSP cmd_obj_sp) {
2968   uint32_t result = 0;
2969 
2970   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2971 
2972   static char callee_name[] = "get_flags";
2973 
2974   if (!cmd_obj_sp)
2975     return result;
2976 
2977   PythonObject implementor(PyRefType::Borrowed,
2978                            (PyObject *)cmd_obj_sp->GetValue());
2979 
2980   if (!implementor.IsAllocated())
2981     return result;
2982 
2983   PythonObject pmeth(PyRefType::Owned,
2984                      PyObject_GetAttrString(implementor.get(), callee_name));
2985 
2986   if (PyErr_Occurred())
2987     PyErr_Clear();
2988 
2989   if (!pmeth.IsAllocated())
2990     return result;
2991 
2992   if (PyCallable_Check(pmeth.get()) == 0) {
2993     if (PyErr_Occurred())
2994       PyErr_Clear();
2995     return result;
2996   }
2997 
2998   if (PyErr_Occurred())
2999     PyErr_Clear();
3000 
3001   long long py_return = unwrapOrSetPythonException(
3002       As<long long>(implementor.CallMethod(callee_name)));
3003 
3004   // if it fails, print the error but otherwise go on
3005   if (PyErr_Occurred()) {
3006     PyErr_Print();
3007     PyErr_Clear();
3008   } else {
3009     result = py_return;
3010   }
3011 
3012   return result;
3013 }
3014 
3015 bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3016     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
3017   dest.clear();
3018 
3019   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3020 
3021   if (!cmd_obj_sp)
3022     return false;
3023 
3024   PythonObject implementor(PyRefType::Borrowed,
3025                            (PyObject *)cmd_obj_sp->GetValue());
3026 
3027   if (!implementor.IsAllocated())
3028     return false;
3029 
3030   llvm::Expected<PythonObject> expected_py_return =
3031       implementor.CallMethod("get_long_help");
3032 
3033   if (!expected_py_return) {
3034     llvm::consumeError(expected_py_return.takeError());
3035     return false;
3036   }
3037 
3038   PythonObject py_return = std::move(expected_py_return.get());
3039 
3040   bool got_string = false;
3041   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3042     PythonString str(PyRefType::Borrowed, py_return.get());
3043     llvm::StringRef str_data(str.GetString());
3044     dest.assign(str_data.data(), str_data.size());
3045     got_string = true;
3046   }
3047 
3048   return got_string;
3049 }
3050 
3051 std::unique_ptr<ScriptInterpreterLocker>
3052 ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3053   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3054       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3055       Locker::FreeLock | Locker::TearDownSession));
3056   return py_lock;
3057 }
3058 
3059 void ScriptInterpreterPythonImpl::Initialize() {
3060   LLDB_SCOPED_TIMER();
3061 
3062   // RAII-based initialization which correctly handles multiple-initialization,
3063   // version- specific differences among Python 2 and Python 3, and saving and
3064   // restoring various other pieces of state that can get mucked with during
3065   // initialization.
3066   InitializePythonRAII initialize_guard;
3067 
3068   LLDBSwigPyInit();
3069 
3070   // Update the path python uses to search for modules to include the current
3071   // directory.
3072 
3073   PyRun_SimpleString("import sys");
3074   AddToSysPath(AddLocation::End, ".");
3075 
3076   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
3077   // that use a backslash as the path separator, this will result in executing
3078   // python code containing paths with unescaped backslashes.  But Python also
3079   // accepts forward slashes, so to make life easier we just use that.
3080   if (FileSpec file_spec = GetPythonDir())
3081     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3082   if (FileSpec file_spec = HostInfo::GetShlibDir())
3083     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3084 
3085   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3086                      "lldb.embedded_interpreter; from "
3087                      "lldb.embedded_interpreter import run_python_interpreter; "
3088                      "from lldb.embedded_interpreter import run_one_line");
3089 
3090 #if LLDB_USE_PYTHON_SET_INTERRUPT
3091   // Python will not just overwrite its internal SIGINT handler but also the
3092   // one from the process. Backup the current SIGINT handler to prevent that
3093   // Python deletes it.
3094   RestoreSignalHandlerScope save_sigint(SIGINT);
3095 
3096   // Setup a default SIGINT signal handler that works the same way as the
3097   // normal Python REPL signal handler which raises a KeyboardInterrupt.
3098   // Also make sure to not pollute the user's REPL with the signal module nor
3099   // our utility function.
3100   PyRun_SimpleString("def lldb_setup_sigint_handler():\n"
3101                      "  import signal;\n"
3102                      "  def signal_handler(sig, frame):\n"
3103                      "    raise KeyboardInterrupt()\n"
3104                      "  signal.signal(signal.SIGINT, signal_handler);\n"
3105                      "lldb_setup_sigint_handler();\n"
3106                      "del lldb_setup_sigint_handler\n");
3107 #endif
3108 }
3109 
3110 void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3111                                                std::string path) {
3112   std::string path_copy;
3113 
3114   std::string statement;
3115   if (location == AddLocation::Beginning) {
3116     statement.assign("sys.path.insert(0,\"");
3117     statement.append(path);
3118     statement.append("\")");
3119   } else {
3120     statement.assign("sys.path.append(\"");
3121     statement.append(path);
3122     statement.append("\")");
3123   }
3124   PyRun_SimpleString(statement.c_str());
3125 }
3126 
3127 // We are intentionally NOT calling Py_Finalize here (this would be the logical
3128 // place to call it).  Calling Py_Finalize here causes test suite runs to seg
3129 // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
3130 // be called 'at_exit'.  When the test suite Python harness finishes up, it
3131 // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3132 // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3133 // which calls ScriptInterpreter::Terminate, which calls
3134 // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
3135 // end up with Py_Finalize being called from within Py_Finalize, which results
3136 // in a seg fault. Since this function only gets called when lldb is shutting
3137 // down and going away anyway, the fact that we don't actually call Py_Finalize
3138 // should not cause any problems (everything should shut down/go away anyway
3139 // when the process exits).
3140 //
3141 // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3142 
3143 #endif
3144