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