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