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