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