xref: /llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp (revision d6c062bce1e499f52500cc759a7c0846dd178cda)
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     llvm::StringRef command, CommandReturnObject *result,
755     const ExecuteScriptOptions &options) {
756   std::string command_str = command.str();
757 
758   if (!m_valid_session)
759     return false;
760 
761   if (!command.empty()) {
762     // We want to call run_one_line, passing in the dictionary and the command
763     // string.  We cannot do this through PyRun_SimpleString here because the
764     // command string may contain escaped characters, and putting it inside
765     // another string to pass to PyRun_SimpleString messes up the escaping.  So
766     // we use the following more complicated method to pass the command string
767     // directly down to Python.
768     Debugger &debugger = m_interpreter.GetDebugger();
769 
770     StreamFileSP input_file_sp;
771     StreamFileSP output_file_sp;
772     StreamFileSP error_file_sp;
773     Communication output_comm(
774         "lldb.ScriptInterpreterPython.ExecuteOneLine.comm");
775     bool join_read_thread = false;
776     if (options.GetEnableIO()) {
777       if (result) {
778         input_file_sp = debugger.GetInputFile();
779         // Set output to a temporary file so we can forward the results on to
780         // the result object
781 
782         Pipe pipe;
783         Status pipe_result = pipe.CreateNew(false);
784         if (pipe_result.Success()) {
785 #if defined(_WIN32)
786           lldb::file_t read_file = pipe.GetReadNativeHandle();
787           pipe.ReleaseReadFileDescriptor();
788           std::unique_ptr<ConnectionGenericFile> conn_ap(
789               new ConnectionGenericFile(read_file, true));
790 #else
791           std::unique_ptr<ConnectionFileDescriptor> conn_ap(
792               new ConnectionFileDescriptor(pipe.ReleaseReadFileDescriptor(),
793                                            true));
794 #endif
795           if (conn_ap->IsConnected()) {
796             output_comm.SetConnection(conn_ap.release());
797             output_comm.SetReadThreadBytesReceivedCallback(
798                 ReadThreadBytesReceived, &result->GetOutputStream());
799             output_comm.StartReadThread();
800             join_read_thread = true;
801             FILE *outfile_handle =
802                 fdopen(pipe.ReleaseWriteFileDescriptor(), "w");
803             output_file_sp.reset(new StreamFile(outfile_handle, true));
804             error_file_sp = output_file_sp;
805             if (outfile_handle)
806               ::setbuf(outfile_handle, nullptr);
807 
808             result->SetImmediateOutputFile(
809                 debugger.GetOutputFile()->GetFile().GetStream());
810             result->SetImmediateErrorFile(
811                 debugger.GetErrorFile()->GetFile().GetStream());
812           }
813         }
814       }
815       if (!input_file_sp || !output_file_sp || !error_file_sp)
816         debugger.AdoptTopIOHandlerFilesIfInvalid(input_file_sp, output_file_sp,
817                                                  error_file_sp);
818     } else {
819       input_file_sp.reset(new StreamFile());
820       input_file_sp->GetFile().Open(FileSystem::DEV_NULL,
821                                     File::eOpenOptionRead);
822       output_file_sp.reset(new StreamFile());
823       output_file_sp->GetFile().Open(FileSystem::DEV_NULL,
824                                      File::eOpenOptionWrite);
825       error_file_sp = output_file_sp;
826     }
827 
828     FILE *in_file = input_file_sp->GetFile().GetStream();
829     FILE *out_file = output_file_sp->GetFile().GetStream();
830     FILE *err_file = error_file_sp->GetFile().GetStream();
831     bool success = false;
832     {
833       // WARNING!  It's imperative that this RAII scope be as tight as
834       // possible. In particular, the scope must end *before* we try to join
835       // the read thread.  The reason for this is that a pre-requisite for
836       // joining the read thread is that we close the write handle (to break
837       // the pipe and cause it to wake up and exit).  But acquiring the GIL as
838       // below will redirect Python's stdio to use this same handle.  If we
839       // close the handle while Python is still using it, bad things will
840       // happen.
841       Locker locker(
842           this,
843           ScriptInterpreterPython::Locker::AcquireLock |
844               ScriptInterpreterPython::Locker::InitSession |
845               (options.GetSetLLDBGlobals()
846                    ? ScriptInterpreterPython::Locker::InitGlobals
847                    : 0) |
848               ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
849           ScriptInterpreterPython::Locker::FreeAcquiredLock |
850               ScriptInterpreterPython::Locker::TearDownSession,
851           in_file, out_file, err_file);
852 
853       // Find the correct script interpreter dictionary in the main module.
854       PythonDictionary &session_dict = GetSessionDictionary();
855       if (session_dict.IsValid()) {
856         if (GetEmbeddedInterpreterModuleObjects()) {
857           if (PyCallable_Check(m_run_one_line_function.get())) {
858             PythonObject pargs(
859                 PyRefType::Owned,
860                 Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
861             if (pargs.IsValid()) {
862               PythonObject return_value(
863                   PyRefType::Owned,
864                   PyObject_CallObject(m_run_one_line_function.get(),
865                                       pargs.get()));
866               if (return_value.IsValid())
867                 success = true;
868               else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
869                 PyErr_Print();
870                 PyErr_Clear();
871               }
872             }
873           }
874         }
875       }
876 
877       // Flush our output and error file handles
878       ::fflush(out_file);
879       if (out_file != err_file)
880         ::fflush(err_file);
881     }
882 
883     if (join_read_thread) {
884       // Close the write end of the pipe since we are done with our one line
885       // script. This should cause the read thread that output_comm is using to
886       // exit
887       output_file_sp->GetFile().Close();
888       // The close above should cause this thread to exit when it gets to the
889       // end of file, so let it get all its data
890       output_comm.JoinReadThread();
891       // Now we can close the read end of the pipe
892       output_comm.Disconnect();
893     }
894 
895     if (success)
896       return true;
897 
898     // The one-liner failed.  Append the error message.
899     if (result) {
900       result->AppendErrorWithFormat(
901           "python failed attempting to evaluate '%s'\n", command_str.c_str());
902     }
903     return false;
904   }
905 
906   if (result)
907     result->AppendError("empty command passed to python\n");
908   return false;
909 }
910 
911 class IOHandlerPythonInterpreter : public IOHandler {
912 public:
913   IOHandlerPythonInterpreter(Debugger &debugger,
914                              ScriptInterpreterPython *python)
915       : IOHandler(debugger, IOHandler::Type::PythonInterpreter),
916         m_python(python) {}
917 
918   ~IOHandlerPythonInterpreter() override {}
919 
920   ConstString GetControlSequence(char ch) override {
921     if (ch == 'd')
922       return ConstString("quit()\n");
923     return ConstString();
924   }
925 
926   void Run() override {
927     if (m_python) {
928       int stdin_fd = GetInputFD();
929       if (stdin_fd >= 0) {
930         Terminal terminal(stdin_fd);
931         TerminalState terminal_state;
932         const bool is_a_tty = terminal.IsATerminal();
933 
934         if (is_a_tty) {
935           terminal_state.Save(stdin_fd, false);
936           terminal.SetCanonical(false);
937           terminal.SetEcho(true);
938         }
939 
940         ScriptInterpreterPython::Locker locker(
941             m_python, ScriptInterpreterPython::Locker::AcquireLock |
942                           ScriptInterpreterPython::Locker::InitSession |
943                           ScriptInterpreterPython::Locker::InitGlobals,
944             ScriptInterpreterPython::Locker::FreeAcquiredLock |
945                 ScriptInterpreterPython::Locker::TearDownSession);
946 
947         // The following call drops into the embedded interpreter loop and
948         // stays there until the user chooses to exit from the Python
949         // interpreter. This embedded interpreter will, as any Python code that
950         // performs I/O, unlock the GIL before a system call that can hang, and
951         // lock it when the syscall has returned.
952 
953         // We need to surround the call to the embedded interpreter with calls
954         // to PyGILState_Ensure and PyGILState_Release (using the Locker
955         // above). This is because Python has a global lock which must be held
956         // whenever we want to touch any Python objects. Otherwise, if the user
957         // calls Python code, the interpreter state will be off, and things
958         // could hang (it's happened before).
959 
960         StreamString run_string;
961         run_string.Printf("run_python_interpreter (%s)",
962                           m_python->GetDictionaryName());
963         PyRun_SimpleString(run_string.GetData());
964 
965         if (is_a_tty)
966           terminal_state.Restore();
967       }
968     }
969     SetIsDone(true);
970   }
971 
972   void Cancel() override {}
973 
974   bool Interrupt() override { return m_python->Interrupt(); }
975 
976   void GotEOF() override {}
977 
978 protected:
979   ScriptInterpreterPython *m_python;
980 };
981 
982 void ScriptInterpreterPython::ExecuteInterpreterLoop() {
983   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
984   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
985 
986   Debugger &debugger = GetCommandInterpreter().GetDebugger();
987 
988   // At the moment, the only time the debugger does not have an input file
989   // handle is when this is called directly from Python, in which case it is
990   // both dangerous and unnecessary (not to mention confusing) to try to embed
991   // a running interpreter loop inside the already running Python interpreter
992   // loop, so we won't do it.
993 
994   if (!debugger.GetInputFile()->GetFile().IsValid())
995     return;
996 
997   IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
998   if (io_handler_sp) {
999     debugger.PushIOHandler(io_handler_sp);
1000   }
1001 }
1002 
1003 bool ScriptInterpreterPython::Interrupt() {
1004   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
1005 
1006   if (IsExecutingPython()) {
1007     PyThreadState *state = PyThreadState_GET();
1008     if (!state)
1009       state = GetThreadState();
1010     if (state) {
1011       long tid = state->thread_id;
1012       PyThreadState_Swap(state);
1013       int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
1014       if (log)
1015         log->Printf("ScriptInterpreterPython::Interrupt() sending "
1016                     "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
1017                     tid, num_threads);
1018       return true;
1019     }
1020   }
1021   if (log)
1022     log->Printf("ScriptInterpreterPython::Interrupt() python code not running, "
1023                 "can't interrupt");
1024   return false;
1025 }
1026 bool ScriptInterpreterPython::ExecuteOneLineWithReturn(
1027     llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
1028     void *ret_value, const ExecuteScriptOptions &options) {
1029 
1030   Locker locker(this, ScriptInterpreterPython::Locker::AcquireLock |
1031                           ScriptInterpreterPython::Locker::InitSession |
1032                           (options.GetSetLLDBGlobals()
1033                                ? ScriptInterpreterPython::Locker::InitGlobals
1034                                : 0) |
1035                           Locker::NoSTDIN,
1036                 ScriptInterpreterPython::Locker::FreeAcquiredLock |
1037                     ScriptInterpreterPython::Locker::TearDownSession);
1038 
1039   PythonObject py_return;
1040   PythonObject &main_module = GetMainModule();
1041   PythonDictionary globals(PyRefType::Borrowed,
1042                            PyModule_GetDict(main_module.get()));
1043   PythonObject py_error;
1044   bool ret_success = false;
1045   int success;
1046 
1047   PythonDictionary locals = GetSessionDictionary();
1048 
1049   if (!locals.IsValid()) {
1050     locals.Reset(
1051         PyRefType::Owned,
1052         PyObject_GetAttrString(globals.get(), m_dictionary_name.c_str()));
1053   }
1054 
1055   if (!locals.IsValid())
1056     locals = globals;
1057 
1058   py_error.Reset(PyRefType::Borrowed, PyErr_Occurred());
1059   if (py_error.IsValid())
1060     PyErr_Clear();
1061 
1062   std::string as_string = in_string.str();
1063   { // scope for PythonInputReaderManager
1064     // PythonInputReaderManager py_input(options.GetEnableIO() ? this : NULL);
1065     py_return.Reset(PyRefType::Owned,
1066                     PyRun_String(as_string.c_str(), Py_eval_input,
1067                                  globals.get(), locals.get()));
1068     if (!py_return.IsValid()) {
1069       py_error.Reset(PyRefType::Borrowed, PyErr_Occurred());
1070       if (py_error.IsValid())
1071         PyErr_Clear();
1072 
1073       py_return.Reset(PyRefType::Owned,
1074                       PyRun_String(as_string.c_str(), Py_single_input,
1075                                    globals.get(), locals.get()));
1076     }
1077   }
1078 
1079   if (py_return.IsValid()) {
1080     switch (return_type) {
1081     case eScriptReturnTypeCharPtr: // "char *"
1082     {
1083       const char format[3] = "s#";
1084       success = PyArg_Parse(py_return.get(), format, (char **)ret_value);
1085       break;
1086     }
1087     case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
1088                                          // Py_None
1089     {
1090       const char format[3] = "z";
1091       success = PyArg_Parse(py_return.get(), format, (char **)ret_value);
1092       break;
1093     }
1094     case eScriptReturnTypeBool: {
1095       const char format[2] = "b";
1096       success = PyArg_Parse(py_return.get(), format, (bool *)ret_value);
1097       break;
1098     }
1099     case eScriptReturnTypeShortInt: {
1100       const char format[2] = "h";
1101       success = PyArg_Parse(py_return.get(), format, (short *)ret_value);
1102       break;
1103     }
1104     case eScriptReturnTypeShortIntUnsigned: {
1105       const char format[2] = "H";
1106       success =
1107           PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
1108       break;
1109     }
1110     case eScriptReturnTypeInt: {
1111       const char format[2] = "i";
1112       success = PyArg_Parse(py_return.get(), format, (int *)ret_value);
1113       break;
1114     }
1115     case eScriptReturnTypeIntUnsigned: {
1116       const char format[2] = "I";
1117       success = PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
1118       break;
1119     }
1120     case eScriptReturnTypeLongInt: {
1121       const char format[2] = "l";
1122       success = PyArg_Parse(py_return.get(), format, (long *)ret_value);
1123       break;
1124     }
1125     case eScriptReturnTypeLongIntUnsigned: {
1126       const char format[2] = "k";
1127       success =
1128           PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
1129       break;
1130     }
1131     case eScriptReturnTypeLongLong: {
1132       const char format[2] = "L";
1133       success = PyArg_Parse(py_return.get(), format, (long long *)ret_value);
1134       break;
1135     }
1136     case eScriptReturnTypeLongLongUnsigned: {
1137       const char format[2] = "K";
1138       success =
1139           PyArg_Parse(py_return.get(), format, (unsigned long long *)ret_value);
1140       break;
1141     }
1142     case eScriptReturnTypeFloat: {
1143       const char format[2] = "f";
1144       success = PyArg_Parse(py_return.get(), format, (float *)ret_value);
1145       break;
1146     }
1147     case eScriptReturnTypeDouble: {
1148       const char format[2] = "d";
1149       success = PyArg_Parse(py_return.get(), format, (double *)ret_value);
1150       break;
1151     }
1152     case eScriptReturnTypeChar: {
1153       const char format[2] = "c";
1154       success = PyArg_Parse(py_return.get(), format, (char *)ret_value);
1155       break;
1156     }
1157     case eScriptReturnTypeOpaqueObject: {
1158       success = true;
1159       PyObject *saved_value = py_return.get();
1160       Py_XINCREF(saved_value);
1161       *((PyObject **)ret_value) = saved_value;
1162       break;
1163     }
1164     }
1165 
1166     if (success)
1167       ret_success = true;
1168     else
1169       ret_success = false;
1170   }
1171 
1172   py_error.Reset(PyRefType::Borrowed, PyErr_Occurred());
1173   if (py_error.IsValid()) {
1174     ret_success = false;
1175     if (options.GetMaskoutErrors()) {
1176       if (PyErr_GivenExceptionMatches(py_error.get(), PyExc_SyntaxError))
1177         PyErr_Print();
1178       PyErr_Clear();
1179     }
1180   }
1181 
1182   return ret_success;
1183 }
1184 
1185 Status ScriptInterpreterPython::ExecuteMultipleLines(
1186     const char *in_string, const ExecuteScriptOptions &options) {
1187   Status error;
1188 
1189   Locker locker(this, ScriptInterpreterPython::Locker::AcquireLock |
1190                           ScriptInterpreterPython::Locker::InitSession |
1191                           (options.GetSetLLDBGlobals()
1192                                ? ScriptInterpreterPython::Locker::InitGlobals
1193                                : 0) |
1194                           Locker::NoSTDIN,
1195                 ScriptInterpreterPython::Locker::FreeAcquiredLock |
1196                     ScriptInterpreterPython::Locker::TearDownSession);
1197 
1198   PythonObject return_value;
1199   PythonObject &main_module = GetMainModule();
1200   PythonDictionary globals(PyRefType::Borrowed,
1201                            PyModule_GetDict(main_module.get()));
1202   PythonObject py_error;
1203 
1204   PythonDictionary locals = GetSessionDictionary();
1205 
1206   if (!locals.IsValid())
1207     locals.Reset(
1208         PyRefType::Owned,
1209         PyObject_GetAttrString(globals.get(), m_dictionary_name.c_str()));
1210 
1211   if (!locals.IsValid())
1212     locals = globals;
1213 
1214   py_error.Reset(PyRefType::Borrowed, PyErr_Occurred());
1215   if (py_error.IsValid())
1216     PyErr_Clear();
1217 
1218   if (in_string != nullptr) {
1219     PythonObject code_object;
1220     code_object.Reset(PyRefType::Owned,
1221                       Py_CompileString(in_string, "temp.py", Py_file_input));
1222 
1223     if (code_object.IsValid()) {
1224 // In Python 2.x, PyEval_EvalCode takes a PyCodeObject, but in Python 3.x, it
1225 // takes a PyObject.  They are convertible (hence the function
1226 // PyCode_Check(PyObject*), so we have to do the cast for Python 2.x
1227 #if PY_MAJOR_VERSION >= 3
1228       PyObject *py_code_obj = code_object.get();
1229 #else
1230       PyCodeObject *py_code_obj =
1231           reinterpret_cast<PyCodeObject *>(code_object.get());
1232 #endif
1233       return_value.Reset(
1234           PyRefType::Owned,
1235           PyEval_EvalCode(py_code_obj, globals.get(), locals.get()));
1236     }
1237   }
1238 
1239   PythonExceptionState exception_state(!options.GetMaskoutErrors());
1240   if (exception_state.IsError())
1241     error.SetErrorString(exception_state.Format().c_str());
1242 
1243   return error;
1244 }
1245 
1246 void ScriptInterpreterPython::CollectDataForBreakpointCommandCallback(
1247     std::vector<BreakpointOptions *> &bp_options_vec,
1248     CommandReturnObject &result) {
1249   m_active_io_handler = eIOHandlerBreakpoint;
1250   m_interpreter.GetPythonCommandsFromIOHandler("    ", *this, true,
1251                                                &bp_options_vec);
1252 }
1253 
1254 void ScriptInterpreterPython::CollectDataForWatchpointCommandCallback(
1255     WatchpointOptions *wp_options, CommandReturnObject &result) {
1256   m_active_io_handler = eIOHandlerWatchpoint;
1257   m_interpreter.GetPythonCommandsFromIOHandler("    ", *this, true, wp_options);
1258 }
1259 
1260 void ScriptInterpreterPython::SetBreakpointCommandCallbackFunction(
1261     BreakpointOptions *bp_options, const char *function_name) {
1262   // For now just cons up a oneliner that calls the provided function.
1263   std::string oneliner("return ");
1264   oneliner += function_name;
1265   oneliner += "(frame, bp_loc, internal_dict)";
1266   m_interpreter.GetScriptInterpreter()->SetBreakpointCommandCallback(
1267       bp_options, oneliner.c_str());
1268 }
1269 
1270 Status ScriptInterpreterPython::SetBreakpointCommandCallback(
1271     BreakpointOptions *bp_options,
1272     std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
1273   Status error;
1274   error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1275                                                 cmd_data_up->script_source);
1276   if (error.Fail()) {
1277     return error;
1278   }
1279   auto baton_sp =
1280       std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1281   bp_options->SetCallback(ScriptInterpreterPython::BreakpointCallbackFunction,
1282                           baton_sp);
1283   return error;
1284 }
1285 
1286 // Set a Python one-liner as the callback for the breakpoint.
1287 Status ScriptInterpreterPython::SetBreakpointCommandCallback(
1288     BreakpointOptions *bp_options, const char *command_body_text) {
1289   auto data_ap = llvm::make_unique<CommandDataPython>();
1290 
1291   // Split the command_body_text into lines, and pass that to
1292   // GenerateBreakpointCommandCallbackData.  That will wrap the body in an
1293   // auto-generated function, and return the function name in script_source.
1294   // That is what the callback will actually invoke.
1295 
1296   data_ap->user_source.SplitIntoLines(command_body_text);
1297   Status error = GenerateBreakpointCommandCallbackData(data_ap->user_source,
1298                                                        data_ap->script_source);
1299   if (error.Success()) {
1300     auto baton_sp =
1301         std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_ap));
1302     bp_options->SetCallback(ScriptInterpreterPython::BreakpointCallbackFunction,
1303                             baton_sp);
1304     return error;
1305   } else
1306     return error;
1307 }
1308 
1309 // Set a Python one-liner as the callback for the watchpoint.
1310 void ScriptInterpreterPython::SetWatchpointCommandCallback(
1311     WatchpointOptions *wp_options, const char *oneliner) {
1312   auto data_ap = llvm::make_unique<WatchpointOptions::CommandData>();
1313 
1314   // It's necessary to set both user_source and script_source to the oneliner.
1315   // The former is used to generate callback description (as in watchpoint
1316   // command list) while the latter is used for Python to interpret during the
1317   // actual callback.
1318 
1319   data_ap->user_source.AppendString(oneliner);
1320   data_ap->script_source.assign(oneliner);
1321 
1322   if (GenerateWatchpointCommandCallbackData(data_ap->user_source,
1323                                             data_ap->script_source)) {
1324     auto baton_sp =
1325         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_ap));
1326     wp_options->SetCallback(ScriptInterpreterPython::WatchpointCallbackFunction,
1327                             baton_sp);
1328   }
1329 
1330   return;
1331 }
1332 
1333 Status ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter(
1334     StringList &function_def) {
1335   // Convert StringList to one long, newline delimited, const char *.
1336   std::string function_def_string(function_def.CopyList());
1337 
1338   Status error = ExecuteMultipleLines(
1339       function_def_string.c_str(),
1340       ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false));
1341   return error;
1342 }
1343 
1344 Status ScriptInterpreterPython::GenerateFunction(const char *signature,
1345                                                  const StringList &input) {
1346   Status error;
1347   int num_lines = input.GetSize();
1348   if (num_lines == 0) {
1349     error.SetErrorString("No input data.");
1350     return error;
1351   }
1352 
1353   if (!signature || *signature == 0) {
1354     error.SetErrorString("No output function name.");
1355     return error;
1356   }
1357 
1358   StreamString sstr;
1359   StringList auto_generated_function;
1360   auto_generated_function.AppendString(signature);
1361   auto_generated_function.AppendString(
1362       "     global_dict = globals()"); // Grab the global dictionary
1363   auto_generated_function.AppendString(
1364       "     new_keys = internal_dict.keys()"); // Make a list of keys in the
1365                                                // session dict
1366   auto_generated_function.AppendString(
1367       "     old_keys = global_dict.keys()"); // Save list of keys in global dict
1368   auto_generated_function.AppendString(
1369       "     global_dict.update (internal_dict)"); // Add the session dictionary
1370                                                   // to the
1371   // global dictionary.
1372 
1373   // Wrap everything up inside the function, increasing the indentation.
1374 
1375   auto_generated_function.AppendString("     if True:");
1376   for (int i = 0; i < num_lines; ++i) {
1377     sstr.Clear();
1378     sstr.Printf("       %s", input.GetStringAtIndex(i));
1379     auto_generated_function.AppendString(sstr.GetData());
1380   }
1381   auto_generated_function.AppendString(
1382       "     for key in new_keys:"); // Iterate over all the keys from session
1383                                     // dict
1384   auto_generated_function.AppendString(
1385       "         internal_dict[key] = global_dict[key]"); // Update session dict
1386                                                          // values
1387   auto_generated_function.AppendString(
1388       "         if key not in old_keys:"); // If key was not originally in
1389                                            // global dict
1390   auto_generated_function.AppendString(
1391       "             del global_dict[key]"); //  ...then remove key/value from
1392                                             //  global dict
1393 
1394   // Verify that the results are valid Python.
1395 
1396   error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
1397 
1398   return error;
1399 }
1400 
1401 bool ScriptInterpreterPython::GenerateTypeScriptFunction(
1402     StringList &user_input, std::string &output, const void *name_token) {
1403   static uint32_t num_created_functions = 0;
1404   user_input.RemoveBlankLines();
1405   StreamString sstr;
1406 
1407   // Check to see if we have any data; if not, just return.
1408   if (user_input.GetSize() == 0)
1409     return false;
1410 
1411   // Take what the user wrote, wrap it all up inside one big auto-generated
1412   // Python function, passing in the ValueObject as parameter to the function.
1413 
1414   std::string auto_generated_function_name(
1415       GenerateUniqueName("lldb_autogen_python_type_print_func",
1416                          num_created_functions, name_token));
1417   sstr.Printf("def %s (valobj, internal_dict):",
1418               auto_generated_function_name.c_str());
1419 
1420   if (!GenerateFunction(sstr.GetData(), user_input).Success())
1421     return false;
1422 
1423   // Store the name of the auto-generated function to be called.
1424   output.assign(auto_generated_function_name);
1425   return true;
1426 }
1427 
1428 bool ScriptInterpreterPython::GenerateScriptAliasFunction(
1429     StringList &user_input, std::string &output) {
1430   static uint32_t num_created_functions = 0;
1431   user_input.RemoveBlankLines();
1432   StreamString sstr;
1433 
1434   // Check to see if we have any data; if not, just return.
1435   if (user_input.GetSize() == 0)
1436     return false;
1437 
1438   std::string auto_generated_function_name(GenerateUniqueName(
1439       "lldb_autogen_python_cmd_alias_func", num_created_functions));
1440 
1441   sstr.Printf("def %s (debugger, args, result, internal_dict):",
1442               auto_generated_function_name.c_str());
1443 
1444   if (!GenerateFunction(sstr.GetData(), user_input).Success())
1445     return false;
1446 
1447   // Store the name of the auto-generated function to be called.
1448   output.assign(auto_generated_function_name);
1449   return true;
1450 }
1451 
1452 bool ScriptInterpreterPython::GenerateTypeSynthClass(StringList &user_input,
1453                                                      std::string &output,
1454                                                      const void *name_token) {
1455   static uint32_t num_created_classes = 0;
1456   user_input.RemoveBlankLines();
1457   int num_lines = user_input.GetSize();
1458   StreamString sstr;
1459 
1460   // Check to see if we have any data; if not, just return.
1461   if (user_input.GetSize() == 0)
1462     return false;
1463 
1464   // Wrap all user input into a Python class
1465 
1466   std::string auto_generated_class_name(GenerateUniqueName(
1467       "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1468 
1469   StringList auto_generated_class;
1470 
1471   // Create the function name & definition string.
1472 
1473   sstr.Printf("class %s:", auto_generated_class_name.c_str());
1474   auto_generated_class.AppendString(sstr.GetString());
1475 
1476   // Wrap everything up inside the class, increasing the indentation. we don't
1477   // need to play any fancy indentation tricks here because there is no
1478   // surrounding code whose indentation we need to honor
1479   for (int i = 0; i < num_lines; ++i) {
1480     sstr.Clear();
1481     sstr.Printf("     %s", user_input.GetStringAtIndex(i));
1482     auto_generated_class.AppendString(sstr.GetString());
1483   }
1484 
1485   // Verify that the results are valid Python. (even though the method is
1486   // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1487   // (TODO: rename that method to ExportDefinitionToInterpreter)
1488   if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
1489     return false;
1490 
1491   // Store the name of the auto-generated class
1492 
1493   output.assign(auto_generated_class_name);
1494   return true;
1495 }
1496 
1497 StructuredData::GenericSP ScriptInterpreterPython::OSPlugin_CreatePluginObject(
1498     const char *class_name, lldb::ProcessSP process_sp) {
1499   if (class_name == nullptr || class_name[0] == '\0')
1500     return StructuredData::GenericSP();
1501 
1502   if (!process_sp)
1503     return StructuredData::GenericSP();
1504 
1505   void *ret_val;
1506 
1507   {
1508     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
1509                    Locker::FreeLock);
1510     ret_val = g_swig_create_os_plugin(class_name, m_dictionary_name.c_str(),
1511                                       process_sp);
1512   }
1513 
1514   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
1515 }
1516 
1517 StructuredData::DictionarySP ScriptInterpreterPython::OSPlugin_RegisterInfo(
1518     StructuredData::ObjectSP os_plugin_object_sp) {
1519   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1520 
1521   static char callee_name[] = "get_register_info";
1522 
1523   if (!os_plugin_object_sp)
1524     return StructuredData::DictionarySP();
1525 
1526   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1527   if (!generic)
1528     return nullptr;
1529 
1530   PythonObject implementor(PyRefType::Borrowed,
1531                            (PyObject *)generic->GetValue());
1532 
1533   if (!implementor.IsAllocated())
1534     return StructuredData::DictionarySP();
1535 
1536   PythonObject pmeth(PyRefType::Owned,
1537                      PyObject_GetAttrString(implementor.get(), callee_name));
1538 
1539   if (PyErr_Occurred())
1540     PyErr_Clear();
1541 
1542   if (!pmeth.IsAllocated())
1543     return StructuredData::DictionarySP();
1544 
1545   if (PyCallable_Check(pmeth.get()) == 0) {
1546     if (PyErr_Occurred())
1547       PyErr_Clear();
1548 
1549     return StructuredData::DictionarySP();
1550   }
1551 
1552   if (PyErr_Occurred())
1553     PyErr_Clear();
1554 
1555   // right now we know this function exists and is callable..
1556   PythonObject py_return(
1557       PyRefType::Owned,
1558       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
1559 
1560   // if it fails, print the error but otherwise go on
1561   if (PyErr_Occurred()) {
1562     PyErr_Print();
1563     PyErr_Clear();
1564   }
1565   if (py_return.get()) {
1566     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1567     return result_dict.CreateStructuredDictionary();
1568   }
1569   return StructuredData::DictionarySP();
1570 }
1571 
1572 StructuredData::ArraySP ScriptInterpreterPython::OSPlugin_ThreadsInfo(
1573     StructuredData::ObjectSP os_plugin_object_sp) {
1574   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1575 
1576   static char callee_name[] = "get_thread_info";
1577 
1578   if (!os_plugin_object_sp)
1579     return StructuredData::ArraySP();
1580 
1581   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1582   if (!generic)
1583     return nullptr;
1584 
1585   PythonObject implementor(PyRefType::Borrowed,
1586                            (PyObject *)generic->GetValue());
1587 
1588   if (!implementor.IsAllocated())
1589     return StructuredData::ArraySP();
1590 
1591   PythonObject pmeth(PyRefType::Owned,
1592                      PyObject_GetAttrString(implementor.get(), callee_name));
1593 
1594   if (PyErr_Occurred())
1595     PyErr_Clear();
1596 
1597   if (!pmeth.IsAllocated())
1598     return StructuredData::ArraySP();
1599 
1600   if (PyCallable_Check(pmeth.get()) == 0) {
1601     if (PyErr_Occurred())
1602       PyErr_Clear();
1603 
1604     return StructuredData::ArraySP();
1605   }
1606 
1607   if (PyErr_Occurred())
1608     PyErr_Clear();
1609 
1610   // right now we know this function exists and is callable..
1611   PythonObject py_return(
1612       PyRefType::Owned,
1613       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
1614 
1615   // if it fails, print the error but otherwise go on
1616   if (PyErr_Occurred()) {
1617     PyErr_Print();
1618     PyErr_Clear();
1619   }
1620 
1621   if (py_return.get()) {
1622     PythonList result_list(PyRefType::Borrowed, py_return.get());
1623     return result_list.CreateStructuredArray();
1624   }
1625   return StructuredData::ArraySP();
1626 }
1627 
1628 // GetPythonValueFormatString provides a system independent type safe way to
1629 // convert a variable's type into a python value format. Python value formats
1630 // are defined in terms of builtin C types and could change from system to as
1631 // the underlying typedef for uint* types, size_t, off_t and other values
1632 // change.
1633 
1634 template <typename T> const char *GetPythonValueFormatString(T t);
1635 template <> const char *GetPythonValueFormatString(char *) { return "s"; }
1636 template <> const char *GetPythonValueFormatString(char) { return "b"; }
1637 template <> const char *GetPythonValueFormatString(unsigned char) {
1638   return "B";
1639 }
1640 template <> const char *GetPythonValueFormatString(short) { return "h"; }
1641 template <> const char *GetPythonValueFormatString(unsigned short) {
1642   return "H";
1643 }
1644 template <> const char *GetPythonValueFormatString(int) { return "i"; }
1645 template <> const char *GetPythonValueFormatString(unsigned int) { return "I"; }
1646 template <> const char *GetPythonValueFormatString(long) { return "l"; }
1647 template <> const char *GetPythonValueFormatString(unsigned long) {
1648   return "k";
1649 }
1650 template <> const char *GetPythonValueFormatString(long long) { return "L"; }
1651 template <> const char *GetPythonValueFormatString(unsigned long long) {
1652   return "K";
1653 }
1654 template <> const char *GetPythonValueFormatString(float t) { return "f"; }
1655 template <> const char *GetPythonValueFormatString(double t) { return "d"; }
1656 
1657 StructuredData::StringSP ScriptInterpreterPython::OSPlugin_RegisterContextData(
1658     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
1659   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1660 
1661   static char callee_name[] = "get_register_data";
1662   static char *param_format =
1663       const_cast<char *>(GetPythonValueFormatString(tid));
1664 
1665   if (!os_plugin_object_sp)
1666     return StructuredData::StringSP();
1667 
1668   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1669   if (!generic)
1670     return nullptr;
1671   PythonObject implementor(PyRefType::Borrowed,
1672                            (PyObject *)generic->GetValue());
1673 
1674   if (!implementor.IsAllocated())
1675     return StructuredData::StringSP();
1676 
1677   PythonObject pmeth(PyRefType::Owned,
1678                      PyObject_GetAttrString(implementor.get(), callee_name));
1679 
1680   if (PyErr_Occurred())
1681     PyErr_Clear();
1682 
1683   if (!pmeth.IsAllocated())
1684     return StructuredData::StringSP();
1685 
1686   if (PyCallable_Check(pmeth.get()) == 0) {
1687     if (PyErr_Occurred())
1688       PyErr_Clear();
1689     return StructuredData::StringSP();
1690   }
1691 
1692   if (PyErr_Occurred())
1693     PyErr_Clear();
1694 
1695   // right now we know this function exists and is callable..
1696   PythonObject py_return(
1697       PyRefType::Owned,
1698       PyObject_CallMethod(implementor.get(), callee_name, param_format, tid));
1699 
1700   // if it fails, print the error but otherwise go on
1701   if (PyErr_Occurred()) {
1702     PyErr_Print();
1703     PyErr_Clear();
1704   }
1705 
1706   if (py_return.get()) {
1707     PythonBytes result(PyRefType::Borrowed, py_return.get());
1708     return result.CreateStructuredString();
1709   }
1710   return StructuredData::StringSP();
1711 }
1712 
1713 StructuredData::DictionarySP ScriptInterpreterPython::OSPlugin_CreateThread(
1714     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
1715     lldb::addr_t context) {
1716   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1717 
1718   static char callee_name[] = "create_thread";
1719   std::string param_format;
1720   param_format += GetPythonValueFormatString(tid);
1721   param_format += GetPythonValueFormatString(context);
1722 
1723   if (!os_plugin_object_sp)
1724     return StructuredData::DictionarySP();
1725 
1726   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1727   if (!generic)
1728     return nullptr;
1729 
1730   PythonObject implementor(PyRefType::Borrowed,
1731                            (PyObject *)generic->GetValue());
1732 
1733   if (!implementor.IsAllocated())
1734     return StructuredData::DictionarySP();
1735 
1736   PythonObject pmeth(PyRefType::Owned,
1737                      PyObject_GetAttrString(implementor.get(), callee_name));
1738 
1739   if (PyErr_Occurred())
1740     PyErr_Clear();
1741 
1742   if (!pmeth.IsAllocated())
1743     return StructuredData::DictionarySP();
1744 
1745   if (PyCallable_Check(pmeth.get()) == 0) {
1746     if (PyErr_Occurred())
1747       PyErr_Clear();
1748     return StructuredData::DictionarySP();
1749   }
1750 
1751   if (PyErr_Occurred())
1752     PyErr_Clear();
1753 
1754   // right now we know this function exists and is callable..
1755   PythonObject py_return(PyRefType::Owned,
1756                          PyObject_CallMethod(implementor.get(), callee_name,
1757                                              &param_format[0], tid, context));
1758 
1759   // if it fails, print the error but otherwise go on
1760   if (PyErr_Occurred()) {
1761     PyErr_Print();
1762     PyErr_Clear();
1763   }
1764 
1765   if (py_return.get()) {
1766     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1767     return result_dict.CreateStructuredDictionary();
1768   }
1769   return StructuredData::DictionarySP();
1770 }
1771 
1772 StructuredData::ObjectSP ScriptInterpreterPython::CreateScriptedThreadPlan(
1773     const char *class_name, lldb::ThreadPlanSP thread_plan_sp) {
1774   if (class_name == nullptr || class_name[0] == '\0')
1775     return StructuredData::ObjectSP();
1776 
1777   if (!thread_plan_sp.get())
1778     return StructuredData::ObjectSP();
1779 
1780   Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
1781   ScriptInterpreter *script_interpreter =
1782       debugger.GetCommandInterpreter().GetScriptInterpreter();
1783   ScriptInterpreterPython *python_interpreter =
1784       static_cast<ScriptInterpreterPython *>(script_interpreter);
1785 
1786   if (!script_interpreter)
1787     return StructuredData::ObjectSP();
1788 
1789   void *ret_val;
1790 
1791   {
1792     Locker py_lock(this,
1793                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1794 
1795     ret_val = g_swig_thread_plan_script(
1796         class_name, python_interpreter->m_dictionary_name.c_str(),
1797         thread_plan_sp);
1798   }
1799 
1800   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
1801 }
1802 
1803 bool ScriptInterpreterPython::ScriptedThreadPlanExplainsStop(
1804     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1805   bool explains_stop = true;
1806   StructuredData::Generic *generic = nullptr;
1807   if (implementor_sp)
1808     generic = implementor_sp->GetAsGeneric();
1809   if (generic) {
1810     Locker py_lock(this,
1811                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1812     explains_stop = g_swig_call_thread_plan(
1813         generic->GetValue(), "explains_stop", event, script_error);
1814     if (script_error)
1815       return true;
1816   }
1817   return explains_stop;
1818 }
1819 
1820 bool ScriptInterpreterPython::ScriptedThreadPlanShouldStop(
1821     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1822   bool should_stop = true;
1823   StructuredData::Generic *generic = nullptr;
1824   if (implementor_sp)
1825     generic = implementor_sp->GetAsGeneric();
1826   if (generic) {
1827     Locker py_lock(this,
1828                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1829     should_stop = g_swig_call_thread_plan(generic->GetValue(), "should_stop",
1830                                           event, script_error);
1831     if (script_error)
1832       return true;
1833   }
1834   return should_stop;
1835 }
1836 
1837 bool ScriptInterpreterPython::ScriptedThreadPlanIsStale(
1838     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1839   bool is_stale = true;
1840   StructuredData::Generic *generic = nullptr;
1841   if (implementor_sp)
1842     generic = implementor_sp->GetAsGeneric();
1843   if (generic) {
1844     Locker py_lock(this,
1845                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1846     is_stale = g_swig_call_thread_plan(generic->GetValue(), "is_stale", nullptr,
1847                                        script_error);
1848     if (script_error)
1849       return true;
1850   }
1851   return is_stale;
1852 }
1853 
1854 lldb::StateType ScriptInterpreterPython::ScriptedThreadPlanGetRunState(
1855     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1856   bool should_step = false;
1857   StructuredData::Generic *generic = nullptr;
1858   if (implementor_sp)
1859     generic = implementor_sp->GetAsGeneric();
1860   if (generic) {
1861     Locker py_lock(this,
1862                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1863     should_step = g_swig_call_thread_plan(generic->GetValue(), "should_step",
1864                                           NULL, script_error);
1865     if (script_error)
1866       should_step = true;
1867   }
1868   if (should_step)
1869     return lldb::eStateStepping;
1870   else
1871     return lldb::eStateRunning;
1872 }
1873 
1874 StructuredData::ObjectSP
1875 ScriptInterpreterPython::LoadPluginModule(const FileSpec &file_spec,
1876                                           lldb_private::Status &error) {
1877   if (!file_spec.Exists()) {
1878     error.SetErrorString("no such file");
1879     return StructuredData::ObjectSP();
1880   }
1881 
1882   StructuredData::ObjectSP module_sp;
1883 
1884   if (LoadScriptingModule(file_spec.GetPath().c_str(), true, true, error,
1885                           &module_sp))
1886     return module_sp;
1887 
1888   return StructuredData::ObjectSP();
1889 }
1890 
1891 StructuredData::DictionarySP ScriptInterpreterPython::GetDynamicSettings(
1892     StructuredData::ObjectSP plugin_module_sp, Target *target,
1893     const char *setting_name, lldb_private::Status &error) {
1894   if (!plugin_module_sp || !target || !setting_name || !setting_name[0] ||
1895       !g_swig_plugin_get)
1896     return StructuredData::DictionarySP();
1897   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
1898   if (!generic)
1899     return StructuredData::DictionarySP();
1900 
1901   PythonObject reply_pyobj;
1902   Locker py_lock(this,
1903                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1904   TargetSP target_sp(target->shared_from_this());
1905   reply_pyobj.Reset(PyRefType::Owned,
1906                     (PyObject *)g_swig_plugin_get(generic->GetValue(),
1907                                                   setting_name, target_sp));
1908 
1909   PythonDictionary py_dict(PyRefType::Borrowed, reply_pyobj.get());
1910   return py_dict.CreateStructuredDictionary();
1911 }
1912 
1913 StructuredData::ObjectSP
1914 ScriptInterpreterPython::CreateSyntheticScriptedProvider(
1915     const char *class_name, lldb::ValueObjectSP valobj) {
1916   if (class_name == nullptr || class_name[0] == '\0')
1917     return StructuredData::ObjectSP();
1918 
1919   if (!valobj.get())
1920     return StructuredData::ObjectSP();
1921 
1922   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
1923   Target *target = exe_ctx.GetTargetPtr();
1924 
1925   if (!target)
1926     return StructuredData::ObjectSP();
1927 
1928   Debugger &debugger = target->GetDebugger();
1929   ScriptInterpreter *script_interpreter =
1930       debugger.GetCommandInterpreter().GetScriptInterpreter();
1931   ScriptInterpreterPython *python_interpreter =
1932       (ScriptInterpreterPython *)script_interpreter;
1933 
1934   if (!script_interpreter)
1935     return StructuredData::ObjectSP();
1936 
1937   void *ret_val = nullptr;
1938 
1939   {
1940     Locker py_lock(this,
1941                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1942     ret_val = g_swig_synthetic_script(
1943         class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
1944   }
1945 
1946   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
1947 }
1948 
1949 StructuredData::GenericSP
1950 ScriptInterpreterPython::CreateScriptCommandObject(const char *class_name) {
1951   DebuggerSP debugger_sp(
1952       GetCommandInterpreter().GetDebugger().shared_from_this());
1953 
1954   if (class_name == nullptr || class_name[0] == '\0')
1955     return StructuredData::GenericSP();
1956 
1957   if (!debugger_sp.get())
1958     return StructuredData::GenericSP();
1959 
1960   void *ret_val;
1961 
1962   {
1963     Locker py_lock(this,
1964                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1965     ret_val =
1966         g_swig_create_cmd(class_name, m_dictionary_name.c_str(), debugger_sp);
1967   }
1968 
1969   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
1970 }
1971 
1972 bool ScriptInterpreterPython::GenerateTypeScriptFunction(
1973     const char *oneliner, std::string &output, const void *name_token) {
1974   StringList input;
1975   input.SplitIntoLines(oneliner, strlen(oneliner));
1976   return GenerateTypeScriptFunction(input, output, name_token);
1977 }
1978 
1979 bool ScriptInterpreterPython::GenerateTypeSynthClass(const char *oneliner,
1980                                                      std::string &output,
1981                                                      const void *name_token) {
1982   StringList input;
1983   input.SplitIntoLines(oneliner, strlen(oneliner));
1984   return GenerateTypeSynthClass(input, output, name_token);
1985 }
1986 
1987 Status ScriptInterpreterPython::GenerateBreakpointCommandCallbackData(
1988     StringList &user_input, std::string &output) {
1989   static uint32_t num_created_functions = 0;
1990   user_input.RemoveBlankLines();
1991   StreamString sstr;
1992   Status error;
1993   if (user_input.GetSize() == 0) {
1994     error.SetErrorString("No input data.");
1995     return error;
1996   }
1997 
1998   std::string auto_generated_function_name(GenerateUniqueName(
1999       "lldb_autogen_python_bp_callback_func_", num_created_functions));
2000   sstr.Printf("def %s (frame, bp_loc, internal_dict):",
2001               auto_generated_function_name.c_str());
2002 
2003   error = GenerateFunction(sstr.GetData(), user_input);
2004   if (!error.Success())
2005     return error;
2006 
2007   // Store the name of the auto-generated function to be called.
2008   output.assign(auto_generated_function_name);
2009   return error;
2010 }
2011 
2012 bool ScriptInterpreterPython::GenerateWatchpointCommandCallbackData(
2013     StringList &user_input, std::string &output) {
2014   static uint32_t num_created_functions = 0;
2015   user_input.RemoveBlankLines();
2016   StreamString sstr;
2017 
2018   if (user_input.GetSize() == 0)
2019     return false;
2020 
2021   std::string auto_generated_function_name(GenerateUniqueName(
2022       "lldb_autogen_python_wp_callback_func_", num_created_functions));
2023   sstr.Printf("def %s (frame, wp, internal_dict):",
2024               auto_generated_function_name.c_str());
2025 
2026   if (!GenerateFunction(sstr.GetData(), user_input).Success())
2027     return false;
2028 
2029   // Store the name of the auto-generated function to be called.
2030   output.assign(auto_generated_function_name);
2031   return true;
2032 }
2033 
2034 bool ScriptInterpreterPython::GetScriptedSummary(
2035     const char *python_function_name, lldb::ValueObjectSP valobj,
2036     StructuredData::ObjectSP &callee_wrapper_sp,
2037     const TypeSummaryOptions &options, std::string &retval) {
2038 
2039   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2040   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
2041 
2042   if (!valobj.get()) {
2043     retval.assign("<no object>");
2044     return false;
2045   }
2046 
2047   void *old_callee = nullptr;
2048   StructuredData::Generic *generic = nullptr;
2049   if (callee_wrapper_sp) {
2050     generic = callee_wrapper_sp->GetAsGeneric();
2051     if (generic)
2052       old_callee = generic->GetValue();
2053   }
2054   void *new_callee = old_callee;
2055 
2056   bool ret_val;
2057   if (python_function_name && *python_function_name) {
2058     {
2059       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
2060                                Locker::NoSTDIN);
2061       {
2062         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
2063 
2064         static Timer::Category func_cat("g_swig_typescript_callback");
2065         Timer scoped_timer(func_cat, "g_swig_typescript_callback");
2066         ret_val = g_swig_typescript_callback(
2067             python_function_name, GetSessionDictionary().get(), valobj,
2068             &new_callee, options_sp, retval);
2069       }
2070     }
2071   } else {
2072     retval.assign("<no function name>");
2073     return false;
2074   }
2075 
2076   if (new_callee && old_callee != new_callee)
2077     callee_wrapper_sp.reset(new StructuredPythonObject(new_callee));
2078 
2079   return ret_val;
2080 }
2081 
2082 void ScriptInterpreterPython::Clear() {
2083   // Release any global variables that might have strong references to
2084   // LLDB objects when clearing the python script interpreter.
2085   Locker locker(this, ScriptInterpreterPython::Locker::AcquireLock,
2086                 ScriptInterpreterPython::Locker::FreeAcquiredLock);
2087 
2088   // This may be called as part of Py_Finalize.  In that case the modules are
2089   // destroyed in random order and we can't guarantee that we can access these.
2090   if (Py_IsInitialized())
2091     PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
2092                        "= None; lldb.thread = None; lldb.frame = None");
2093 }
2094 
2095 bool ScriptInterpreterPython::BreakpointCallbackFunction(
2096     void *baton, StoppointCallbackContext *context, user_id_t break_id,
2097     user_id_t break_loc_id) {
2098   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
2099   const char *python_function_name = bp_option_data->script_source.c_str();
2100 
2101   if (!context)
2102     return true;
2103 
2104   ExecutionContext exe_ctx(context->exe_ctx_ref);
2105   Target *target = exe_ctx.GetTargetPtr();
2106 
2107   if (!target)
2108     return true;
2109 
2110   Debugger &debugger = target->GetDebugger();
2111   ScriptInterpreter *script_interpreter =
2112       debugger.GetCommandInterpreter().GetScriptInterpreter();
2113   ScriptInterpreterPython *python_interpreter =
2114       (ScriptInterpreterPython *)script_interpreter;
2115 
2116   if (!script_interpreter)
2117     return true;
2118 
2119   if (python_function_name && python_function_name[0]) {
2120     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2121     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2122     if (breakpoint_sp) {
2123       const BreakpointLocationSP bp_loc_sp(
2124           breakpoint_sp->FindLocationByID(break_loc_id));
2125 
2126       if (stop_frame_sp && bp_loc_sp) {
2127         bool ret_val = true;
2128         {
2129           Locker py_lock(python_interpreter, Locker::AcquireLock |
2130                                                  Locker::InitSession |
2131                                                  Locker::NoSTDIN);
2132           ret_val = g_swig_breakpoint_callback(
2133               python_function_name,
2134               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2135               bp_loc_sp);
2136         }
2137         return ret_val;
2138       }
2139     }
2140   }
2141   // We currently always true so we stop in case anything goes wrong when
2142   // trying to call the script function
2143   return true;
2144 }
2145 
2146 bool ScriptInterpreterPython::WatchpointCallbackFunction(
2147     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2148   WatchpointOptions::CommandData *wp_option_data =
2149       (WatchpointOptions::CommandData *)baton;
2150   const char *python_function_name = wp_option_data->script_source.c_str();
2151 
2152   if (!context)
2153     return true;
2154 
2155   ExecutionContext exe_ctx(context->exe_ctx_ref);
2156   Target *target = exe_ctx.GetTargetPtr();
2157 
2158   if (!target)
2159     return true;
2160 
2161   Debugger &debugger = target->GetDebugger();
2162   ScriptInterpreter *script_interpreter =
2163       debugger.GetCommandInterpreter().GetScriptInterpreter();
2164   ScriptInterpreterPython *python_interpreter =
2165       (ScriptInterpreterPython *)script_interpreter;
2166 
2167   if (!script_interpreter)
2168     return true;
2169 
2170   if (python_function_name && python_function_name[0]) {
2171     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2172     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2173     if (wp_sp) {
2174       if (stop_frame_sp && wp_sp) {
2175         bool ret_val = true;
2176         {
2177           Locker py_lock(python_interpreter, Locker::AcquireLock |
2178                                                  Locker::InitSession |
2179                                                  Locker::NoSTDIN);
2180           ret_val = g_swig_watchpoint_callback(
2181               python_function_name,
2182               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2183               wp_sp);
2184         }
2185         return ret_val;
2186       }
2187     }
2188   }
2189   // We currently always true so we stop in case anything goes wrong when
2190   // trying to call the script function
2191   return true;
2192 }
2193 
2194 size_t ScriptInterpreterPython::CalculateNumChildren(
2195     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
2196   if (!implementor_sp)
2197     return 0;
2198   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2199   if (!generic)
2200     return 0;
2201   void *implementor = generic->GetValue();
2202   if (!implementor)
2203     return 0;
2204 
2205   if (!g_swig_calc_children)
2206     return 0;
2207 
2208   size_t ret_val = 0;
2209 
2210   {
2211     Locker py_lock(this,
2212                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2213     ret_val = g_swig_calc_children(implementor, max);
2214   }
2215 
2216   return ret_val;
2217 }
2218 
2219 lldb::ValueObjectSP ScriptInterpreterPython::GetChildAtIndex(
2220     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
2221   if (!implementor_sp)
2222     return lldb::ValueObjectSP();
2223 
2224   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2225   if (!generic)
2226     return lldb::ValueObjectSP();
2227   void *implementor = generic->GetValue();
2228   if (!implementor)
2229     return lldb::ValueObjectSP();
2230 
2231   if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
2232     return lldb::ValueObjectSP();
2233 
2234   lldb::ValueObjectSP ret_val;
2235 
2236   {
2237     Locker py_lock(this,
2238                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2239     void *child_ptr = g_swig_get_child_index(implementor, idx);
2240     if (child_ptr != nullptr && child_ptr != Py_None) {
2241       lldb::SBValue *sb_value_ptr =
2242           (lldb::SBValue *)g_swig_cast_to_sbvalue(child_ptr);
2243       if (sb_value_ptr == nullptr)
2244         Py_XDECREF(child_ptr);
2245       else
2246         ret_val = g_swig_get_valobj_sp_from_sbvalue(sb_value_ptr);
2247     } else {
2248       Py_XDECREF(child_ptr);
2249     }
2250   }
2251 
2252   return ret_val;
2253 }
2254 
2255 int ScriptInterpreterPython::GetIndexOfChildWithName(
2256     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
2257   if (!implementor_sp)
2258     return UINT32_MAX;
2259 
2260   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2261   if (!generic)
2262     return UINT32_MAX;
2263   void *implementor = generic->GetValue();
2264   if (!implementor)
2265     return UINT32_MAX;
2266 
2267   if (!g_swig_get_index_child)
2268     return UINT32_MAX;
2269 
2270   int ret_val = UINT32_MAX;
2271 
2272   {
2273     Locker py_lock(this,
2274                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2275     ret_val = g_swig_get_index_child(implementor, child_name);
2276   }
2277 
2278   return ret_val;
2279 }
2280 
2281 bool ScriptInterpreterPython::UpdateSynthProviderInstance(
2282     const StructuredData::ObjectSP &implementor_sp) {
2283   bool ret_val = false;
2284 
2285   if (!implementor_sp)
2286     return ret_val;
2287 
2288   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2289   if (!generic)
2290     return ret_val;
2291   void *implementor = generic->GetValue();
2292   if (!implementor)
2293     return ret_val;
2294 
2295   if (!g_swig_update_provider)
2296     return ret_val;
2297 
2298   {
2299     Locker py_lock(this,
2300                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2301     ret_val = g_swig_update_provider(implementor);
2302   }
2303 
2304   return ret_val;
2305 }
2306 
2307 bool ScriptInterpreterPython::MightHaveChildrenSynthProviderInstance(
2308     const StructuredData::ObjectSP &implementor_sp) {
2309   bool ret_val = false;
2310 
2311   if (!implementor_sp)
2312     return ret_val;
2313 
2314   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2315   if (!generic)
2316     return ret_val;
2317   void *implementor = generic->GetValue();
2318   if (!implementor)
2319     return ret_val;
2320 
2321   if (!g_swig_mighthavechildren_provider)
2322     return ret_val;
2323 
2324   {
2325     Locker py_lock(this,
2326                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2327     ret_val = g_swig_mighthavechildren_provider(implementor);
2328   }
2329 
2330   return ret_val;
2331 }
2332 
2333 lldb::ValueObjectSP ScriptInterpreterPython::GetSyntheticValue(
2334     const StructuredData::ObjectSP &implementor_sp) {
2335   lldb::ValueObjectSP ret_val(nullptr);
2336 
2337   if (!implementor_sp)
2338     return ret_val;
2339 
2340   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2341   if (!generic)
2342     return ret_val;
2343   void *implementor = generic->GetValue();
2344   if (!implementor)
2345     return ret_val;
2346 
2347   if (!g_swig_getvalue_provider || !g_swig_cast_to_sbvalue ||
2348       !g_swig_get_valobj_sp_from_sbvalue)
2349     return ret_val;
2350 
2351   {
2352     Locker py_lock(this,
2353                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2354     void *child_ptr = g_swig_getvalue_provider(implementor);
2355     if (child_ptr != nullptr && child_ptr != Py_None) {
2356       lldb::SBValue *sb_value_ptr =
2357           (lldb::SBValue *)g_swig_cast_to_sbvalue(child_ptr);
2358       if (sb_value_ptr == nullptr)
2359         Py_XDECREF(child_ptr);
2360       else
2361         ret_val = g_swig_get_valobj_sp_from_sbvalue(sb_value_ptr);
2362     } else {
2363       Py_XDECREF(child_ptr);
2364     }
2365   }
2366 
2367   return ret_val;
2368 }
2369 
2370 ConstString ScriptInterpreterPython::GetSyntheticTypeName(
2371     const StructuredData::ObjectSP &implementor_sp) {
2372   Locker py_lock(this,
2373                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2374 
2375   static char callee_name[] = "get_type_name";
2376 
2377   ConstString ret_val;
2378   bool got_string = false;
2379   std::string buffer;
2380 
2381   if (!implementor_sp)
2382     return ret_val;
2383 
2384   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2385   if (!generic)
2386     return ret_val;
2387   PythonObject implementor(PyRefType::Borrowed,
2388                            (PyObject *)generic->GetValue());
2389   if (!implementor.IsAllocated())
2390     return ret_val;
2391 
2392   PythonObject pmeth(PyRefType::Owned,
2393                      PyObject_GetAttrString(implementor.get(), callee_name));
2394 
2395   if (PyErr_Occurred())
2396     PyErr_Clear();
2397 
2398   if (!pmeth.IsAllocated())
2399     return ret_val;
2400 
2401   if (PyCallable_Check(pmeth.get()) == 0) {
2402     if (PyErr_Occurred())
2403       PyErr_Clear();
2404     return ret_val;
2405   }
2406 
2407   if (PyErr_Occurred())
2408     PyErr_Clear();
2409 
2410   // right now we know this function exists and is callable..
2411   PythonObject py_return(
2412       PyRefType::Owned,
2413       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
2414 
2415   // if it fails, print the error but otherwise go on
2416   if (PyErr_Occurred()) {
2417     PyErr_Print();
2418     PyErr_Clear();
2419   }
2420 
2421   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2422     PythonString py_string(PyRefType::Borrowed, py_return.get());
2423     llvm::StringRef return_data(py_string.GetString());
2424     if (!return_data.empty()) {
2425       buffer.assign(return_data.data(), return_data.size());
2426       got_string = true;
2427     }
2428   }
2429 
2430   if (got_string)
2431     ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
2432 
2433   return ret_val;
2434 }
2435 
2436 bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function,
2437                                                      Process *process,
2438                                                      std::string &output,
2439                                                      Status &error) {
2440   bool ret_val;
2441   if (!process) {
2442     error.SetErrorString("no process");
2443     return false;
2444   }
2445   if (!impl_function || !impl_function[0]) {
2446     error.SetErrorString("no function to execute");
2447     return false;
2448   }
2449   if (!g_swig_run_script_keyword_process) {
2450     error.SetErrorString("internal helper function missing");
2451     return false;
2452   }
2453   {
2454     ProcessSP process_sp(process->shared_from_this());
2455     Locker py_lock(this,
2456                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2457     ret_val = g_swig_run_script_keyword_process(
2458         impl_function, m_dictionary_name.c_str(), process_sp, output);
2459     if (!ret_val)
2460       error.SetErrorString("python script evaluation failed");
2461   }
2462   return ret_val;
2463 }
2464 
2465 bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function,
2466                                                      Thread *thread,
2467                                                      std::string &output,
2468                                                      Status &error) {
2469   bool ret_val;
2470   if (!thread) {
2471     error.SetErrorString("no thread");
2472     return false;
2473   }
2474   if (!impl_function || !impl_function[0]) {
2475     error.SetErrorString("no function to execute");
2476     return false;
2477   }
2478   if (!g_swig_run_script_keyword_thread) {
2479     error.SetErrorString("internal helper function missing");
2480     return false;
2481   }
2482   {
2483     ThreadSP thread_sp(thread->shared_from_this());
2484     Locker py_lock(this,
2485                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2486     ret_val = g_swig_run_script_keyword_thread(
2487         impl_function, m_dictionary_name.c_str(), thread_sp, output);
2488     if (!ret_val)
2489       error.SetErrorString("python script evaluation failed");
2490   }
2491   return ret_val;
2492 }
2493 
2494 bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function,
2495                                                      Target *target,
2496                                                      std::string &output,
2497                                                      Status &error) {
2498   bool ret_val;
2499   if (!target) {
2500     error.SetErrorString("no thread");
2501     return false;
2502   }
2503   if (!impl_function || !impl_function[0]) {
2504     error.SetErrorString("no function to execute");
2505     return false;
2506   }
2507   if (!g_swig_run_script_keyword_target) {
2508     error.SetErrorString("internal helper function missing");
2509     return false;
2510   }
2511   {
2512     TargetSP target_sp(target->shared_from_this());
2513     Locker py_lock(this,
2514                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2515     ret_val = g_swig_run_script_keyword_target(
2516         impl_function, m_dictionary_name.c_str(), target_sp, output);
2517     if (!ret_val)
2518       error.SetErrorString("python script evaluation failed");
2519   }
2520   return ret_val;
2521 }
2522 
2523 bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function,
2524                                                      StackFrame *frame,
2525                                                      std::string &output,
2526                                                      Status &error) {
2527   bool ret_val;
2528   if (!frame) {
2529     error.SetErrorString("no frame");
2530     return false;
2531   }
2532   if (!impl_function || !impl_function[0]) {
2533     error.SetErrorString("no function to execute");
2534     return false;
2535   }
2536   if (!g_swig_run_script_keyword_frame) {
2537     error.SetErrorString("internal helper function missing");
2538     return false;
2539   }
2540   {
2541     StackFrameSP frame_sp(frame->shared_from_this());
2542     Locker py_lock(this,
2543                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2544     ret_val = g_swig_run_script_keyword_frame(
2545         impl_function, m_dictionary_name.c_str(), frame_sp, output);
2546     if (!ret_val)
2547       error.SetErrorString("python script evaluation failed");
2548   }
2549   return ret_val;
2550 }
2551 
2552 bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function,
2553                                                      ValueObject *value,
2554                                                      std::string &output,
2555                                                      Status &error) {
2556   bool ret_val;
2557   if (!value) {
2558     error.SetErrorString("no value");
2559     return false;
2560   }
2561   if (!impl_function || !impl_function[0]) {
2562     error.SetErrorString("no function to execute");
2563     return false;
2564   }
2565   if (!g_swig_run_script_keyword_value) {
2566     error.SetErrorString("internal helper function missing");
2567     return false;
2568   }
2569   {
2570     ValueObjectSP value_sp(value->GetSP());
2571     Locker py_lock(this,
2572                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2573     ret_val = g_swig_run_script_keyword_value(
2574         impl_function, m_dictionary_name.c_str(), value_sp, output);
2575     if (!ret_val)
2576       error.SetErrorString("python script evaluation failed");
2577   }
2578   return ret_val;
2579 }
2580 
2581 uint64_t replace_all(std::string &str, const std::string &oldStr,
2582                      const std::string &newStr) {
2583   size_t pos = 0;
2584   uint64_t matches = 0;
2585   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2586     matches++;
2587     str.replace(pos, oldStr.length(), newStr);
2588     pos += newStr.length();
2589   }
2590   return matches;
2591 }
2592 
2593 bool ScriptInterpreterPython::LoadScriptingModule(
2594     const char *pathname, bool can_reload, bool init_session,
2595     lldb_private::Status &error, StructuredData::ObjectSP *module_sp) {
2596   if (!pathname || !pathname[0]) {
2597     error.SetErrorString("invalid pathname");
2598     return false;
2599   }
2600 
2601   if (!g_swig_call_module_init) {
2602     error.SetErrorString("internal helper function missing");
2603     return false;
2604   }
2605 
2606   lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
2607 
2608   {
2609     FileSpec target_file(pathname, true);
2610     std::string basename(target_file.GetFilename().GetCString());
2611 
2612     StreamString command_stream;
2613 
2614     // Before executing Python code, lock the GIL.
2615     Locker py_lock(this, Locker::AcquireLock |
2616                              (init_session ? Locker::InitSession : 0) |
2617                              Locker::NoSTDIN,
2618                    Locker::FreeAcquiredLock |
2619                        (init_session ? Locker::TearDownSession : 0));
2620     namespace fs = llvm::sys::fs;
2621     fs::file_status st;
2622     std::error_code ec = status(target_file.GetPath(), st);
2623 
2624     if (ec || st.type() == fs::file_type::status_error ||
2625         st.type() == fs::file_type::type_unknown ||
2626         st.type() == fs::file_type::file_not_found) {
2627       // if not a valid file of any sort, check if it might be a filename still
2628       // dot can't be used but / and \ can, and if either is found, reject
2629       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2630         error.SetErrorString("invalid pathname");
2631         return false;
2632       }
2633       basename = pathname; // not a filename, probably a package of some sort,
2634                            // let it go through
2635     } else if (is_directory(st) || is_regular_file(st)) {
2636       std::string directory = target_file.GetDirectory().GetCString();
2637       replace_all(directory, "\\", "\\\\");
2638       replace_all(directory, "'", "\\'");
2639 
2640       // now make sure that Python has "directory" in the search path
2641       StreamString command_stream;
2642       command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
2643                             "sys.path.insert(1,'%s');\n\n",
2644                             directory.c_str(), directory.c_str());
2645       bool syspath_retval =
2646           ExecuteMultipleLines(command_stream.GetData(),
2647                                ScriptInterpreter::ExecuteScriptOptions()
2648                                    .SetEnableIO(false)
2649                                    .SetSetLLDBGlobals(false))
2650               .Success();
2651       if (!syspath_retval) {
2652         error.SetErrorString("Python sys.path handling failed");
2653         return false;
2654       }
2655 
2656       // strip .py or .pyc extension
2657       ConstString extension = target_file.GetFileNameExtension();
2658       if (extension) {
2659         if (llvm::StringRef(extension.GetCString()) == ".py")
2660           basename.resize(basename.length() - 3);
2661         else if (llvm::StringRef(extension.GetCString()) == ".pyc")
2662           basename.resize(basename.length() - 4);
2663       }
2664     } else {
2665       error.SetErrorString("no known way to import this module specification");
2666       return false;
2667     }
2668 
2669     // check if the module is already import-ed
2670     command_stream.Clear();
2671     command_stream.Printf("sys.modules.__contains__('%s')", basename.c_str());
2672     bool does_contain = false;
2673     // this call will succeed if the module was ever imported in any Debugger
2674     // in the lifetime of the process in which this LLDB framework is living
2675     bool was_imported_globally =
2676         (ExecuteOneLineWithReturn(
2677              command_stream.GetData(),
2678              ScriptInterpreterPython::eScriptReturnTypeBool, &does_contain,
2679              ScriptInterpreter::ExecuteScriptOptions()
2680                  .SetEnableIO(false)
2681                  .SetSetLLDBGlobals(false)) &&
2682          does_contain);
2683     // this call will fail if the module was not imported in this Debugger
2684     // before
2685     command_stream.Clear();
2686     command_stream.Printf("sys.getrefcount(%s)", basename.c_str());
2687     bool was_imported_locally = GetSessionDictionary()
2688                                     .GetItemForKey(PythonString(basename))
2689                                     .IsAllocated();
2690 
2691     bool was_imported = (was_imported_globally || was_imported_locally);
2692 
2693     if (was_imported == true && can_reload == false) {
2694       error.SetErrorString("module already imported");
2695       return false;
2696     }
2697 
2698     // now actually do the import
2699     command_stream.Clear();
2700 
2701     if (was_imported) {
2702       if (!was_imported_locally)
2703         command_stream.Printf("import %s ; reload_module(%s)", basename.c_str(),
2704                               basename.c_str());
2705       else
2706         command_stream.Printf("reload_module(%s)", basename.c_str());
2707     } else
2708       command_stream.Printf("import %s", basename.c_str());
2709 
2710     error = ExecuteMultipleLines(command_stream.GetData(),
2711                                  ScriptInterpreter::ExecuteScriptOptions()
2712                                      .SetEnableIO(false)
2713                                      .SetSetLLDBGlobals(false));
2714     if (error.Fail())
2715       return false;
2716 
2717     // if we are here, everything worked
2718     // call __lldb_init_module(debugger,dict)
2719     if (!g_swig_call_module_init(basename.c_str(), m_dictionary_name.c_str(),
2720                                  debugger_sp)) {
2721       error.SetErrorString("calling __lldb_init_module failed");
2722       return false;
2723     }
2724 
2725     if (module_sp) {
2726       // everything went just great, now set the module object
2727       command_stream.Clear();
2728       command_stream.Printf("%s", basename.c_str());
2729       void *module_pyobj = nullptr;
2730       if (ExecuteOneLineWithReturn(
2731               command_stream.GetData(),
2732               ScriptInterpreter::eScriptReturnTypeOpaqueObject,
2733               &module_pyobj) &&
2734           module_pyobj)
2735         module_sp->reset(new StructuredPythonObject(module_pyobj));
2736     }
2737 
2738     return true;
2739   }
2740 }
2741 
2742 bool ScriptInterpreterPython::IsReservedWord(const char *word) {
2743   if (!word || !word[0])
2744     return false;
2745 
2746   llvm::StringRef word_sr(word);
2747 
2748   // filter out a few characters that would just confuse us and that are
2749   // clearly not keyword material anyway
2750   if (word_sr.find_first_of("'\"") != llvm::StringRef::npos)
2751     return false;
2752 
2753   StreamString command_stream;
2754   command_stream.Printf("keyword.iskeyword('%s')", word);
2755   bool result;
2756   ExecuteScriptOptions options;
2757   options.SetEnableIO(false);
2758   options.SetMaskoutErrors(true);
2759   options.SetSetLLDBGlobals(false);
2760   if (ExecuteOneLineWithReturn(command_stream.GetData(),
2761                                ScriptInterpreter::eScriptReturnTypeBool,
2762                                &result, options))
2763     return result;
2764   return false;
2765 }
2766 
2767 ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler(
2768     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2769     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2770       m_old_asynch(debugger_sp->GetAsyncExecution()) {
2771   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2772     m_debugger_sp->SetAsyncExecution(false);
2773   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2774     m_debugger_sp->SetAsyncExecution(true);
2775 }
2776 
2777 ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler() {
2778   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2779     m_debugger_sp->SetAsyncExecution(m_old_asynch);
2780 }
2781 
2782 bool ScriptInterpreterPython::RunScriptBasedCommand(
2783     const char *impl_function, llvm::StringRef args,
2784     ScriptedCommandSynchronicity synchronicity,
2785     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2786     const lldb_private::ExecutionContext &exe_ctx) {
2787   if (!impl_function) {
2788     error.SetErrorString("no function to execute");
2789     return false;
2790   }
2791 
2792   if (!g_swig_call_command) {
2793     error.SetErrorString("no helper function to run scripted commands");
2794     return false;
2795   }
2796 
2797   lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
2798   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2799 
2800   if (!debugger_sp.get()) {
2801     error.SetErrorString("invalid Debugger pointer");
2802     return false;
2803   }
2804 
2805   bool ret_val = false;
2806 
2807   std::string err_msg;
2808 
2809   {
2810     Locker py_lock(this,
2811                    Locker::AcquireLock | Locker::InitSession |
2812                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2813                    Locker::FreeLock | Locker::TearDownSession);
2814 
2815     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2816 
2817     std::string args_str = args.str();
2818     ret_val = g_swig_call_command(impl_function, m_dictionary_name.c_str(),
2819                                   debugger_sp, args_str.c_str(), cmd_retobj,
2820                                   exe_ctx_ref_sp);
2821   }
2822 
2823   if (!ret_val)
2824     error.SetErrorString("unable to execute script function");
2825   else
2826     error.Clear();
2827 
2828   return ret_val;
2829 }
2830 
2831 bool ScriptInterpreterPython::RunScriptBasedCommand(
2832     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
2833     ScriptedCommandSynchronicity synchronicity,
2834     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2835     const lldb_private::ExecutionContext &exe_ctx) {
2836   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2837     error.SetErrorString("no function to execute");
2838     return false;
2839   }
2840 
2841   if (!g_swig_call_command_object) {
2842     error.SetErrorString("no helper function to run scripted commands");
2843     return false;
2844   }
2845 
2846   lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
2847   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2848 
2849   if (!debugger_sp.get()) {
2850     error.SetErrorString("invalid Debugger pointer");
2851     return false;
2852   }
2853 
2854   bool ret_val = false;
2855 
2856   std::string err_msg;
2857 
2858   {
2859     Locker py_lock(this,
2860                    Locker::AcquireLock | Locker::InitSession |
2861                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2862                    Locker::FreeLock | Locker::TearDownSession);
2863 
2864     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2865 
2866     std::string args_str = args.str();
2867     ret_val = g_swig_call_command_object(impl_obj_sp->GetValue(), debugger_sp,
2868                                          args_str.c_str(), cmd_retobj,
2869                                          exe_ctx_ref_sp);
2870   }
2871 
2872   if (!ret_val)
2873     error.SetErrorString("unable to execute script function");
2874   else
2875     error.Clear();
2876 
2877   return ret_val;
2878 }
2879 
2880 // in Python, a special attribute __doc__ contains the docstring for an object
2881 // (function, method, class, ...) if any is defined Otherwise, the attribute's
2882 // value is None
2883 bool ScriptInterpreterPython::GetDocumentationForItem(const char *item,
2884                                                       std::string &dest) {
2885   dest.clear();
2886   if (!item || !*item)
2887     return false;
2888   std::string command(item);
2889   command += ".__doc__";
2890 
2891   char *result_ptr = nullptr; // Python is going to point this to valid data if
2892                               // ExecuteOneLineWithReturn returns successfully
2893 
2894   if (ExecuteOneLineWithReturn(
2895           command.c_str(), ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
2896           &result_ptr,
2897           ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false))) {
2898     if (result_ptr)
2899       dest.assign(result_ptr);
2900     return true;
2901   } else {
2902     StreamString str_stream;
2903     str_stream.Printf(
2904         "Function %s was not found. Containing module might be missing.", item);
2905     dest = str_stream.GetString();
2906     return false;
2907   }
2908 }
2909 
2910 bool ScriptInterpreterPython::GetShortHelpForCommandObject(
2911     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2912   bool got_string = false;
2913   dest.clear();
2914 
2915   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2916 
2917   static char callee_name[] = "get_short_help";
2918 
2919   if (!cmd_obj_sp)
2920     return false;
2921 
2922   PythonObject implementor(PyRefType::Borrowed,
2923                            (PyObject *)cmd_obj_sp->GetValue());
2924 
2925   if (!implementor.IsAllocated())
2926     return false;
2927 
2928   PythonObject pmeth(PyRefType::Owned,
2929                      PyObject_GetAttrString(implementor.get(), callee_name));
2930 
2931   if (PyErr_Occurred())
2932     PyErr_Clear();
2933 
2934   if (!pmeth.IsAllocated())
2935     return false;
2936 
2937   if (PyCallable_Check(pmeth.get()) == 0) {
2938     if (PyErr_Occurred())
2939       PyErr_Clear();
2940     return false;
2941   }
2942 
2943   if (PyErr_Occurred())
2944     PyErr_Clear();
2945 
2946   // right now we know this function exists and is callable..
2947   PythonObject py_return(
2948       PyRefType::Owned,
2949       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
2950 
2951   // if it fails, print the error but otherwise go on
2952   if (PyErr_Occurred()) {
2953     PyErr_Print();
2954     PyErr_Clear();
2955   }
2956 
2957   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2958     PythonString py_string(PyRefType::Borrowed, py_return.get());
2959     llvm::StringRef return_data(py_string.GetString());
2960     dest.assign(return_data.data(), return_data.size());
2961     got_string = true;
2962   }
2963   return got_string;
2964 }
2965 
2966 uint32_t ScriptInterpreterPython::GetFlagsForCommandObject(
2967     StructuredData::GenericSP cmd_obj_sp) {
2968   uint32_t result = 0;
2969 
2970   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2971 
2972   static char callee_name[] = "get_flags";
2973 
2974   if (!cmd_obj_sp)
2975     return result;
2976 
2977   PythonObject implementor(PyRefType::Borrowed,
2978                            (PyObject *)cmd_obj_sp->GetValue());
2979 
2980   if (!implementor.IsAllocated())
2981     return result;
2982 
2983   PythonObject pmeth(PyRefType::Owned,
2984                      PyObject_GetAttrString(implementor.get(), callee_name));
2985 
2986   if (PyErr_Occurred())
2987     PyErr_Clear();
2988 
2989   if (!pmeth.IsAllocated())
2990     return result;
2991 
2992   if (PyCallable_Check(pmeth.get()) == 0) {
2993     if (PyErr_Occurred())
2994       PyErr_Clear();
2995     return result;
2996   }
2997 
2998   if (PyErr_Occurred())
2999     PyErr_Clear();
3000 
3001   // right now we know this function exists and is callable..
3002   PythonObject py_return(
3003       PyRefType::Owned,
3004       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3005 
3006   // if it fails, print the error but otherwise go on
3007   if (PyErr_Occurred()) {
3008     PyErr_Print();
3009     PyErr_Clear();
3010   }
3011 
3012   if (py_return.IsAllocated() && PythonInteger::Check(py_return.get())) {
3013     PythonInteger int_value(PyRefType::Borrowed, py_return.get());
3014     result = int_value.GetInteger();
3015   }
3016 
3017   return result;
3018 }
3019 
3020 bool ScriptInterpreterPython::GetLongHelpForCommandObject(
3021     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
3022   bool got_string = false;
3023   dest.clear();
3024 
3025   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3026 
3027   static char callee_name[] = "get_long_help";
3028 
3029   if (!cmd_obj_sp)
3030     return false;
3031 
3032   PythonObject implementor(PyRefType::Borrowed,
3033                            (PyObject *)cmd_obj_sp->GetValue());
3034 
3035   if (!implementor.IsAllocated())
3036     return false;
3037 
3038   PythonObject pmeth(PyRefType::Owned,
3039                      PyObject_GetAttrString(implementor.get(), callee_name));
3040 
3041   if (PyErr_Occurred())
3042     PyErr_Clear();
3043 
3044   if (!pmeth.IsAllocated())
3045     return false;
3046 
3047   if (PyCallable_Check(pmeth.get()) == 0) {
3048     if (PyErr_Occurred())
3049       PyErr_Clear();
3050 
3051     return false;
3052   }
3053 
3054   if (PyErr_Occurred())
3055     PyErr_Clear();
3056 
3057   // right now we know this function exists and is callable..
3058   PythonObject py_return(
3059       PyRefType::Owned,
3060       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3061 
3062   // if it fails, print the error but otherwise go on
3063   if (PyErr_Occurred()) {
3064     PyErr_Print();
3065     PyErr_Clear();
3066   }
3067 
3068   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3069     PythonString str(PyRefType::Borrowed, py_return.get());
3070     llvm::StringRef str_data(str.GetString());
3071     dest.assign(str_data.data(), str_data.size());
3072     got_string = true;
3073   }
3074 
3075   return got_string;
3076 }
3077 
3078 std::unique_ptr<ScriptInterpreterLocker>
3079 ScriptInterpreterPython::AcquireInterpreterLock() {
3080   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3081       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3082       Locker::FreeLock | Locker::TearDownSession));
3083   return py_lock;
3084 }
3085 
3086 void ScriptInterpreterPython::InitializeInterpreter(
3087     SWIGInitCallback swig_init_callback,
3088     SWIGBreakpointCallbackFunction swig_breakpoint_callback,
3089     SWIGWatchpointCallbackFunction swig_watchpoint_callback,
3090     SWIGPythonTypeScriptCallbackFunction swig_typescript_callback,
3091     SWIGPythonCreateSyntheticProvider swig_synthetic_script,
3092     SWIGPythonCreateCommandObject swig_create_cmd,
3093     SWIGPythonCalculateNumChildren swig_calc_children,
3094     SWIGPythonGetChildAtIndex swig_get_child_index,
3095     SWIGPythonGetIndexOfChildWithName swig_get_index_child,
3096     SWIGPythonCastPyObjectToSBValue swig_cast_to_sbvalue,
3097     SWIGPythonGetValueObjectSPFromSBValue swig_get_valobj_sp_from_sbvalue,
3098     SWIGPythonUpdateSynthProviderInstance swig_update_provider,
3099     SWIGPythonMightHaveChildrenSynthProviderInstance
3100         swig_mighthavechildren_provider,
3101     SWIGPythonGetValueSynthProviderInstance swig_getvalue_provider,
3102     SWIGPythonCallCommand swig_call_command,
3103     SWIGPythonCallCommandObject swig_call_command_object,
3104     SWIGPythonCallModuleInit swig_call_module_init,
3105     SWIGPythonCreateOSPlugin swig_create_os_plugin,
3106     SWIGPythonScriptKeyword_Process swig_run_script_keyword_process,
3107     SWIGPythonScriptKeyword_Thread swig_run_script_keyword_thread,
3108     SWIGPythonScriptKeyword_Target swig_run_script_keyword_target,
3109     SWIGPythonScriptKeyword_Frame swig_run_script_keyword_frame,
3110     SWIGPythonScriptKeyword_Value swig_run_script_keyword_value,
3111     SWIGPython_GetDynamicSetting swig_plugin_get,
3112     SWIGPythonCreateScriptedThreadPlan swig_thread_plan_script,
3113     SWIGPythonCallThreadPlan swig_call_thread_plan) {
3114   g_swig_init_callback = swig_init_callback;
3115   g_swig_breakpoint_callback = swig_breakpoint_callback;
3116   g_swig_watchpoint_callback = swig_watchpoint_callback;
3117   g_swig_typescript_callback = swig_typescript_callback;
3118   g_swig_synthetic_script = swig_synthetic_script;
3119   g_swig_create_cmd = swig_create_cmd;
3120   g_swig_calc_children = swig_calc_children;
3121   g_swig_get_child_index = swig_get_child_index;
3122   g_swig_get_index_child = swig_get_index_child;
3123   g_swig_cast_to_sbvalue = swig_cast_to_sbvalue;
3124   g_swig_get_valobj_sp_from_sbvalue = swig_get_valobj_sp_from_sbvalue;
3125   g_swig_update_provider = swig_update_provider;
3126   g_swig_mighthavechildren_provider = swig_mighthavechildren_provider;
3127   g_swig_getvalue_provider = swig_getvalue_provider;
3128   g_swig_call_command = swig_call_command;
3129   g_swig_call_command_object = swig_call_command_object;
3130   g_swig_call_module_init = swig_call_module_init;
3131   g_swig_create_os_plugin = swig_create_os_plugin;
3132   g_swig_run_script_keyword_process = swig_run_script_keyword_process;
3133   g_swig_run_script_keyword_thread = swig_run_script_keyword_thread;
3134   g_swig_run_script_keyword_target = swig_run_script_keyword_target;
3135   g_swig_run_script_keyword_frame = swig_run_script_keyword_frame;
3136   g_swig_run_script_keyword_value = swig_run_script_keyword_value;
3137   g_swig_plugin_get = swig_plugin_get;
3138   g_swig_thread_plan_script = swig_thread_plan_script;
3139   g_swig_call_thread_plan = swig_call_thread_plan;
3140 }
3141 
3142 void ScriptInterpreterPython::InitializePrivate() {
3143   if (g_initialized)
3144     return;
3145 
3146   g_initialized = true;
3147 
3148   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
3149   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
3150 
3151   // RAII-based initialization which correctly handles multiple-initialization,
3152   // version- specific differences among Python 2 and Python 3, and saving and
3153   // restoring various other pieces of state that can get mucked with during
3154   // initialization.
3155   InitializePythonRAII initialize_guard;
3156 
3157   if (g_swig_init_callback)
3158     g_swig_init_callback();
3159 
3160   // Update the path python uses to search for modules to include the current
3161   // directory.
3162 
3163   PyRun_SimpleString("import sys");
3164   AddToSysPath(AddLocation::End, ".");
3165 
3166   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
3167   // that use a backslash as the path separator, this will result in executing
3168   // python code containing paths with unescaped backslashes.  But Python also
3169   // accepts forward slashes, so to make life easier we just use that.
3170   if (FileSpec file_spec = GetPythonDir())
3171     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3172   if (FileSpec file_spec = HostInfo::GetShlibDir())
3173     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3174 
3175   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3176                      "lldb.embedded_interpreter; from "
3177                      "lldb.embedded_interpreter import run_python_interpreter; "
3178                      "from lldb.embedded_interpreter import run_one_line");
3179 }
3180 
3181 void ScriptInterpreterPython::AddToSysPath(AddLocation location,
3182                                            std::string path) {
3183   std::string path_copy;
3184 
3185   std::string statement;
3186   if (location == AddLocation::Beginning) {
3187     statement.assign("sys.path.insert(0,\"");
3188     statement.append(path);
3189     statement.append("\")");
3190   } else {
3191     statement.assign("sys.path.append(\"");
3192     statement.append(path);
3193     statement.append("\")");
3194   }
3195   PyRun_SimpleString(statement.c_str());
3196 }
3197 
3198 // We are intentionally NOT calling Py_Finalize here (this would be the logical
3199 // place to call it).  Calling Py_Finalize here causes test suite runs to seg
3200 // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
3201 // be called 'at_exit'.  When the test suite Python harness finishes up, it
3202 // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3203 // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3204 // which calls ScriptInterpreter::Terminate, which calls
3205 // ScriptInterpreterPython::Terminate.  So if we call Py_Finalize here, we end
3206 // up with Py_Finalize being called from within Py_Finalize, which results in a
3207 // seg fault. Since this function only gets called when lldb is shutting down
3208 // and going away anyway, the fact that we don't actually call Py_Finalize
3209 // should not cause any problems (everything should shut down/go away anyway
3210 // when the process exits).
3211 //
3212 // void ScriptInterpreterPython::Terminate() { Py_Finalize (); }
3213 
3214 #endif // LLDB_DISABLE_PYTHON
3215