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