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