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