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