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