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