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