xref: /llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp (revision d76566417e592cfac9c710f82575473b1b4a9285)
1 //===-- ScriptInterpreterPython.cpp ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Host/Config.h"
10 #include "lldb/lldb-enumerations.h"
11 
12 #if LLDB_ENABLE_PYTHON
13 
14 // LLDB Python header must be included first
15 #include "lldb-python.h"
16 
17 #include "PythonDataObjects.h"
18 #include "PythonReadline.h"
19 #include "SWIGPythonBridge.h"
20 #include "ScriptInterpreterPythonImpl.h"
21 #include "ScriptedProcessPythonInterface.h"
22 
23 #include "lldb/API/SBError.h"
24 #include "lldb/API/SBFrame.h"
25 #include "lldb/API/SBValue.h"
26 #include "lldb/Breakpoint/StoppointCallbackContext.h"
27 #include "lldb/Breakpoint/WatchpointOptions.h"
28 #include "lldb/Core/Debugger.h"
29 #include "lldb/Core/PluginManager.h"
30 #include "lldb/Core/ThreadedCommunication.h"
31 #include "lldb/Core/ValueObject.h"
32 #include "lldb/DataFormatters/TypeSummary.h"
33 #include "lldb/Host/FileSystem.h"
34 #include "lldb/Host/HostInfo.h"
35 #include "lldb/Host/Pipe.h"
36 #include "lldb/Interpreter/CommandInterpreter.h"
37 #include "lldb/Interpreter/CommandReturnObject.h"
38 #include "lldb/Target/Thread.h"
39 #include "lldb/Target/ThreadPlan.h"
40 #include "lldb/Utility/Instrumentation.h"
41 #include "lldb/Utility/LLDBLog.h"
42 #include "lldb/Utility/Timer.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/StringRef.h"
45 #include "llvm/Support/Error.h"
46 #include "llvm/Support/FileSystem.h"
47 #include "llvm/Support/FormatAdapters.h"
48 
49 #include <cstdio>
50 #include <cstdlib>
51 #include <memory>
52 #include <mutex>
53 #include <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 != nullptr; 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::FormatterCallbackFunction(
2158     const char *python_function_name, TypeImplSP type_impl_sp) {
2159   Locker py_lock(this,
2160                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2161   return LLDBSwigPythonFormatterCallbackFunction(
2162       python_function_name, m_dictionary_name.c_str(), type_impl_sp);
2163 }
2164 
2165 bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
2166     void *baton, StoppointCallbackContext *context, user_id_t break_id,
2167     user_id_t break_loc_id) {
2168   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
2169   const char *python_function_name = bp_option_data->script_source.c_str();
2170 
2171   if (!context)
2172     return true;
2173 
2174   ExecutionContext exe_ctx(context->exe_ctx_ref);
2175   Target *target = exe_ctx.GetTargetPtr();
2176 
2177   if (!target)
2178     return true;
2179 
2180   Debugger &debugger = target->GetDebugger();
2181   ScriptInterpreterPythonImpl *python_interpreter =
2182       GetPythonInterpreter(debugger);
2183 
2184   if (!python_interpreter)
2185     return true;
2186 
2187   if (python_function_name && python_function_name[0]) {
2188     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2189     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2190     if (breakpoint_sp) {
2191       const BreakpointLocationSP bp_loc_sp(
2192           breakpoint_sp->FindLocationByID(break_loc_id));
2193 
2194       if (stop_frame_sp && bp_loc_sp) {
2195         bool ret_val = true;
2196         {
2197           Locker py_lock(python_interpreter, Locker::AcquireLock |
2198                                                  Locker::InitSession |
2199                                                  Locker::NoSTDIN);
2200           Expected<bool> maybe_ret_val =
2201               LLDBSwigPythonBreakpointCallbackFunction(
2202                   python_function_name,
2203                   python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2204                   bp_loc_sp, bp_option_data->m_extra_args);
2205 
2206           if (!maybe_ret_val) {
2207 
2208             llvm::handleAllErrors(
2209                 maybe_ret_val.takeError(),
2210                 [&](PythonException &E) {
2211                   debugger.GetErrorStream() << E.ReadBacktrace();
2212                 },
2213                 [&](const llvm::ErrorInfoBase &E) {
2214                   debugger.GetErrorStream() << E.message();
2215                 });
2216 
2217           } else {
2218             ret_val = maybe_ret_val.get();
2219           }
2220         }
2221         return ret_val;
2222       }
2223     }
2224   }
2225   // We currently always true so we stop in case anything goes wrong when
2226   // trying to call the script function
2227   return true;
2228 }
2229 
2230 bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
2231     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2232   WatchpointOptions::CommandData *wp_option_data =
2233       (WatchpointOptions::CommandData *)baton;
2234   const char *python_function_name = wp_option_data->script_source.c_str();
2235 
2236   if (!context)
2237     return true;
2238 
2239   ExecutionContext exe_ctx(context->exe_ctx_ref);
2240   Target *target = exe_ctx.GetTargetPtr();
2241 
2242   if (!target)
2243     return true;
2244 
2245   Debugger &debugger = target->GetDebugger();
2246   ScriptInterpreterPythonImpl *python_interpreter =
2247       GetPythonInterpreter(debugger);
2248 
2249   if (!python_interpreter)
2250     return true;
2251 
2252   if (python_function_name && python_function_name[0]) {
2253     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2254     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2255     if (wp_sp) {
2256       if (stop_frame_sp && wp_sp) {
2257         bool ret_val = true;
2258         {
2259           Locker py_lock(python_interpreter, Locker::AcquireLock |
2260                                                  Locker::InitSession |
2261                                                  Locker::NoSTDIN);
2262           ret_val = LLDBSwigPythonWatchpointCallbackFunction(
2263               python_function_name,
2264               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2265               wp_sp);
2266         }
2267         return ret_val;
2268       }
2269     }
2270   }
2271   // We currently always true so we stop in case anything goes wrong when
2272   // trying to call the script function
2273   return true;
2274 }
2275 
2276 size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2277     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
2278   if (!implementor_sp)
2279     return 0;
2280   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2281   if (!generic)
2282     return 0;
2283   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2284   if (!implementor)
2285     return 0;
2286 
2287   size_t ret_val = 0;
2288 
2289   {
2290     Locker py_lock(this,
2291                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2292     ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max);
2293   }
2294 
2295   return ret_val;
2296 }
2297 
2298 lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
2299     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
2300   if (!implementor_sp)
2301     return lldb::ValueObjectSP();
2302 
2303   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2304   if (!generic)
2305     return lldb::ValueObjectSP();
2306   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2307   if (!implementor)
2308     return lldb::ValueObjectSP();
2309 
2310   lldb::ValueObjectSP ret_val;
2311   {
2312     Locker py_lock(this,
2313                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2314     PyObject *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx);
2315     if (child_ptr != nullptr && child_ptr != Py_None) {
2316       lldb::SBValue *sb_value_ptr =
2317           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2318       if (sb_value_ptr == nullptr)
2319         Py_XDECREF(child_ptr);
2320       else
2321         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2322     } else {
2323       Py_XDECREF(child_ptr);
2324     }
2325   }
2326 
2327   return ret_val;
2328 }
2329 
2330 int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2331     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
2332   if (!implementor_sp)
2333     return UINT32_MAX;
2334 
2335   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2336   if (!generic)
2337     return UINT32_MAX;
2338   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2339   if (!implementor)
2340     return UINT32_MAX;
2341 
2342   int ret_val = UINT32_MAX;
2343 
2344   {
2345     Locker py_lock(this,
2346                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2347     ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
2348   }
2349 
2350   return ret_val;
2351 }
2352 
2353 bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2354     const StructuredData::ObjectSP &implementor_sp) {
2355   bool ret_val = false;
2356 
2357   if (!implementor_sp)
2358     return ret_val;
2359 
2360   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2361   if (!generic)
2362     return ret_val;
2363   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2364   if (!implementor)
2365     return ret_val;
2366 
2367   {
2368     Locker py_lock(this,
2369                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2370     ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor);
2371   }
2372 
2373   return ret_val;
2374 }
2375 
2376 bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2377     const StructuredData::ObjectSP &implementor_sp) {
2378   bool ret_val = false;
2379 
2380   if (!implementor_sp)
2381     return ret_val;
2382 
2383   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2384   if (!generic)
2385     return ret_val;
2386   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2387   if (!implementor)
2388     return ret_val;
2389 
2390   {
2391     Locker py_lock(this,
2392                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2393     ret_val =
2394         LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor);
2395   }
2396 
2397   return ret_val;
2398 }
2399 
2400 lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
2401     const StructuredData::ObjectSP &implementor_sp) {
2402   lldb::ValueObjectSP ret_val(nullptr);
2403 
2404   if (!implementor_sp)
2405     return ret_val;
2406 
2407   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2408   if (!generic)
2409     return ret_val;
2410   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2411   if (!implementor)
2412     return ret_val;
2413 
2414   {
2415     Locker py_lock(this,
2416                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2417     PyObject *child_ptr =
2418         LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2419     if (child_ptr != nullptr && child_ptr != Py_None) {
2420       lldb::SBValue *sb_value_ptr =
2421           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2422       if (sb_value_ptr == nullptr)
2423         Py_XDECREF(child_ptr);
2424       else
2425         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2426     } else {
2427       Py_XDECREF(child_ptr);
2428     }
2429   }
2430 
2431   return ret_val;
2432 }
2433 
2434 ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2435     const StructuredData::ObjectSP &implementor_sp) {
2436   Locker py_lock(this,
2437                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2438 
2439   static char callee_name[] = "get_type_name";
2440 
2441   ConstString ret_val;
2442   bool got_string = false;
2443   std::string buffer;
2444 
2445   if (!implementor_sp)
2446     return ret_val;
2447 
2448   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2449   if (!generic)
2450     return ret_val;
2451   PythonObject implementor(PyRefType::Borrowed,
2452                            (PyObject *)generic->GetValue());
2453   if (!implementor.IsAllocated())
2454     return ret_val;
2455 
2456   PythonObject pmeth(PyRefType::Owned,
2457                      PyObject_GetAttrString(implementor.get(), callee_name));
2458 
2459   if (PyErr_Occurred())
2460     PyErr_Clear();
2461 
2462   if (!pmeth.IsAllocated())
2463     return ret_val;
2464 
2465   if (PyCallable_Check(pmeth.get()) == 0) {
2466     if (PyErr_Occurred())
2467       PyErr_Clear();
2468     return ret_val;
2469   }
2470 
2471   if (PyErr_Occurred())
2472     PyErr_Clear();
2473 
2474   // right now we know this function exists and is callable..
2475   PythonObject py_return(
2476       PyRefType::Owned,
2477       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
2478 
2479   // if it fails, print the error but otherwise go on
2480   if (PyErr_Occurred()) {
2481     PyErr_Print();
2482     PyErr_Clear();
2483   }
2484 
2485   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2486     PythonString py_string(PyRefType::Borrowed, py_return.get());
2487     llvm::StringRef return_data(py_string.GetString());
2488     if (!return_data.empty()) {
2489       buffer.assign(return_data.data(), return_data.size());
2490       got_string = true;
2491     }
2492   }
2493 
2494   if (got_string)
2495     ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
2496 
2497   return ret_val;
2498 }
2499 
2500 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2501     const char *impl_function, Process *process, std::string &output,
2502     Status &error) {
2503   bool ret_val;
2504   if (!process) {
2505     error.SetErrorString("no process");
2506     return false;
2507   }
2508   if (!impl_function || !impl_function[0]) {
2509     error.SetErrorString("no function to execute");
2510     return false;
2511   }
2512 
2513   {
2514     Locker py_lock(this,
2515                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2516     ret_val = LLDBSWIGPythonRunScriptKeywordProcess(
2517         impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
2518         output);
2519     if (!ret_val)
2520       error.SetErrorString("python script evaluation failed");
2521   }
2522   return ret_val;
2523 }
2524 
2525 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2526     const char *impl_function, Thread *thread, std::string &output,
2527     Status &error) {
2528   if (!thread) {
2529     error.SetErrorString("no thread");
2530     return false;
2531   }
2532   if (!impl_function || !impl_function[0]) {
2533     error.SetErrorString("no function to execute");
2534     return false;
2535   }
2536 
2537   Locker py_lock(this,
2538                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2539   if (llvm::Optional<std::string> result = LLDBSWIGPythonRunScriptKeywordThread(
2540           impl_function, m_dictionary_name.c_str(),
2541           thread->shared_from_this())) {
2542     output = std::move(*result);
2543     return true;
2544   }
2545   error.SetErrorString("python script evaluation failed");
2546   return false;
2547 }
2548 
2549 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2550     const char *impl_function, Target *target, std::string &output,
2551     Status &error) {
2552   bool ret_val;
2553   if (!target) {
2554     error.SetErrorString("no thread");
2555     return false;
2556   }
2557   if (!impl_function || !impl_function[0]) {
2558     error.SetErrorString("no function to execute");
2559     return false;
2560   }
2561 
2562   {
2563     TargetSP target_sp(target->shared_from_this());
2564     Locker py_lock(this,
2565                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2566     ret_val = LLDBSWIGPythonRunScriptKeywordTarget(
2567         impl_function, m_dictionary_name.c_str(), target_sp, output);
2568     if (!ret_val)
2569       error.SetErrorString("python script evaluation failed");
2570   }
2571   return ret_val;
2572 }
2573 
2574 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2575     const char *impl_function, StackFrame *frame, std::string &output,
2576     Status &error) {
2577   if (!frame) {
2578     error.SetErrorString("no frame");
2579     return false;
2580   }
2581   if (!impl_function || !impl_function[0]) {
2582     error.SetErrorString("no function to execute");
2583     return false;
2584   }
2585 
2586   Locker py_lock(this,
2587                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2588   if (llvm::Optional<std::string> result = LLDBSWIGPythonRunScriptKeywordFrame(
2589           impl_function, m_dictionary_name.c_str(),
2590           frame->shared_from_this())) {
2591     output = std::move(*result);
2592     return true;
2593   }
2594   error.SetErrorString("python script evaluation failed");
2595   return false;
2596 }
2597 
2598 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2599     const char *impl_function, ValueObject *value, std::string &output,
2600     Status &error) {
2601   bool ret_val;
2602   if (!value) {
2603     error.SetErrorString("no value");
2604     return false;
2605   }
2606   if (!impl_function || !impl_function[0]) {
2607     error.SetErrorString("no function to execute");
2608     return false;
2609   }
2610 
2611   {
2612     Locker py_lock(this,
2613                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2614     ret_val = LLDBSWIGPythonRunScriptKeywordValue(
2615         impl_function, m_dictionary_name.c_str(), value->GetSP(), output);
2616     if (!ret_val)
2617       error.SetErrorString("python script evaluation failed");
2618   }
2619   return ret_val;
2620 }
2621 
2622 uint64_t replace_all(std::string &str, const std::string &oldStr,
2623                      const std::string &newStr) {
2624   size_t pos = 0;
2625   uint64_t matches = 0;
2626   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2627     matches++;
2628     str.replace(pos, oldStr.length(), newStr);
2629     pos += newStr.length();
2630   }
2631   return matches;
2632 }
2633 
2634 bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2635     const char *pathname, const LoadScriptOptions &options,
2636     lldb_private::Status &error, StructuredData::ObjectSP *module_sp,
2637     FileSpec extra_search_dir) {
2638   namespace fs = llvm::sys::fs;
2639   namespace path = llvm::sys::path;
2640 
2641   ExecuteScriptOptions exc_options = ExecuteScriptOptions()
2642                                          .SetEnableIO(!options.GetSilent())
2643                                          .SetSetLLDBGlobals(false);
2644 
2645   if (!pathname || !pathname[0]) {
2646     error.SetErrorString("empty path");
2647     return false;
2648   }
2649 
2650   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2651       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2652           exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2653 
2654   if (!io_redirect_or_error) {
2655     error = io_redirect_or_error.takeError();
2656     return false;
2657   }
2658 
2659   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
2660 
2661   // Before executing Python code, lock the GIL.
2662   Locker py_lock(this,
2663                  Locker::AcquireLock |
2664                      (options.GetInitSession() ? Locker::InitSession : 0) |
2665                      Locker::NoSTDIN,
2666                  Locker::FreeAcquiredLock |
2667                      (options.GetInitSession() ? Locker::TearDownSession : 0),
2668                  io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2669                  io_redirect.GetErrorFile());
2670 
2671   auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2672     if (directory.empty()) {
2673       return llvm::make_error<llvm::StringError>(
2674           "invalid directory name", llvm::inconvertibleErrorCode());
2675     }
2676 
2677     replace_all(directory, "\\", "\\\\");
2678     replace_all(directory, "'", "\\'");
2679 
2680     // Make sure that Python has "directory" in the search path.
2681     StreamString command_stream;
2682     command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
2683                           "sys.path.insert(1,'%s');\n\n",
2684                           directory.c_str(), directory.c_str());
2685     bool syspath_retval =
2686         ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
2687     if (!syspath_retval) {
2688       return llvm::make_error<llvm::StringError>(
2689           "Python sys.path handling failed", llvm::inconvertibleErrorCode());
2690     }
2691 
2692     return llvm::Error::success();
2693   };
2694 
2695   std::string module_name(pathname);
2696   bool possible_package = false;
2697 
2698   if (extra_search_dir) {
2699     if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2700       error = std::move(e);
2701       return false;
2702     }
2703   } else {
2704     FileSpec module_file(pathname);
2705     FileSystem::Instance().Resolve(module_file);
2706 
2707     fs::file_status st;
2708     std::error_code ec = status(module_file.GetPath(), st);
2709 
2710     if (ec || st.type() == fs::file_type::status_error ||
2711         st.type() == fs::file_type::type_unknown ||
2712         st.type() == fs::file_type::file_not_found) {
2713       // if not a valid file of any sort, check if it might be a filename still
2714       // dot can't be used but / and \ can, and if either is found, reject
2715       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2716         error.SetErrorStringWithFormatv("invalid pathname '{0}'", pathname);
2717         return false;
2718       }
2719       // Not a filename, probably a package of some sort, let it go through.
2720       possible_package = true;
2721     } else if (is_directory(st) || is_regular_file(st)) {
2722       if (module_file.GetDirectory().IsEmpty()) {
2723         error.SetErrorStringWithFormatv("invalid directory name '{0}'", pathname);
2724         return false;
2725       }
2726       if (llvm::Error e =
2727               ExtendSysPath(module_file.GetDirectory().GetCString())) {
2728         error = std::move(e);
2729         return false;
2730       }
2731       module_name = module_file.GetFilename().GetCString();
2732     } else {
2733       error.SetErrorString("no known way to import this module specification");
2734       return false;
2735     }
2736   }
2737 
2738   // Strip .py or .pyc extension
2739   llvm::StringRef extension = llvm::sys::path::extension(module_name);
2740   if (!extension.empty()) {
2741     if (extension == ".py")
2742       module_name.resize(module_name.length() - 3);
2743     else if (extension == ".pyc")
2744       module_name.resize(module_name.length() - 4);
2745   }
2746 
2747   if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2748     error.SetErrorStringWithFormat(
2749         "Python does not allow dots in module names: %s", module_name.c_str());
2750     return false;
2751   }
2752 
2753   if (module_name.find('-') != llvm::StringRef::npos) {
2754     error.SetErrorStringWithFormat(
2755         "Python discourages dashes in module names: %s", module_name.c_str());
2756     return false;
2757   }
2758 
2759   // Check if the module is already imported.
2760   StreamString command_stream;
2761   command_stream.Clear();
2762   command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
2763   bool does_contain = false;
2764   // This call will succeed if the module was ever imported in any Debugger in
2765   // the lifetime of the process in which this LLDB framework is living.
2766   const bool does_contain_executed = ExecuteOneLineWithReturn(
2767       command_stream.GetData(),
2768       ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options);
2769 
2770   const bool was_imported_globally = does_contain_executed && does_contain;
2771   const bool was_imported_locally =
2772       GetSessionDictionary()
2773           .GetItemForKey(PythonString(module_name))
2774           .IsAllocated();
2775 
2776   // now actually do the import
2777   command_stream.Clear();
2778 
2779   if (was_imported_globally || was_imported_locally) {
2780     if (!was_imported_locally)
2781       command_stream.Printf("import %s ; reload_module(%s)",
2782                             module_name.c_str(), module_name.c_str());
2783     else
2784       command_stream.Printf("reload_module(%s)", module_name.c_str());
2785   } else
2786     command_stream.Printf("import %s", module_name.c_str());
2787 
2788   error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
2789   if (error.Fail())
2790     return false;
2791 
2792   // if we are here, everything worked
2793   // call __lldb_init_module(debugger,dict)
2794   if (!LLDBSwigPythonCallModuleInit(module_name.c_str(),
2795                                     m_dictionary_name.c_str(),
2796                                     m_debugger.shared_from_this())) {
2797     error.SetErrorString("calling __lldb_init_module failed");
2798     return false;
2799   }
2800 
2801   if (module_sp) {
2802     // everything went just great, now set the module object
2803     command_stream.Clear();
2804     command_stream.Printf("%s", module_name.c_str());
2805     void *module_pyobj = nullptr;
2806     if (ExecuteOneLineWithReturn(
2807             command_stream.GetData(),
2808             ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2809             exc_options) &&
2810         module_pyobj)
2811       *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2812           PyRefType::Owned, static_cast<PyObject *>(module_pyobj)));
2813   }
2814 
2815   return true;
2816 }
2817 
2818 bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
2819   if (!word || !word[0])
2820     return false;
2821 
2822   llvm::StringRef word_sr(word);
2823 
2824   // filter out a few characters that would just confuse us and that are
2825   // clearly not keyword material anyway
2826   if (word_sr.find('"') != llvm::StringRef::npos ||
2827       word_sr.find('\'') != llvm::StringRef::npos)
2828     return false;
2829 
2830   StreamString command_stream;
2831   command_stream.Printf("keyword.iskeyword('%s')", word);
2832   bool result;
2833   ExecuteScriptOptions options;
2834   options.SetEnableIO(false);
2835   options.SetMaskoutErrors(true);
2836   options.SetSetLLDBGlobals(false);
2837   if (ExecuteOneLineWithReturn(command_stream.GetData(),
2838                                ScriptInterpreter::eScriptReturnTypeBool,
2839                                &result, options))
2840     return result;
2841   return false;
2842 }
2843 
2844 ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2845     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2846     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2847       m_old_asynch(debugger_sp->GetAsyncExecution()) {
2848   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2849     m_debugger_sp->SetAsyncExecution(false);
2850   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2851     m_debugger_sp->SetAsyncExecution(true);
2852 }
2853 
2854 ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
2855   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2856     m_debugger_sp->SetAsyncExecution(m_old_asynch);
2857 }
2858 
2859 bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2860     const char *impl_function, llvm::StringRef args,
2861     ScriptedCommandSynchronicity synchronicity,
2862     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2863     const lldb_private::ExecutionContext &exe_ctx) {
2864   if (!impl_function) {
2865     error.SetErrorString("no function to execute");
2866     return false;
2867   }
2868 
2869   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2870   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2871 
2872   if (!debugger_sp.get()) {
2873     error.SetErrorString("invalid Debugger pointer");
2874     return false;
2875   }
2876 
2877   bool ret_val = false;
2878 
2879   std::string err_msg;
2880 
2881   {
2882     Locker py_lock(this,
2883                    Locker::AcquireLock | Locker::InitSession |
2884                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2885                    Locker::FreeLock | Locker::TearDownSession);
2886 
2887     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2888 
2889     std::string args_str = args.str();
2890     ret_val = LLDBSwigPythonCallCommand(
2891         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2892         cmd_retobj, exe_ctx_ref_sp);
2893   }
2894 
2895   if (!ret_val)
2896     error.SetErrorString("unable to execute script function");
2897   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2898     return false;
2899 
2900   error.Clear();
2901   return ret_val;
2902 }
2903 
2904 bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2905     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
2906     ScriptedCommandSynchronicity synchronicity,
2907     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2908     const lldb_private::ExecutionContext &exe_ctx) {
2909   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2910     error.SetErrorString("no function to execute");
2911     return false;
2912   }
2913 
2914   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2915   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2916 
2917   if (!debugger_sp.get()) {
2918     error.SetErrorString("invalid Debugger pointer");
2919     return false;
2920   }
2921 
2922   bool ret_val = false;
2923 
2924   std::string err_msg;
2925 
2926   {
2927     Locker py_lock(this,
2928                    Locker::AcquireLock | Locker::InitSession |
2929                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2930                    Locker::FreeLock | Locker::TearDownSession);
2931 
2932     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2933 
2934     std::string args_str = args.str();
2935     ret_val = LLDBSwigPythonCallCommandObject(
2936         static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
2937         args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
2938   }
2939 
2940   if (!ret_val)
2941     error.SetErrorString("unable to execute script function");
2942   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2943     return false;
2944 
2945   error.Clear();
2946   return ret_val;
2947 }
2948 
2949 /// In Python, a special attribute __doc__ contains the docstring for an object
2950 /// (function, method, class, ...) if any is defined Otherwise, the attribute's
2951 /// value is None.
2952 bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
2953                                                           std::string &dest) {
2954   dest.clear();
2955 
2956   if (!item || !*item)
2957     return false;
2958 
2959   std::string command(item);
2960   command += ".__doc__";
2961 
2962   // Python is going to point this to valid data if ExecuteOneLineWithReturn
2963   // returns successfully.
2964   char *result_ptr = nullptr;
2965 
2966   if (ExecuteOneLineWithReturn(
2967           command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
2968           &result_ptr,
2969           ExecuteScriptOptions().SetEnableIO(false))) {
2970     if (result_ptr)
2971       dest.assign(result_ptr);
2972     return true;
2973   }
2974 
2975   StreamString str_stream;
2976   str_stream << "Function " << item
2977              << " was not found. Containing module might be missing.";
2978   dest = std::string(str_stream.GetString());
2979 
2980   return false;
2981 }
2982 
2983 bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
2984     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2985   dest.clear();
2986 
2987   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2988 
2989   static char callee_name[] = "get_short_help";
2990 
2991   if (!cmd_obj_sp)
2992     return false;
2993 
2994   PythonObject implementor(PyRefType::Borrowed,
2995                            (PyObject *)cmd_obj_sp->GetValue());
2996 
2997   if (!implementor.IsAllocated())
2998     return false;
2999 
3000   PythonObject pmeth(PyRefType::Owned,
3001                      PyObject_GetAttrString(implementor.get(), callee_name));
3002 
3003   if (PyErr_Occurred())
3004     PyErr_Clear();
3005 
3006   if (!pmeth.IsAllocated())
3007     return false;
3008 
3009   if (PyCallable_Check(pmeth.get()) == 0) {
3010     if (PyErr_Occurred())
3011       PyErr_Clear();
3012     return false;
3013   }
3014 
3015   if (PyErr_Occurred())
3016     PyErr_Clear();
3017 
3018   // Right now we know this function exists and is callable.
3019   PythonObject py_return(
3020       PyRefType::Owned,
3021       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3022 
3023   // If it fails, print the error but otherwise go on.
3024   if (PyErr_Occurred()) {
3025     PyErr_Print();
3026     PyErr_Clear();
3027   }
3028 
3029   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3030     PythonString py_string(PyRefType::Borrowed, py_return.get());
3031     llvm::StringRef return_data(py_string.GetString());
3032     dest.assign(return_data.data(), return_data.size());
3033     return true;
3034   }
3035 
3036   return false;
3037 }
3038 
3039 uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
3040     StructuredData::GenericSP cmd_obj_sp) {
3041   uint32_t result = 0;
3042 
3043   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3044 
3045   static char callee_name[] = "get_flags";
3046 
3047   if (!cmd_obj_sp)
3048     return result;
3049 
3050   PythonObject implementor(PyRefType::Borrowed,
3051                            (PyObject *)cmd_obj_sp->GetValue());
3052 
3053   if (!implementor.IsAllocated())
3054     return result;
3055 
3056   PythonObject pmeth(PyRefType::Owned,
3057                      PyObject_GetAttrString(implementor.get(), callee_name));
3058 
3059   if (PyErr_Occurred())
3060     PyErr_Clear();
3061 
3062   if (!pmeth.IsAllocated())
3063     return result;
3064 
3065   if (PyCallable_Check(pmeth.get()) == 0) {
3066     if (PyErr_Occurred())
3067       PyErr_Clear();
3068     return result;
3069   }
3070 
3071   if (PyErr_Occurred())
3072     PyErr_Clear();
3073 
3074   long long py_return = unwrapOrSetPythonException(
3075       As<long long>(implementor.CallMethod(callee_name)));
3076 
3077   // if it fails, print the error but otherwise go on
3078   if (PyErr_Occurred()) {
3079     PyErr_Print();
3080     PyErr_Clear();
3081   } else {
3082     result = py_return;
3083   }
3084 
3085   return result;
3086 }
3087 
3088 bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3089     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
3090   bool got_string = false;
3091   dest.clear();
3092 
3093   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3094 
3095   static char callee_name[] = "get_long_help";
3096 
3097   if (!cmd_obj_sp)
3098     return false;
3099 
3100   PythonObject implementor(PyRefType::Borrowed,
3101                            (PyObject *)cmd_obj_sp->GetValue());
3102 
3103   if (!implementor.IsAllocated())
3104     return false;
3105 
3106   PythonObject pmeth(PyRefType::Owned,
3107                      PyObject_GetAttrString(implementor.get(), callee_name));
3108 
3109   if (PyErr_Occurred())
3110     PyErr_Clear();
3111 
3112   if (!pmeth.IsAllocated())
3113     return false;
3114 
3115   if (PyCallable_Check(pmeth.get()) == 0) {
3116     if (PyErr_Occurred())
3117       PyErr_Clear();
3118 
3119     return false;
3120   }
3121 
3122   if (PyErr_Occurred())
3123     PyErr_Clear();
3124 
3125   // right now we know this function exists and is callable..
3126   PythonObject py_return(
3127       PyRefType::Owned,
3128       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3129 
3130   // if it fails, print the error but otherwise go on
3131   if (PyErr_Occurred()) {
3132     PyErr_Print();
3133     PyErr_Clear();
3134   }
3135 
3136   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3137     PythonString str(PyRefType::Borrowed, py_return.get());
3138     llvm::StringRef str_data(str.GetString());
3139     dest.assign(str_data.data(), str_data.size());
3140     got_string = true;
3141   }
3142 
3143   return got_string;
3144 }
3145 
3146 std::unique_ptr<ScriptInterpreterLocker>
3147 ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3148   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3149       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3150       Locker::FreeLock | Locker::TearDownSession));
3151   return py_lock;
3152 }
3153 
3154 void ScriptInterpreterPythonImpl::Initialize() {
3155   LLDB_SCOPED_TIMER();
3156 
3157   // RAII-based initialization which correctly handles multiple-initialization,
3158   // version- specific differences among Python 2 and Python 3, and saving and
3159   // restoring various other pieces of state that can get mucked with during
3160   // initialization.
3161   InitializePythonRAII initialize_guard;
3162 
3163   LLDBSwigPyInit();
3164 
3165   // Update the path python uses to search for modules to include the current
3166   // directory.
3167 
3168   PyRun_SimpleString("import sys");
3169   AddToSysPath(AddLocation::End, ".");
3170 
3171   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
3172   // that use a backslash as the path separator, this will result in executing
3173   // python code containing paths with unescaped backslashes.  But Python also
3174   // accepts forward slashes, so to make life easier we just use that.
3175   if (FileSpec file_spec = GetPythonDir())
3176     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3177   if (FileSpec file_spec = HostInfo::GetShlibDir())
3178     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3179 
3180   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3181                      "lldb.embedded_interpreter; from "
3182                      "lldb.embedded_interpreter import run_python_interpreter; "
3183                      "from lldb.embedded_interpreter import run_one_line");
3184 
3185 #if LLDB_USE_PYTHON_SET_INTERRUPT
3186   // Python will not just overwrite its internal SIGINT handler but also the
3187   // one from the process. Backup the current SIGINT handler to prevent that
3188   // Python deletes it.
3189   RestoreSignalHandlerScope save_sigint(SIGINT);
3190 
3191   // Setup a default SIGINT signal handler that works the same way as the
3192   // normal Python REPL signal handler which raises a KeyboardInterrupt.
3193   // Also make sure to not pollute the user's REPL with the signal module nor
3194   // our utility function.
3195   PyRun_SimpleString("def lldb_setup_sigint_handler():\n"
3196                      "  import signal;\n"
3197                      "  def signal_handler(sig, frame):\n"
3198                      "    raise KeyboardInterrupt()\n"
3199                      "  signal.signal(signal.SIGINT, signal_handler);\n"
3200                      "lldb_setup_sigint_handler();\n"
3201                      "del lldb_setup_sigint_handler\n");
3202 #endif
3203 }
3204 
3205 void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3206                                                std::string path) {
3207   std::string path_copy;
3208 
3209   std::string statement;
3210   if (location == AddLocation::Beginning) {
3211     statement.assign("sys.path.insert(0,\"");
3212     statement.append(path);
3213     statement.append("\")");
3214   } else {
3215     statement.assign("sys.path.append(\"");
3216     statement.append(path);
3217     statement.append("\")");
3218   }
3219   PyRun_SimpleString(statement.c_str());
3220 }
3221 
3222 // We are intentionally NOT calling Py_Finalize here (this would be the logical
3223 // place to call it).  Calling Py_Finalize here causes test suite runs to seg
3224 // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
3225 // be called 'at_exit'.  When the test suite Python harness finishes up, it
3226 // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3227 // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3228 // which calls ScriptInterpreter::Terminate, which calls
3229 // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
3230 // end up with Py_Finalize being called from within Py_Finalize, which results
3231 // in a seg fault. Since this function only gets called when lldb is shutting
3232 // down and going away anyway, the fact that we don't actually call Py_Finalize
3233 // should not cause any problems (everything should shut down/go away anyway
3234 // when the process exits).
3235 //
3236 // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3237 
3238 #endif
3239