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