xref: /llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp (revision f01f80ce6ca7640bb0e267b84b1ed0e89b57e2d9)
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(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(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.SetErrorStringWithFormat(
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.SetErrorString("cannot pass extra_args to a three argument callback"
1192                           );
1193       return error;
1194     }
1195     uses_extra_args = false;
1196     function_signature += "(frame, bp_loc, internal_dict)";
1197   } else {
1198     error.SetErrorStringWithFormat("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.SetErrorString("No input data.");
1301     return error;
1302   }
1303 
1304   if (!signature || *signature == 0) {
1305     error.SetErrorString("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("ScriptInterpreterPythonImpl::GenerateFunction(is_callback="
1333                     "true) = ERROR: python function is multiline.");
1334     }
1335   } else {
1336     auto_generated_function.AppendString(
1337         "    __return_val = None"); // Initialize user callback return value.
1338     auto_generated_function.AppendString(
1339         "    def __user_code():"); // Create a nested function that will wrap
1340                                    // the user input. This is necessary to
1341                                    // capture the return value of the user input
1342                                    // and prevent early returns.
1343     for (int i = 0; i < num_lines; ++i) {
1344       sstr.Clear();
1345       sstr.Printf("      %s", input.GetStringAtIndex(i));
1346       auto_generated_function.AppendString(sstr.GetData());
1347     }
1348     auto_generated_function.AppendString(
1349         "    __return_val = __user_code()"); //  Call user code and capture
1350                                              //  return value
1351   }
1352   auto_generated_function.AppendString(
1353       "    for key in new_keys:"); // Iterate over all the keys from session
1354                                    // dict
1355   auto_generated_function.AppendString(
1356       "        internal_dict[key] = global_dict[key]"); // Update session dict
1357                                                         // values
1358   auto_generated_function.AppendString(
1359       "        if key not in old_keys:"); // If key was not originally in
1360                                           // global dict
1361   auto_generated_function.AppendString(
1362       "            del global_dict[key]"); //  ...then remove key/value from
1363                                            //  global dict
1364   auto_generated_function.AppendString(
1365       "    return __return_val"); //  Return the user callback return value.
1366 
1367   // Verify that the results are valid Python.
1368   error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
1369 
1370   return error;
1371 }
1372 
1373 bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1374     StringList &user_input, std::string &output, const void *name_token) {
1375   static uint32_t num_created_functions = 0;
1376   user_input.RemoveBlankLines();
1377   StreamString sstr;
1378 
1379   // Check to see if we have any data; if not, just return.
1380   if (user_input.GetSize() == 0)
1381     return false;
1382 
1383   // Take what the user wrote, wrap it all up inside one big auto-generated
1384   // Python function, passing in the ValueObject as parameter to the function.
1385 
1386   std::string auto_generated_function_name(
1387       GenerateUniqueName("lldb_autogen_python_type_print_func",
1388                          num_created_functions, name_token));
1389   sstr.Printf("def %s (valobj, internal_dict):",
1390               auto_generated_function_name.c_str());
1391 
1392   if (!GenerateFunction(sstr.GetData(), user_input, /*is_callback=*/false)
1393            .Success())
1394     return false;
1395 
1396   // Store the name of the auto-generated function to be called.
1397   output.assign(auto_generated_function_name);
1398   return true;
1399 }
1400 
1401 bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1402     StringList &user_input, std::string &output) {
1403   static uint32_t num_created_functions = 0;
1404   user_input.RemoveBlankLines();
1405   StreamString sstr;
1406 
1407   // Check to see if we have any data; if not, just return.
1408   if (user_input.GetSize() == 0)
1409     return false;
1410 
1411   std::string auto_generated_function_name(GenerateUniqueName(
1412       "lldb_autogen_python_cmd_alias_func", num_created_functions));
1413 
1414   sstr.Printf("def %s (debugger, args, exe_ctx, result, internal_dict):",
1415               auto_generated_function_name.c_str());
1416 
1417   if (!GenerateFunction(sstr.GetData(), user_input, /*is_callback=*/false)
1418            .Success())
1419     return false;
1420 
1421   // Store the name of the auto-generated function to be called.
1422   output.assign(auto_generated_function_name);
1423   return true;
1424 }
1425 
1426 bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1427     StringList &user_input, std::string &output, const void *name_token) {
1428   static uint32_t num_created_classes = 0;
1429   user_input.RemoveBlankLines();
1430   int num_lines = user_input.GetSize();
1431   StreamString sstr;
1432 
1433   // Check to see if we have any data; if not, just return.
1434   if (user_input.GetSize() == 0)
1435     return false;
1436 
1437   // Wrap all user input into a Python class
1438 
1439   std::string auto_generated_class_name(GenerateUniqueName(
1440       "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1441 
1442   StringList auto_generated_class;
1443 
1444   // Create the function name & definition string.
1445 
1446   sstr.Printf("class %s:", auto_generated_class_name.c_str());
1447   auto_generated_class.AppendString(sstr.GetString());
1448 
1449   // Wrap everything up inside the class, increasing the indentation. we don't
1450   // need to play any fancy indentation tricks here because there is no
1451   // surrounding code whose indentation we need to honor
1452   for (int i = 0; i < num_lines; ++i) {
1453     sstr.Clear();
1454     sstr.Printf("     %s", user_input.GetStringAtIndex(i));
1455     auto_generated_class.AppendString(sstr.GetString());
1456   }
1457 
1458   // Verify that the results are valid Python. (even though the method is
1459   // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1460   // (TODO: rename that method to ExportDefinitionToInterpreter)
1461   if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
1462     return false;
1463 
1464   // Store the name of the auto-generated class
1465 
1466   output.assign(auto_generated_class_name);
1467   return true;
1468 }
1469 
1470 StructuredData::GenericSP
1471 ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
1472   if (class_name == nullptr || class_name[0] == '\0')
1473     return StructuredData::GenericSP();
1474 
1475   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1476   PythonObject ret_val = SWIGBridge::LLDBSWIGPython_CreateFrameRecognizer(
1477       class_name, m_dictionary_name.c_str());
1478 
1479   return StructuredData::GenericSP(
1480       new StructuredPythonObject(std::move(ret_val)));
1481 }
1482 
1483 lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
1484     const StructuredData::ObjectSP &os_plugin_object_sp,
1485     lldb::StackFrameSP frame_sp) {
1486   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1487 
1488   if (!os_plugin_object_sp)
1489     return ValueObjectListSP();
1490 
1491   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1492   if (!generic)
1493     return nullptr;
1494 
1495   PythonObject implementor(PyRefType::Borrowed,
1496                            (PyObject *)generic->GetValue());
1497 
1498   if (!implementor.IsAllocated())
1499     return ValueObjectListSP();
1500 
1501   PythonObject py_return(PyRefType::Owned,
1502                          SWIGBridge::LLDBSwigPython_GetRecognizedArguments(
1503                              implementor.get(), frame_sp));
1504 
1505   // if it fails, print the error but otherwise go on
1506   if (PyErr_Occurred()) {
1507     PyErr_Print();
1508     PyErr_Clear();
1509   }
1510   if (py_return.get()) {
1511     PythonList result_list(PyRefType::Borrowed, py_return.get());
1512     ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
1513     for (size_t i = 0; i < result_list.GetSize(); i++) {
1514       PyObject *item = result_list.GetItemAtIndex(i).get();
1515       lldb::SBValue *sb_value_ptr =
1516           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
1517       auto valobj_sp =
1518           SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
1519       if (valobj_sp)
1520         result->Append(valobj_sp);
1521     }
1522     return result;
1523   }
1524   return ValueObjectListSP();
1525 }
1526 
1527 bool ScriptInterpreterPythonImpl::ShouldHide(
1528     const StructuredData::ObjectSP &os_plugin_object_sp,
1529     lldb::StackFrameSP frame_sp) {
1530   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1531 
1532   if (!os_plugin_object_sp)
1533     return false;
1534 
1535   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1536   if (!generic)
1537     return false;
1538 
1539   PythonObject implementor(PyRefType::Borrowed,
1540                            (PyObject *)generic->GetValue());
1541 
1542   if (!implementor.IsAllocated())
1543     return false;
1544 
1545   bool result =
1546       SWIGBridge::LLDBSwigPython_ShouldHide(implementor.get(), frame_sp);
1547 
1548   // if it fails, print the error but otherwise go on
1549   if (PyErr_Occurred()) {
1550     PyErr_Print();
1551     PyErr_Clear();
1552   }
1553   return result;
1554 }
1555 
1556 ScriptedProcessInterfaceUP
1557 ScriptInterpreterPythonImpl::CreateScriptedProcessInterface() {
1558   return std::make_unique<ScriptedProcessPythonInterface>(*this);
1559 }
1560 
1561 ScriptedThreadInterfaceSP
1562 ScriptInterpreterPythonImpl::CreateScriptedThreadInterface() {
1563   return std::make_shared<ScriptedThreadPythonInterface>(*this);
1564 }
1565 
1566 ScriptedThreadPlanInterfaceSP
1567 ScriptInterpreterPythonImpl::CreateScriptedThreadPlanInterface() {
1568   return std::make_shared<ScriptedThreadPlanPythonInterface>(*this);
1569 }
1570 
1571 OperatingSystemInterfaceSP
1572 ScriptInterpreterPythonImpl::CreateOperatingSystemInterface() {
1573   return std::make_shared<OperatingSystemPythonInterface>(*this);
1574 }
1575 
1576 StructuredData::ObjectSP
1577 ScriptInterpreterPythonImpl::CreateStructuredDataFromScriptObject(
1578     ScriptObject obj) {
1579   void *ptr = const_cast<void *>(obj.GetPointer());
1580   PythonObject py_obj(PyRefType::Borrowed, static_cast<PyObject *>(ptr));
1581   if (!py_obj.IsValid() || py_obj.IsNone())
1582     return {};
1583   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1584   return py_obj.CreateStructuredObject();
1585 }
1586 
1587 StructuredData::GenericSP
1588 ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
1589     const char *class_name, const StructuredDataImpl &args_data,
1590     lldb::BreakpointSP &bkpt_sp) {
1591 
1592   if (class_name == nullptr || class_name[0] == '\0')
1593     return StructuredData::GenericSP();
1594 
1595   if (!bkpt_sp.get())
1596     return StructuredData::GenericSP();
1597 
1598   Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
1599   ScriptInterpreterPythonImpl *python_interpreter =
1600       GetPythonInterpreter(debugger);
1601 
1602   if (!python_interpreter)
1603     return StructuredData::GenericSP();
1604 
1605   Locker py_lock(this,
1606                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1607 
1608   PythonObject ret_val =
1609       SWIGBridge::LLDBSwigPythonCreateScriptedBreakpointResolver(
1610           class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
1611           bkpt_sp);
1612 
1613   return StructuredData::GenericSP(
1614       new StructuredPythonObject(std::move(ret_val)));
1615 }
1616 
1617 bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
1618     StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
1619   bool should_continue = false;
1620 
1621   if (implementor_sp) {
1622     Locker py_lock(this,
1623                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1624     should_continue = SWIGBridge::LLDBSwigPythonCallBreakpointResolver(
1625         implementor_sp->GetValue(), "__callback__", sym_ctx);
1626     if (PyErr_Occurred()) {
1627       PyErr_Print();
1628       PyErr_Clear();
1629     }
1630   }
1631   return should_continue;
1632 }
1633 
1634 lldb::SearchDepth
1635 ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
1636     StructuredData::GenericSP implementor_sp) {
1637   int depth_as_int = lldb::eSearchDepthModule;
1638   if (implementor_sp) {
1639     Locker py_lock(this,
1640                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1641     depth_as_int = SWIGBridge::LLDBSwigPythonCallBreakpointResolver(
1642         implementor_sp->GetValue(), "__get_depth__", nullptr);
1643     if (PyErr_Occurred()) {
1644       PyErr_Print();
1645       PyErr_Clear();
1646     }
1647   }
1648   if (depth_as_int == lldb::eSearchDepthInvalid)
1649     return lldb::eSearchDepthModule;
1650 
1651   if (depth_as_int <= lldb::kLastSearchDepthKind)
1652     return (lldb::SearchDepth)depth_as_int;
1653   return lldb::eSearchDepthModule;
1654 }
1655 
1656 StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
1657     TargetSP target_sp, const char *class_name,
1658     const StructuredDataImpl &args_data, Status &error) {
1659 
1660   if (!target_sp) {
1661     error.SetErrorString("No target for scripted stop-hook.");
1662     return StructuredData::GenericSP();
1663   }
1664 
1665   if (class_name == nullptr || class_name[0] == '\0') {
1666     error.SetErrorString("No class name for scripted stop-hook.");
1667     return StructuredData::GenericSP();
1668   }
1669 
1670   ScriptInterpreterPythonImpl *python_interpreter =
1671       GetPythonInterpreter(m_debugger);
1672 
1673   if (!python_interpreter) {
1674     error.SetErrorString("No script interpreter for scripted stop-hook.");
1675     return StructuredData::GenericSP();
1676   }
1677 
1678   Locker py_lock(this,
1679                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1680 
1681   PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateScriptedStopHook(
1682       target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
1683       args_data, error);
1684 
1685   return StructuredData::GenericSP(
1686       new StructuredPythonObject(std::move(ret_val)));
1687 }
1688 
1689 bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
1690     StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
1691     lldb::StreamSP stream_sp) {
1692   assert(implementor_sp &&
1693          "can't call a stop hook with an invalid implementor");
1694   assert(stream_sp && "can't call a stop hook with an invalid stream");
1695 
1696   Locker py_lock(this,
1697                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1698 
1699   lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
1700 
1701   bool ret_val = SWIGBridge::LLDBSwigPythonStopHookCallHandleStop(
1702       implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
1703   return ret_val;
1704 }
1705 
1706 StructuredData::ObjectSP
1707 ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
1708                                               lldb_private::Status &error) {
1709   if (!FileSystem::Instance().Exists(file_spec)) {
1710     error.SetErrorString("no such file");
1711     return StructuredData::ObjectSP();
1712   }
1713 
1714   StructuredData::ObjectSP module_sp;
1715 
1716   LoadScriptOptions load_script_options =
1717       LoadScriptOptions().SetInitSession(true).SetSilent(false);
1718   if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1719                           error, &module_sp))
1720     return module_sp;
1721 
1722   return StructuredData::ObjectSP();
1723 }
1724 
1725 StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
1726     StructuredData::ObjectSP plugin_module_sp, Target *target,
1727     const char *setting_name, lldb_private::Status &error) {
1728   if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
1729     return StructuredData::DictionarySP();
1730   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
1731   if (!generic)
1732     return StructuredData::DictionarySP();
1733 
1734   Locker py_lock(this,
1735                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1736   TargetSP target_sp(target->shared_from_this());
1737 
1738   auto setting = (PyObject *)SWIGBridge::LLDBSWIGPython_GetDynamicSetting(
1739       generic->GetValue(), setting_name, target_sp);
1740 
1741   if (!setting)
1742     return StructuredData::DictionarySP();
1743 
1744   PythonDictionary py_dict =
1745       unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
1746 
1747   if (!py_dict)
1748     return StructuredData::DictionarySP();
1749 
1750   return py_dict.CreateStructuredDictionary();
1751 }
1752 
1753 StructuredData::ObjectSP
1754 ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
1755     const char *class_name, lldb::ValueObjectSP valobj) {
1756   if (class_name == nullptr || class_name[0] == '\0')
1757     return StructuredData::ObjectSP();
1758 
1759   if (!valobj.get())
1760     return StructuredData::ObjectSP();
1761 
1762   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
1763   Target *target = exe_ctx.GetTargetPtr();
1764 
1765   if (!target)
1766     return StructuredData::ObjectSP();
1767 
1768   Debugger &debugger = target->GetDebugger();
1769   ScriptInterpreterPythonImpl *python_interpreter =
1770       GetPythonInterpreter(debugger);
1771 
1772   if (!python_interpreter)
1773     return StructuredData::ObjectSP();
1774 
1775   Locker py_lock(this,
1776                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1777   PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateSyntheticProvider(
1778       class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
1779 
1780   return StructuredData::ObjectSP(
1781       new StructuredPythonObject(std::move(ret_val)));
1782 }
1783 
1784 StructuredData::GenericSP
1785 ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
1786   DebuggerSP debugger_sp(m_debugger.shared_from_this());
1787 
1788   if (class_name == nullptr || class_name[0] == '\0')
1789     return StructuredData::GenericSP();
1790 
1791   if (!debugger_sp.get())
1792     return StructuredData::GenericSP();
1793 
1794   Locker py_lock(this,
1795                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1796   PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateCommandObject(
1797       class_name, m_dictionary_name.c_str(), debugger_sp);
1798 
1799   if (ret_val.IsValid())
1800     return StructuredData::GenericSP(
1801         new StructuredPythonObject(std::move(ret_val)));
1802   else
1803     return {};
1804 }
1805 
1806 bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1807     const char *oneliner, std::string &output, const void *name_token) {
1808   StringList input;
1809   input.SplitIntoLines(oneliner, strlen(oneliner));
1810   return GenerateTypeScriptFunction(input, output, name_token);
1811 }
1812 
1813 bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1814     const char *oneliner, std::string &output, const void *name_token) {
1815   StringList input;
1816   input.SplitIntoLines(oneliner, strlen(oneliner));
1817   return GenerateTypeSynthClass(input, output, name_token);
1818 }
1819 
1820 Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
1821     StringList &user_input, std::string &output, bool has_extra_args,
1822     bool is_callback) {
1823   static uint32_t num_created_functions = 0;
1824   user_input.RemoveBlankLines();
1825   StreamString sstr;
1826   Status error;
1827   if (user_input.GetSize() == 0) {
1828     error.SetErrorString("No input data.");
1829     return error;
1830   }
1831 
1832   std::string auto_generated_function_name(GenerateUniqueName(
1833       "lldb_autogen_python_bp_callback_func_", num_created_functions));
1834   if (has_extra_args)
1835     sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
1836                 auto_generated_function_name.c_str());
1837   else
1838     sstr.Printf("def %s (frame, bp_loc, internal_dict):",
1839                 auto_generated_function_name.c_str());
1840 
1841   error = GenerateFunction(sstr.GetData(), user_input, is_callback);
1842   if (!error.Success())
1843     return error;
1844 
1845   // Store the name of the auto-generated function to be called.
1846   output.assign(auto_generated_function_name);
1847   return error;
1848 }
1849 
1850 bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
1851     StringList &user_input, std::string &output, bool is_callback) {
1852   static uint32_t num_created_functions = 0;
1853   user_input.RemoveBlankLines();
1854   StreamString sstr;
1855 
1856   if (user_input.GetSize() == 0)
1857     return false;
1858 
1859   std::string auto_generated_function_name(GenerateUniqueName(
1860       "lldb_autogen_python_wp_callback_func_", num_created_functions));
1861   sstr.Printf("def %s (frame, wp, internal_dict):",
1862               auto_generated_function_name.c_str());
1863 
1864   if (!GenerateFunction(sstr.GetData(), user_input, is_callback).Success())
1865     return false;
1866 
1867   // Store the name of the auto-generated function to be called.
1868   output.assign(auto_generated_function_name);
1869   return true;
1870 }
1871 
1872 bool ScriptInterpreterPythonImpl::GetScriptedSummary(
1873     const char *python_function_name, lldb::ValueObjectSP valobj,
1874     StructuredData::ObjectSP &callee_wrapper_sp,
1875     const TypeSummaryOptions &options, std::string &retval) {
1876 
1877   LLDB_SCOPED_TIMER();
1878 
1879   if (!valobj.get()) {
1880     retval.assign("<no object>");
1881     return false;
1882   }
1883 
1884   void *old_callee = nullptr;
1885   StructuredData::Generic *generic = nullptr;
1886   if (callee_wrapper_sp) {
1887     generic = callee_wrapper_sp->GetAsGeneric();
1888     if (generic)
1889       old_callee = generic->GetValue();
1890   }
1891   void *new_callee = old_callee;
1892 
1893   bool ret_val;
1894   if (python_function_name && *python_function_name) {
1895     {
1896       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
1897                                Locker::NoSTDIN);
1898       {
1899         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
1900 
1901         static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
1902         Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
1903         ret_val = SWIGBridge::LLDBSwigPythonCallTypeScript(
1904             python_function_name, GetSessionDictionary().get(), valobj,
1905             &new_callee, options_sp, retval);
1906       }
1907     }
1908   } else {
1909     retval.assign("<no function name>");
1910     return false;
1911   }
1912 
1913   if (new_callee && old_callee != new_callee) {
1914     Locker py_lock(this,
1915                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1916     callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
1917         PythonObject(PyRefType::Borrowed, static_cast<PyObject *>(new_callee)));
1918   }
1919 
1920   return ret_val;
1921 }
1922 
1923 bool ScriptInterpreterPythonImpl::FormatterCallbackFunction(
1924     const char *python_function_name, TypeImplSP type_impl_sp) {
1925   Locker py_lock(this,
1926                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1927   return SWIGBridge::LLDBSwigPythonFormatterCallbackFunction(
1928       python_function_name, m_dictionary_name.c_str(), type_impl_sp);
1929 }
1930 
1931 bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
1932     void *baton, StoppointCallbackContext *context, user_id_t break_id,
1933     user_id_t break_loc_id) {
1934   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
1935   const char *python_function_name = bp_option_data->script_source.c_str();
1936 
1937   if (!context)
1938     return true;
1939 
1940   ExecutionContext exe_ctx(context->exe_ctx_ref);
1941   Target *target = exe_ctx.GetTargetPtr();
1942 
1943   if (!target)
1944     return true;
1945 
1946   Debugger &debugger = target->GetDebugger();
1947   ScriptInterpreterPythonImpl *python_interpreter =
1948       GetPythonInterpreter(debugger);
1949 
1950   if (!python_interpreter)
1951     return true;
1952 
1953   if (python_function_name && python_function_name[0]) {
1954     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
1955     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
1956     if (breakpoint_sp) {
1957       const BreakpointLocationSP bp_loc_sp(
1958           breakpoint_sp->FindLocationByID(break_loc_id));
1959 
1960       if (stop_frame_sp && bp_loc_sp) {
1961         bool ret_val = true;
1962         {
1963           Locker py_lock(python_interpreter, Locker::AcquireLock |
1964                                                  Locker::InitSession |
1965                                                  Locker::NoSTDIN);
1966           Expected<bool> maybe_ret_val =
1967               SWIGBridge::LLDBSwigPythonBreakpointCallbackFunction(
1968                   python_function_name,
1969                   python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
1970                   bp_loc_sp, bp_option_data->m_extra_args);
1971 
1972           if (!maybe_ret_val) {
1973 
1974             llvm::handleAllErrors(
1975                 maybe_ret_val.takeError(),
1976                 [&](PythonException &E) {
1977                   debugger.GetErrorStream() << E.ReadBacktrace();
1978                 },
1979                 [&](const llvm::ErrorInfoBase &E) {
1980                   debugger.GetErrorStream() << E.message();
1981                 });
1982 
1983           } else {
1984             ret_val = maybe_ret_val.get();
1985           }
1986         }
1987         return ret_val;
1988       }
1989     }
1990   }
1991   // We currently always true so we stop in case anything goes wrong when
1992   // trying to call the script function
1993   return true;
1994 }
1995 
1996 bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
1997     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
1998   WatchpointOptions::CommandData *wp_option_data =
1999       (WatchpointOptions::CommandData *)baton;
2000   const char *python_function_name = wp_option_data->script_source.c_str();
2001 
2002   if (!context)
2003     return true;
2004 
2005   ExecutionContext exe_ctx(context->exe_ctx_ref);
2006   Target *target = exe_ctx.GetTargetPtr();
2007 
2008   if (!target)
2009     return true;
2010 
2011   Debugger &debugger = target->GetDebugger();
2012   ScriptInterpreterPythonImpl *python_interpreter =
2013       GetPythonInterpreter(debugger);
2014 
2015   if (!python_interpreter)
2016     return true;
2017 
2018   if (python_function_name && python_function_name[0]) {
2019     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2020     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2021     if (wp_sp) {
2022       if (stop_frame_sp && wp_sp) {
2023         bool ret_val = true;
2024         {
2025           Locker py_lock(python_interpreter, Locker::AcquireLock |
2026                                                  Locker::InitSession |
2027                                                  Locker::NoSTDIN);
2028           ret_val = SWIGBridge::LLDBSwigPythonWatchpointCallbackFunction(
2029               python_function_name,
2030               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2031               wp_sp);
2032         }
2033         return ret_val;
2034       }
2035     }
2036   }
2037   // We currently always true so we stop in case anything goes wrong when
2038   // trying to call the script function
2039   return true;
2040 }
2041 
2042 size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2043     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
2044   if (!implementor_sp)
2045     return 0;
2046   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2047   if (!generic)
2048     return 0;
2049   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2050   if (!implementor)
2051     return 0;
2052 
2053   size_t ret_val = 0;
2054 
2055   {
2056     Locker py_lock(this,
2057                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2058     ret_val = SWIGBridge::LLDBSwigPython_CalculateNumChildren(implementor, max);
2059   }
2060 
2061   return ret_val;
2062 }
2063 
2064 lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
2065     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
2066   if (!implementor_sp)
2067     return lldb::ValueObjectSP();
2068 
2069   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2070   if (!generic)
2071     return lldb::ValueObjectSP();
2072   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2073   if (!implementor)
2074     return lldb::ValueObjectSP();
2075 
2076   lldb::ValueObjectSP ret_val;
2077   {
2078     Locker py_lock(this,
2079                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2080     PyObject *child_ptr =
2081         SWIGBridge::LLDBSwigPython_GetChildAtIndex(implementor, idx);
2082     if (child_ptr != nullptr && child_ptr != Py_None) {
2083       lldb::SBValue *sb_value_ptr =
2084           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2085       if (sb_value_ptr == nullptr)
2086         Py_XDECREF(child_ptr);
2087       else
2088         ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
2089             sb_value_ptr);
2090     } else {
2091       Py_XDECREF(child_ptr);
2092     }
2093   }
2094 
2095   return ret_val;
2096 }
2097 
2098 int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2099     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
2100   if (!implementor_sp)
2101     return UINT32_MAX;
2102 
2103   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2104   if (!generic)
2105     return UINT32_MAX;
2106   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2107   if (!implementor)
2108     return UINT32_MAX;
2109 
2110   int ret_val = UINT32_MAX;
2111 
2112   {
2113     Locker py_lock(this,
2114                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2115     ret_val = SWIGBridge::LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
2116   }
2117 
2118   return ret_val;
2119 }
2120 
2121 bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2122     const StructuredData::ObjectSP &implementor_sp) {
2123   bool ret_val = false;
2124 
2125   if (!implementor_sp)
2126     return ret_val;
2127 
2128   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2129   if (!generic)
2130     return ret_val;
2131   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2132   if (!implementor)
2133     return ret_val;
2134 
2135   {
2136     Locker py_lock(this,
2137                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2138     ret_val =
2139         SWIGBridge::LLDBSwigPython_UpdateSynthProviderInstance(implementor);
2140   }
2141 
2142   return ret_val;
2143 }
2144 
2145 bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2146     const StructuredData::ObjectSP &implementor_sp) {
2147   bool ret_val = false;
2148 
2149   if (!implementor_sp)
2150     return ret_val;
2151 
2152   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2153   if (!generic)
2154     return ret_val;
2155   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2156   if (!implementor)
2157     return ret_val;
2158 
2159   {
2160     Locker py_lock(this,
2161                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2162     ret_val = SWIGBridge::LLDBSwigPython_MightHaveChildrenSynthProviderInstance(
2163         implementor);
2164   }
2165 
2166   return ret_val;
2167 }
2168 
2169 lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
2170     const StructuredData::ObjectSP &implementor_sp) {
2171   lldb::ValueObjectSP ret_val(nullptr);
2172 
2173   if (!implementor_sp)
2174     return ret_val;
2175 
2176   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2177   if (!generic)
2178     return ret_val;
2179   auto *implementor = static_cast<PyObject *>(generic->GetValue());
2180   if (!implementor)
2181     return ret_val;
2182 
2183   {
2184     Locker py_lock(this,
2185                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2186     PyObject *child_ptr =
2187         SWIGBridge::LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2188     if (child_ptr != nullptr && child_ptr != Py_None) {
2189       lldb::SBValue *sb_value_ptr =
2190           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2191       if (sb_value_ptr == nullptr)
2192         Py_XDECREF(child_ptr);
2193       else
2194         ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
2195             sb_value_ptr);
2196     } else {
2197       Py_XDECREF(child_ptr);
2198     }
2199   }
2200 
2201   return ret_val;
2202 }
2203 
2204 ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2205     const StructuredData::ObjectSP &implementor_sp) {
2206   Locker py_lock(this,
2207                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2208 
2209   if (!implementor_sp)
2210     return {};
2211 
2212   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2213   if (!generic)
2214     return {};
2215 
2216   PythonObject implementor(PyRefType::Borrowed,
2217                            (PyObject *)generic->GetValue());
2218   if (!implementor.IsAllocated())
2219     return {};
2220 
2221   llvm::Expected<PythonObject> expected_py_return =
2222       implementor.CallMethod("get_type_name");
2223 
2224   if (!expected_py_return) {
2225     llvm::consumeError(expected_py_return.takeError());
2226     return {};
2227   }
2228 
2229   PythonObject py_return = std::move(expected_py_return.get());
2230   if (!py_return.IsAllocated() || !PythonString::Check(py_return.get()))
2231     return {};
2232 
2233   PythonString type_name(PyRefType::Borrowed, py_return.get());
2234   return ConstString(type_name.GetString());
2235 }
2236 
2237 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2238     const char *impl_function, Process *process, std::string &output,
2239     Status &error) {
2240   bool ret_val;
2241   if (!process) {
2242     error.SetErrorString("no process");
2243     return false;
2244   }
2245   if (!impl_function || !impl_function[0]) {
2246     error.SetErrorString("no function to execute");
2247     return false;
2248   }
2249 
2250   {
2251     Locker py_lock(this,
2252                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2253     ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordProcess(
2254         impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
2255         output);
2256     if (!ret_val)
2257       error.SetErrorString("python script evaluation failed");
2258   }
2259   return ret_val;
2260 }
2261 
2262 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2263     const char *impl_function, Thread *thread, std::string &output,
2264     Status &error) {
2265   if (!thread) {
2266     error.SetErrorString("no thread");
2267     return false;
2268   }
2269   if (!impl_function || !impl_function[0]) {
2270     error.SetErrorString("no function to execute");
2271     return false;
2272   }
2273 
2274   Locker py_lock(this,
2275                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2276   if (std::optional<std::string> result =
2277           SWIGBridge::LLDBSWIGPythonRunScriptKeywordThread(
2278               impl_function, m_dictionary_name.c_str(),
2279               thread->shared_from_this())) {
2280     output = std::move(*result);
2281     return true;
2282   }
2283   error.SetErrorString("python script evaluation failed");
2284   return false;
2285 }
2286 
2287 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2288     const char *impl_function, Target *target, std::string &output,
2289     Status &error) {
2290   bool ret_val;
2291   if (!target) {
2292     error.SetErrorString("no thread");
2293     return false;
2294   }
2295   if (!impl_function || !impl_function[0]) {
2296     error.SetErrorString("no function to execute");
2297     return false;
2298   }
2299 
2300   {
2301     TargetSP target_sp(target->shared_from_this());
2302     Locker py_lock(this,
2303                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2304     ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordTarget(
2305         impl_function, m_dictionary_name.c_str(), target_sp, output);
2306     if (!ret_val)
2307       error.SetErrorString("python script evaluation failed");
2308   }
2309   return ret_val;
2310 }
2311 
2312 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2313     const char *impl_function, StackFrame *frame, std::string &output,
2314     Status &error) {
2315   if (!frame) {
2316     error.SetErrorString("no frame");
2317     return false;
2318   }
2319   if (!impl_function || !impl_function[0]) {
2320     error.SetErrorString("no function to execute");
2321     return false;
2322   }
2323 
2324   Locker py_lock(this,
2325                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2326   if (std::optional<std::string> result =
2327           SWIGBridge::LLDBSWIGPythonRunScriptKeywordFrame(
2328               impl_function, m_dictionary_name.c_str(),
2329               frame->shared_from_this())) {
2330     output = std::move(*result);
2331     return true;
2332   }
2333   error.SetErrorString("python script evaluation failed");
2334   return false;
2335 }
2336 
2337 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2338     const char *impl_function, ValueObject *value, std::string &output,
2339     Status &error) {
2340   bool ret_val;
2341   if (!value) {
2342     error.SetErrorString("no value");
2343     return false;
2344   }
2345   if (!impl_function || !impl_function[0]) {
2346     error.SetErrorString("no function to execute");
2347     return false;
2348   }
2349 
2350   {
2351     Locker py_lock(this,
2352                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2353     ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordValue(
2354         impl_function, m_dictionary_name.c_str(), value->GetSP(), output);
2355     if (!ret_val)
2356       error.SetErrorString("python script evaluation failed");
2357   }
2358   return ret_val;
2359 }
2360 
2361 uint64_t replace_all(std::string &str, const std::string &oldStr,
2362                      const std::string &newStr) {
2363   size_t pos = 0;
2364   uint64_t matches = 0;
2365   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2366     matches++;
2367     str.replace(pos, oldStr.length(), newStr);
2368     pos += newStr.length();
2369   }
2370   return matches;
2371 }
2372 
2373 bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2374     const char *pathname, const LoadScriptOptions &options,
2375     lldb_private::Status &error, StructuredData::ObjectSP *module_sp,
2376     FileSpec extra_search_dir) {
2377   namespace fs = llvm::sys::fs;
2378   namespace path = llvm::sys::path;
2379 
2380   ExecuteScriptOptions exc_options = ExecuteScriptOptions()
2381                                          .SetEnableIO(!options.GetSilent())
2382                                          .SetSetLLDBGlobals(false);
2383 
2384   if (!pathname || !pathname[0]) {
2385     error.SetErrorString("empty path");
2386     return false;
2387   }
2388 
2389   llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2390       io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2391           exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2392 
2393   if (!io_redirect_or_error) {
2394     error = io_redirect_or_error.takeError();
2395     return false;
2396   }
2397 
2398   ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
2399 
2400   // Before executing Python code, lock the GIL.
2401   Locker py_lock(this,
2402                  Locker::AcquireLock |
2403                      (options.GetInitSession() ? Locker::InitSession : 0) |
2404                      Locker::NoSTDIN,
2405                  Locker::FreeAcquiredLock |
2406                      (options.GetInitSession() ? Locker::TearDownSession : 0),
2407                  io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2408                  io_redirect.GetErrorFile());
2409 
2410   auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2411     if (directory.empty()) {
2412       return llvm::createStringError("invalid directory name");
2413     }
2414 
2415     replace_all(directory, "\\", "\\\\");
2416     replace_all(directory, "'", "\\'");
2417 
2418     // Make sure that Python has "directory" in the search path.
2419     StreamString command_stream;
2420     command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
2421                           "sys.path.insert(1,'%s');\n\n",
2422                           directory.c_str(), directory.c_str());
2423     bool syspath_retval =
2424         ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
2425     if (!syspath_retval)
2426       return llvm::createStringError("Python sys.path handling failed");
2427 
2428     return llvm::Error::success();
2429   };
2430 
2431   std::string module_name(pathname);
2432   bool possible_package = false;
2433 
2434   if (extra_search_dir) {
2435     if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2436       error = std::move(e);
2437       return false;
2438     }
2439   } else {
2440     FileSpec module_file(pathname);
2441     FileSystem::Instance().Resolve(module_file);
2442 
2443     fs::file_status st;
2444     std::error_code ec = status(module_file.GetPath(), st);
2445 
2446     if (ec || st.type() == fs::file_type::status_error ||
2447         st.type() == fs::file_type::type_unknown ||
2448         st.type() == fs::file_type::file_not_found) {
2449       // if not a valid file of any sort, check if it might be a filename still
2450       // dot can't be used but / and \ can, and if either is found, reject
2451       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2452         error.SetErrorStringWithFormatv("invalid pathname '{0}'", pathname);
2453         return false;
2454       }
2455       // Not a filename, probably a package of some sort, let it go through.
2456       possible_package = true;
2457     } else if (is_directory(st) || is_regular_file(st)) {
2458       if (module_file.GetDirectory().IsEmpty()) {
2459         error.SetErrorStringWithFormatv("invalid directory name '{0}'", pathname);
2460         return false;
2461       }
2462       if (llvm::Error e =
2463               ExtendSysPath(module_file.GetDirectory().GetCString())) {
2464         error = std::move(e);
2465         return false;
2466       }
2467       module_name = module_file.GetFilename().GetCString();
2468     } else {
2469       error.SetErrorString("no known way to import this module specification");
2470       return false;
2471     }
2472   }
2473 
2474   // Strip .py or .pyc extension
2475   llvm::StringRef extension = llvm::sys::path::extension(module_name);
2476   if (!extension.empty()) {
2477     if (extension == ".py")
2478       module_name.resize(module_name.length() - 3);
2479     else if (extension == ".pyc")
2480       module_name.resize(module_name.length() - 4);
2481   }
2482 
2483   if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2484     error.SetErrorStringWithFormat(
2485         "Python does not allow dots in module names: %s", module_name.c_str());
2486     return false;
2487   }
2488 
2489   if (module_name.find('-') != llvm::StringRef::npos) {
2490     error.SetErrorStringWithFormat(
2491         "Python discourages dashes in module names: %s", module_name.c_str());
2492     return false;
2493   }
2494 
2495   // Check if the module is already imported.
2496   StreamString command_stream;
2497   command_stream.Clear();
2498   command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
2499   bool does_contain = false;
2500   // This call will succeed if the module was ever imported in any Debugger in
2501   // the lifetime of the process in which this LLDB framework is living.
2502   const bool does_contain_executed = ExecuteOneLineWithReturn(
2503       command_stream.GetData(),
2504       ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options);
2505 
2506   const bool was_imported_globally = does_contain_executed && does_contain;
2507   const bool was_imported_locally =
2508       GetSessionDictionary()
2509           .GetItemForKey(PythonString(module_name))
2510           .IsAllocated();
2511 
2512   // now actually do the import
2513   command_stream.Clear();
2514 
2515   if (was_imported_globally || was_imported_locally) {
2516     if (!was_imported_locally)
2517       command_stream.Printf("import %s ; reload_module(%s)",
2518                             module_name.c_str(), module_name.c_str());
2519     else
2520       command_stream.Printf("reload_module(%s)", module_name.c_str());
2521   } else
2522     command_stream.Printf("import %s", module_name.c_str());
2523 
2524   error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
2525   if (error.Fail())
2526     return false;
2527 
2528   // if we are here, everything worked
2529   // call __lldb_init_module(debugger,dict)
2530   if (!SWIGBridge::LLDBSwigPythonCallModuleInit(
2531           module_name.c_str(), m_dictionary_name.c_str(),
2532           m_debugger.shared_from_this())) {
2533     error.SetErrorString("calling __lldb_init_module failed");
2534     return false;
2535   }
2536 
2537   if (module_sp) {
2538     // everything went just great, now set the module object
2539     command_stream.Clear();
2540     command_stream.Printf("%s", module_name.c_str());
2541     void *module_pyobj = nullptr;
2542     if (ExecuteOneLineWithReturn(
2543             command_stream.GetData(),
2544             ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2545             exc_options) &&
2546         module_pyobj)
2547       *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2548           PyRefType::Owned, static_cast<PyObject *>(module_pyobj)));
2549   }
2550 
2551   return true;
2552 }
2553 
2554 bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
2555   if (!word || !word[0])
2556     return false;
2557 
2558   llvm::StringRef word_sr(word);
2559 
2560   // filter out a few characters that would just confuse us and that are
2561   // clearly not keyword material anyway
2562   if (word_sr.find('"') != llvm::StringRef::npos ||
2563       word_sr.find('\'') != llvm::StringRef::npos)
2564     return false;
2565 
2566   StreamString command_stream;
2567   command_stream.Printf("keyword.iskeyword('%s')", word);
2568   bool result;
2569   ExecuteScriptOptions options;
2570   options.SetEnableIO(false);
2571   options.SetMaskoutErrors(true);
2572   options.SetSetLLDBGlobals(false);
2573   if (ExecuteOneLineWithReturn(command_stream.GetData(),
2574                                ScriptInterpreter::eScriptReturnTypeBool,
2575                                &result, options))
2576     return result;
2577   return false;
2578 }
2579 
2580 ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2581     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2582     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2583       m_old_asynch(debugger_sp->GetAsyncExecution()) {
2584   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2585     m_debugger_sp->SetAsyncExecution(false);
2586   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2587     m_debugger_sp->SetAsyncExecution(true);
2588 }
2589 
2590 ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
2591   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2592     m_debugger_sp->SetAsyncExecution(m_old_asynch);
2593 }
2594 
2595 bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2596     const char *impl_function, llvm::StringRef args,
2597     ScriptedCommandSynchronicity synchronicity,
2598     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2599     const lldb_private::ExecutionContext &exe_ctx) {
2600   if (!impl_function) {
2601     error.SetErrorString("no function to execute");
2602     return false;
2603   }
2604 
2605   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2606   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2607 
2608   if (!debugger_sp.get()) {
2609     error.SetErrorString("invalid Debugger pointer");
2610     return false;
2611   }
2612 
2613   bool ret_val = false;
2614 
2615   std::string err_msg;
2616 
2617   {
2618     Locker py_lock(this,
2619                    Locker::AcquireLock | Locker::InitSession |
2620                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2621                    Locker::FreeLock | Locker::TearDownSession);
2622 
2623     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2624 
2625     std::string args_str = args.str();
2626     ret_val = SWIGBridge::LLDBSwigPythonCallCommand(
2627         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2628         cmd_retobj, exe_ctx_ref_sp);
2629   }
2630 
2631   if (!ret_val)
2632     error.SetErrorString("unable to execute script function");
2633   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2634     return false;
2635 
2636   error.Clear();
2637   return ret_val;
2638 }
2639 
2640 bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2641     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
2642     ScriptedCommandSynchronicity synchronicity,
2643     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2644     const lldb_private::ExecutionContext &exe_ctx) {
2645   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2646     error.SetErrorString("no function to execute");
2647     return false;
2648   }
2649 
2650   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2651   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2652 
2653   if (!debugger_sp.get()) {
2654     error.SetErrorString("invalid Debugger pointer");
2655     return false;
2656   }
2657 
2658   bool ret_val = false;
2659 
2660   std::string err_msg;
2661 
2662   {
2663     Locker py_lock(this,
2664                    Locker::AcquireLock | Locker::InitSession |
2665                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2666                    Locker::FreeLock | Locker::TearDownSession);
2667 
2668     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2669 
2670     std::string args_str = args.str();
2671     ret_val = SWIGBridge::LLDBSwigPythonCallCommandObject(
2672         static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
2673         args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
2674   }
2675 
2676   if (!ret_val)
2677     error.SetErrorString("unable to execute script function");
2678   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2679     return false;
2680 
2681   error.Clear();
2682   return ret_val;
2683 }
2684 
2685 bool ScriptInterpreterPythonImpl::RunScriptBasedParsedCommand(
2686     StructuredData::GenericSP impl_obj_sp, Args &args,
2687     ScriptedCommandSynchronicity synchronicity,
2688     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2689     const lldb_private::ExecutionContext &exe_ctx) {
2690   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2691     error.SetErrorString("no function to execute");
2692     return false;
2693   }
2694 
2695   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2696   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2697 
2698   if (!debugger_sp.get()) {
2699     error.SetErrorString("invalid Debugger pointer");
2700     return false;
2701   }
2702 
2703   bool ret_val = false;
2704 
2705   std::string err_msg;
2706 
2707   {
2708     Locker py_lock(this,
2709                    Locker::AcquireLock | Locker::InitSession |
2710                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2711                    Locker::FreeLock | Locker::TearDownSession);
2712 
2713     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2714 
2715     StructuredData::ArraySP args_arr_sp(new StructuredData::Array());
2716 
2717     for (const Args::ArgEntry &entry : args) {
2718       args_arr_sp->AddStringItem(entry.ref());
2719     }
2720     StructuredDataImpl args_impl(args_arr_sp);
2721 
2722     ret_val = SWIGBridge::LLDBSwigPythonCallParsedCommandObject(
2723         static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
2724         args_impl, cmd_retobj, exe_ctx_ref_sp);
2725   }
2726 
2727   if (!ret_val)
2728     error.SetErrorString("unable to execute script function");
2729   else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2730     return false;
2731 
2732   error.Clear();
2733   return ret_val;
2734 }
2735 
2736 std::optional<std::string>
2737 ScriptInterpreterPythonImpl::GetRepeatCommandForScriptedCommand(
2738     StructuredData::GenericSP impl_obj_sp, Args &args) {
2739   if (!impl_obj_sp || !impl_obj_sp->IsValid())
2740     return std::nullopt;
2741 
2742   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2743 
2744   if (!debugger_sp.get())
2745     return std::nullopt;
2746 
2747   std::optional<std::string> ret_val;
2748 
2749   {
2750     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
2751                    Locker::FreeLock);
2752 
2753     StructuredData::ArraySP args_arr_sp(new StructuredData::Array());
2754 
2755     // For scripting commands, we send the command string:
2756     std::string command;
2757     args.GetQuotedCommandString(command);
2758     ret_val = SWIGBridge::LLDBSwigPythonGetRepeatCommandForScriptedCommand(
2759         static_cast<PyObject *>(impl_obj_sp->GetValue()), command);
2760   }
2761   return ret_val;
2762 }
2763 
2764 /// In Python, a special attribute __doc__ contains the docstring for an object
2765 /// (function, method, class, ...) if any is defined Otherwise, the attribute's
2766 /// value is None.
2767 bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
2768                                                           std::string &dest) {
2769   dest.clear();
2770 
2771   if (!item || !*item)
2772     return false;
2773 
2774   std::string command(item);
2775   command += ".__doc__";
2776 
2777   // Python is going to point this to valid data if ExecuteOneLineWithReturn
2778   // returns successfully.
2779   char *result_ptr = nullptr;
2780 
2781   if (ExecuteOneLineWithReturn(
2782           command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
2783           &result_ptr,
2784           ExecuteScriptOptions().SetEnableIO(false))) {
2785     if (result_ptr)
2786       dest.assign(result_ptr);
2787     return true;
2788   }
2789 
2790   StreamString str_stream;
2791   str_stream << "Function " << item
2792              << " was not found. Containing module might be missing.";
2793   dest = std::string(str_stream.GetString());
2794 
2795   return false;
2796 }
2797 
2798 bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
2799     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2800   dest.clear();
2801 
2802   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2803 
2804   if (!cmd_obj_sp)
2805     return false;
2806 
2807   PythonObject implementor(PyRefType::Borrowed,
2808                            (PyObject *)cmd_obj_sp->GetValue());
2809 
2810   if (!implementor.IsAllocated())
2811     return false;
2812 
2813   llvm::Expected<PythonObject> expected_py_return =
2814       implementor.CallMethod("get_short_help");
2815 
2816   if (!expected_py_return) {
2817     llvm::consumeError(expected_py_return.takeError());
2818     return false;
2819   }
2820 
2821   PythonObject py_return = std::move(expected_py_return.get());
2822 
2823   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2824     PythonString py_string(PyRefType::Borrowed, py_return.get());
2825     llvm::StringRef return_data(py_string.GetString());
2826     dest.assign(return_data.data(), return_data.size());
2827     return true;
2828   }
2829 
2830   return false;
2831 }
2832 
2833 uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
2834     StructuredData::GenericSP cmd_obj_sp) {
2835   uint32_t result = 0;
2836 
2837   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2838 
2839   static char callee_name[] = "get_flags";
2840 
2841   if (!cmd_obj_sp)
2842     return result;
2843 
2844   PythonObject implementor(PyRefType::Borrowed,
2845                            (PyObject *)cmd_obj_sp->GetValue());
2846 
2847   if (!implementor.IsAllocated())
2848     return result;
2849 
2850   PythonObject pmeth(PyRefType::Owned,
2851                      PyObject_GetAttrString(implementor.get(), callee_name));
2852 
2853   if (PyErr_Occurred())
2854     PyErr_Clear();
2855 
2856   if (!pmeth.IsAllocated())
2857     return result;
2858 
2859   if (PyCallable_Check(pmeth.get()) == 0) {
2860     if (PyErr_Occurred())
2861       PyErr_Clear();
2862     return result;
2863   }
2864 
2865   if (PyErr_Occurred())
2866     PyErr_Clear();
2867 
2868   long long py_return = unwrapOrSetPythonException(
2869       As<long long>(implementor.CallMethod(callee_name)));
2870 
2871   // if it fails, print the error but otherwise go on
2872   if (PyErr_Occurred()) {
2873     PyErr_Print();
2874     PyErr_Clear();
2875   } else {
2876     result = py_return;
2877   }
2878 
2879   return result;
2880 }
2881 
2882 StructuredData::ObjectSP
2883 ScriptInterpreterPythonImpl::GetOptionsForCommandObject(
2884     StructuredData::GenericSP cmd_obj_sp) {
2885   StructuredData::ObjectSP result = {};
2886 
2887   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2888 
2889   static char callee_name[] = "get_options_definition";
2890 
2891   if (!cmd_obj_sp)
2892     return result;
2893 
2894   PythonObject implementor(PyRefType::Borrowed,
2895                            (PyObject *)cmd_obj_sp->GetValue());
2896 
2897   if (!implementor.IsAllocated())
2898     return result;
2899 
2900   PythonObject pmeth(PyRefType::Owned,
2901                      PyObject_GetAttrString(implementor.get(), callee_name));
2902 
2903   if (PyErr_Occurred())
2904     PyErr_Clear();
2905 
2906   if (!pmeth.IsAllocated())
2907     return result;
2908 
2909   if (PyCallable_Check(pmeth.get()) == 0) {
2910     if (PyErr_Occurred())
2911       PyErr_Clear();
2912     return result;
2913   }
2914 
2915   if (PyErr_Occurred())
2916     PyErr_Clear();
2917 
2918   PythonDictionary py_return = unwrapOrSetPythonException(
2919       As<PythonDictionary>(implementor.CallMethod(callee_name)));
2920 
2921   // if it fails, print the error but otherwise go on
2922   if (PyErr_Occurred()) {
2923     PyErr_Print();
2924     PyErr_Clear();
2925     return {};
2926   }
2927     return py_return.CreateStructuredObject();
2928 }
2929 
2930 StructuredData::ObjectSP
2931 ScriptInterpreterPythonImpl::GetArgumentsForCommandObject(
2932     StructuredData::GenericSP cmd_obj_sp) {
2933   StructuredData::ObjectSP result = {};
2934 
2935   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2936 
2937   static char callee_name[] = "get_args_definition";
2938 
2939   if (!cmd_obj_sp)
2940     return result;
2941 
2942   PythonObject implementor(PyRefType::Borrowed,
2943                            (PyObject *)cmd_obj_sp->GetValue());
2944 
2945   if (!implementor.IsAllocated())
2946     return result;
2947 
2948   PythonObject pmeth(PyRefType::Owned,
2949                      PyObject_GetAttrString(implementor.get(), callee_name));
2950 
2951   if (PyErr_Occurred())
2952     PyErr_Clear();
2953 
2954   if (!pmeth.IsAllocated())
2955     return result;
2956 
2957   if (PyCallable_Check(pmeth.get()) == 0) {
2958     if (PyErr_Occurred())
2959       PyErr_Clear();
2960     return result;
2961   }
2962 
2963   if (PyErr_Occurred())
2964     PyErr_Clear();
2965 
2966   PythonList py_return = unwrapOrSetPythonException(
2967       As<PythonList>(implementor.CallMethod(callee_name)));
2968 
2969   // if it fails, print the error but otherwise go on
2970   if (PyErr_Occurred()) {
2971     PyErr_Print();
2972     PyErr_Clear();
2973     return {};
2974   }
2975     return py_return.CreateStructuredObject();
2976 }
2977 
2978 void
2979 ScriptInterpreterPythonImpl::OptionParsingStartedForCommandObject(
2980     StructuredData::GenericSP cmd_obj_sp) {
2981 
2982   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2983 
2984   static char callee_name[] = "option_parsing_started";
2985 
2986   if (!cmd_obj_sp)
2987     return ;
2988 
2989   PythonObject implementor(PyRefType::Borrowed,
2990                            (PyObject *)cmd_obj_sp->GetValue());
2991 
2992   if (!implementor.IsAllocated())
2993     return;
2994 
2995   PythonObject pmeth(PyRefType::Owned,
2996                      PyObject_GetAttrString(implementor.get(), callee_name));
2997 
2998   if (PyErr_Occurred())
2999     PyErr_Clear();
3000 
3001   if (!pmeth.IsAllocated())
3002     return;
3003 
3004   if (PyCallable_Check(pmeth.get()) == 0) {
3005     if (PyErr_Occurred())
3006       PyErr_Clear();
3007     return;
3008   }
3009 
3010   if (PyErr_Occurred())
3011     PyErr_Clear();
3012 
3013   // option_parsing_starting doesn't return anything, ignore anything but
3014   // python errors.
3015   unwrapOrSetPythonException(
3016       As<bool>(implementor.CallMethod(callee_name)));
3017 
3018   // if it fails, print the error but otherwise go on
3019   if (PyErr_Occurred()) {
3020     PyErr_Print();
3021     PyErr_Clear();
3022     return;
3023   }
3024 }
3025 
3026 bool
3027 ScriptInterpreterPythonImpl::SetOptionValueForCommandObject(
3028     StructuredData::GenericSP cmd_obj_sp, ExecutionContext *exe_ctx,
3029     llvm::StringRef long_option, llvm::StringRef value) {
3030   StructuredData::ObjectSP result = {};
3031 
3032   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3033 
3034   static char callee_name[] = "set_option_value";
3035 
3036   if (!cmd_obj_sp)
3037     return false;
3038 
3039   PythonObject implementor(PyRefType::Borrowed,
3040                            (PyObject *)cmd_obj_sp->GetValue());
3041 
3042   if (!implementor.IsAllocated())
3043     return false;
3044 
3045   PythonObject pmeth(PyRefType::Owned,
3046                      PyObject_GetAttrString(implementor.get(), callee_name));
3047 
3048   if (PyErr_Occurred())
3049     PyErr_Clear();
3050 
3051   if (!pmeth.IsAllocated())
3052     return false;
3053 
3054   if (PyCallable_Check(pmeth.get()) == 0) {
3055     if (PyErr_Occurred())
3056       PyErr_Clear();
3057     return false;
3058   }
3059 
3060   if (PyErr_Occurred())
3061     PyErr_Clear();
3062 
3063   lldb::ExecutionContextRefSP exe_ctx_ref_sp;
3064   if (exe_ctx)
3065     exe_ctx_ref_sp.reset(new ExecutionContextRef(exe_ctx));
3066   PythonObject ctx_ref_obj = SWIGBridge::ToSWIGWrapper(exe_ctx_ref_sp);
3067 
3068   bool py_return = unwrapOrSetPythonException(
3069       As<bool>(implementor.CallMethod(callee_name, ctx_ref_obj, long_option.str().c_str(),
3070                                       value.str().c_str())));
3071 
3072   // if it fails, print the error but otherwise go on
3073   if (PyErr_Occurred()) {
3074     PyErr_Print();
3075     PyErr_Clear();
3076     return false;
3077   }
3078   return py_return;
3079 }
3080 
3081 bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3082     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
3083   dest.clear();
3084 
3085   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3086 
3087   if (!cmd_obj_sp)
3088     return false;
3089 
3090   PythonObject implementor(PyRefType::Borrowed,
3091                            (PyObject *)cmd_obj_sp->GetValue());
3092 
3093   if (!implementor.IsAllocated())
3094     return false;
3095 
3096   llvm::Expected<PythonObject> expected_py_return =
3097       implementor.CallMethod("get_long_help");
3098 
3099   if (!expected_py_return) {
3100     llvm::consumeError(expected_py_return.takeError());
3101     return false;
3102   }
3103 
3104   PythonObject py_return = std::move(expected_py_return.get());
3105 
3106   bool got_string = false;
3107   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3108     PythonString str(PyRefType::Borrowed, py_return.get());
3109     llvm::StringRef str_data(str.GetString());
3110     dest.assign(str_data.data(), str_data.size());
3111     got_string = true;
3112   }
3113 
3114   return got_string;
3115 }
3116 
3117 std::unique_ptr<ScriptInterpreterLocker>
3118 ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3119   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3120       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3121       Locker::FreeLock | Locker::TearDownSession));
3122   return py_lock;
3123 }
3124 
3125 void ScriptInterpreterPythonImpl::Initialize() {
3126   LLDB_SCOPED_TIMER();
3127 
3128   // RAII-based initialization which correctly handles multiple-initialization,
3129   // version- specific differences among Python 2 and Python 3, and saving and
3130   // restoring various other pieces of state that can get mucked with during
3131   // initialization.
3132   InitializePythonRAII initialize_guard;
3133 
3134   LLDBSwigPyInit();
3135 
3136   // Update the path python uses to search for modules to include the current
3137   // directory.
3138 
3139   PyRun_SimpleString("import sys");
3140   AddToSysPath(AddLocation::End, ".");
3141 
3142   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
3143   // that use a backslash as the path separator, this will result in executing
3144   // python code containing paths with unescaped backslashes.  But Python also
3145   // accepts forward slashes, so to make life easier we just use that.
3146   if (FileSpec file_spec = GetPythonDir())
3147     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3148   if (FileSpec file_spec = HostInfo::GetShlibDir())
3149     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3150 
3151   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3152                      "lldb.embedded_interpreter; from "
3153                      "lldb.embedded_interpreter import run_python_interpreter; "
3154                      "from lldb.embedded_interpreter import run_one_line");
3155 
3156 #if LLDB_USE_PYTHON_SET_INTERRUPT
3157   // Python will not just overwrite its internal SIGINT handler but also the
3158   // one from the process. Backup the current SIGINT handler to prevent that
3159   // Python deletes it.
3160   RestoreSignalHandlerScope save_sigint(SIGINT);
3161 
3162   // Setup a default SIGINT signal handler that works the same way as the
3163   // normal Python REPL signal handler which raises a KeyboardInterrupt.
3164   // Also make sure to not pollute the user's REPL with the signal module nor
3165   // our utility function.
3166   PyRun_SimpleString("def lldb_setup_sigint_handler():\n"
3167                      "  import signal;\n"
3168                      "  def signal_handler(sig, frame):\n"
3169                      "    raise KeyboardInterrupt()\n"
3170                      "  signal.signal(signal.SIGINT, signal_handler);\n"
3171                      "lldb_setup_sigint_handler();\n"
3172                      "del lldb_setup_sigint_handler\n");
3173 #endif
3174 }
3175 
3176 void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3177                                                std::string path) {
3178   std::string path_copy;
3179 
3180   std::string statement;
3181   if (location == AddLocation::Beginning) {
3182     statement.assign("sys.path.insert(0,\"");
3183     statement.append(path);
3184     statement.append("\")");
3185   } else {
3186     statement.assign("sys.path.append(\"");
3187     statement.append(path);
3188     statement.append("\")");
3189   }
3190   PyRun_SimpleString(statement.c_str());
3191 }
3192 
3193 // We are intentionally NOT calling Py_Finalize here (this would be the logical
3194 // place to call it).  Calling Py_Finalize here causes test suite runs to seg
3195 // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
3196 // be called 'at_exit'.  When the test suite Python harness finishes up, it
3197 // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3198 // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3199 // which calls ScriptInterpreter::Terminate, which calls
3200 // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
3201 // end up with Py_Finalize being called from within Py_Finalize, which results
3202 // in a seg fault. Since this function only gets called when lldb is shutting
3203 // down and going away anyway, the fact that we don't actually call Py_Finalize
3204 // should not cause any problems (everything should shut down/go away anyway
3205 // when the process exits).
3206 //
3207 // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3208 
3209 #endif
3210