xref: /llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp (revision 4e4fbe821119fd168f3dd65fc88fa4220f6826fe)
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<BreakpointOptions::CommandData>();
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 // Set a Python one-liner as the callback for the breakpoint.
1235 Error ScriptInterpreterPython::SetBreakpointCommandCallback(
1236     BreakpointOptions *bp_options, const char *command_body_text) {
1237   auto data_ap = llvm::make_unique<BreakpointOptions::CommandData>();
1238 
1239   // Split the command_body_text into lines, and pass that to
1240   // GenerateBreakpointCommandCallbackData.  That will
1241   // wrap the body in an auto-generated function, and return the function name
1242   // in script_source.  That is what
1243   // the callback will actually invoke.
1244 
1245   data_ap->user_source.SplitIntoLines(command_body_text);
1246   Error error = GenerateBreakpointCommandCallbackData(data_ap->user_source,
1247                                                       data_ap->script_source);
1248   if (error.Success()) {
1249     auto baton_sp =
1250         std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_ap));
1251     bp_options->SetCallback(ScriptInterpreterPython::BreakpointCallbackFunction,
1252                             baton_sp);
1253     return error;
1254   } else
1255     return error;
1256 }
1257 
1258 // Set a Python one-liner as the callback for the watchpoint.
1259 void ScriptInterpreterPython::SetWatchpointCommandCallback(
1260     WatchpointOptions *wp_options, const char *oneliner) {
1261   auto data_ap = llvm::make_unique<WatchpointOptions::CommandData>();
1262 
1263   // It's necessary to set both user_source and script_source to the oneliner.
1264   // The former is used to generate callback description (as in watchpoint
1265   // command list)
1266   // while the latter is used for Python to interpret during the actual
1267   // callback.
1268 
1269   data_ap->user_source.AppendString(oneliner);
1270   data_ap->script_source.assign(oneliner);
1271 
1272   if (GenerateWatchpointCommandCallbackData(data_ap->user_source,
1273                                             data_ap->script_source)) {
1274     auto baton_sp =
1275         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_ap));
1276     wp_options->SetCallback(ScriptInterpreterPython::WatchpointCallbackFunction,
1277                             baton_sp);
1278   }
1279 
1280   return;
1281 }
1282 
1283 Error ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter(
1284     StringList &function_def) {
1285   // Convert StringList to one long, newline delimited, const char *.
1286   std::string function_def_string(function_def.CopyList());
1287 
1288   Error error = ExecuteMultipleLines(
1289       function_def_string.c_str(),
1290       ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false));
1291   return error;
1292 }
1293 
1294 Error ScriptInterpreterPython::GenerateFunction(const char *signature,
1295                                                 const StringList &input) {
1296   Error error;
1297   int num_lines = input.GetSize();
1298   if (num_lines == 0) {
1299     error.SetErrorString("No input data.");
1300     return error;
1301   }
1302 
1303   if (!signature || *signature == 0) {
1304     error.SetErrorString("No output function name.");
1305     return error;
1306   }
1307 
1308   StreamString sstr;
1309   StringList auto_generated_function;
1310   auto_generated_function.AppendString(signature);
1311   auto_generated_function.AppendString(
1312       "     global_dict = globals()"); // Grab the global dictionary
1313   auto_generated_function.AppendString(
1314       "     new_keys = internal_dict.keys()"); // Make a list of keys in the
1315                                                // session dict
1316   auto_generated_function.AppendString(
1317       "     old_keys = global_dict.keys()"); // Save list of keys in global dict
1318   auto_generated_function.AppendString(
1319       "     global_dict.update (internal_dict)"); // Add the session dictionary
1320                                                   // to the
1321   // global dictionary.
1322 
1323   // Wrap everything up inside the function, increasing the indentation.
1324 
1325   auto_generated_function.AppendString("     if True:");
1326   for (int i = 0; i < num_lines; ++i) {
1327     sstr.Clear();
1328     sstr.Printf("       %s", input.GetStringAtIndex(i));
1329     auto_generated_function.AppendString(sstr.GetData());
1330   }
1331   auto_generated_function.AppendString(
1332       "     for key in new_keys:"); // Iterate over all the keys from session
1333                                     // dict
1334   auto_generated_function.AppendString(
1335       "         internal_dict[key] = global_dict[key]"); // Update session dict
1336                                                          // values
1337   auto_generated_function.AppendString(
1338       "         if key not in old_keys:"); // If key was not originally in
1339                                            // global dict
1340   auto_generated_function.AppendString(
1341       "             del global_dict[key]"); //  ...then remove key/value from
1342                                             //  global dict
1343 
1344   // Verify that the results are valid Python.
1345 
1346   error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
1347 
1348   return error;
1349 }
1350 
1351 bool ScriptInterpreterPython::GenerateTypeScriptFunction(
1352     StringList &user_input, std::string &output, const void *name_token) {
1353   static uint32_t num_created_functions = 0;
1354   user_input.RemoveBlankLines();
1355   StreamString sstr;
1356 
1357   // Check to see if we have any data; if not, just return.
1358   if (user_input.GetSize() == 0)
1359     return false;
1360 
1361   // Take what the user wrote, wrap it all up inside one big auto-generated
1362   // Python function, passing in the
1363   // ValueObject as parameter to the function.
1364 
1365   std::string auto_generated_function_name(
1366       GenerateUniqueName("lldb_autogen_python_type_print_func",
1367                          num_created_functions, name_token));
1368   sstr.Printf("def %s (valobj, internal_dict):",
1369               auto_generated_function_name.c_str());
1370 
1371   if (!GenerateFunction(sstr.GetData(), user_input).Success())
1372     return false;
1373 
1374   // Store the name of the auto-generated function to be called.
1375   output.assign(auto_generated_function_name);
1376   return true;
1377 }
1378 
1379 bool ScriptInterpreterPython::GenerateScriptAliasFunction(
1380     StringList &user_input, std::string &output) {
1381   static uint32_t num_created_functions = 0;
1382   user_input.RemoveBlankLines();
1383   StreamString sstr;
1384 
1385   // Check to see if we have any data; if not, just return.
1386   if (user_input.GetSize() == 0)
1387     return false;
1388 
1389   std::string auto_generated_function_name(GenerateUniqueName(
1390       "lldb_autogen_python_cmd_alias_func", num_created_functions));
1391 
1392   sstr.Printf("def %s (debugger, args, result, internal_dict):",
1393               auto_generated_function_name.c_str());
1394 
1395   if (!GenerateFunction(sstr.GetData(), user_input).Success())
1396     return false;
1397 
1398   // Store the name of the auto-generated function to be called.
1399   output.assign(auto_generated_function_name);
1400   return true;
1401 }
1402 
1403 bool ScriptInterpreterPython::GenerateTypeSynthClass(StringList &user_input,
1404                                                      std::string &output,
1405                                                      const void *name_token) {
1406   static uint32_t num_created_classes = 0;
1407   user_input.RemoveBlankLines();
1408   int num_lines = user_input.GetSize();
1409   StreamString sstr;
1410 
1411   // Check to see if we have any data; if not, just return.
1412   if (user_input.GetSize() == 0)
1413     return false;
1414 
1415   // Wrap all user input into a Python class
1416 
1417   std::string auto_generated_class_name(GenerateUniqueName(
1418       "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1419 
1420   StringList auto_generated_class;
1421 
1422   // Create the function name & definition string.
1423 
1424   sstr.Printf("class %s:", auto_generated_class_name.c_str());
1425   auto_generated_class.AppendString(sstr.GetData());
1426 
1427   // Wrap everything up inside the class, increasing the indentation.
1428   // we don't need to play any fancy indentation tricks here because there is no
1429   // surrounding code whose indentation we need to honor
1430   for (int i = 0; i < num_lines; ++i) {
1431     sstr.Clear();
1432     sstr.Printf("     %s", user_input.GetStringAtIndex(i));
1433     auto_generated_class.AppendString(sstr.GetData());
1434   }
1435 
1436   // Verify that the results are valid Python.
1437   // (even though the method is ExportFunctionDefinitionToInterpreter, a class
1438   // will actually be exported)
1439   // (TODO: rename that method to ExportDefinitionToInterpreter)
1440   if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
1441     return false;
1442 
1443   // Store the name of the auto-generated class
1444 
1445   output.assign(auto_generated_class_name);
1446   return true;
1447 }
1448 
1449 StructuredData::GenericSP ScriptInterpreterPython::OSPlugin_CreatePluginObject(
1450     const char *class_name, lldb::ProcessSP process_sp) {
1451   if (class_name == nullptr || class_name[0] == '\0')
1452     return StructuredData::GenericSP();
1453 
1454   if (!process_sp)
1455     return StructuredData::GenericSP();
1456 
1457   void *ret_val;
1458 
1459   {
1460     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
1461                    Locker::FreeLock);
1462     ret_val = g_swig_create_os_plugin(class_name, m_dictionary_name.c_str(),
1463                                       process_sp);
1464   }
1465 
1466   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
1467 }
1468 
1469 StructuredData::DictionarySP ScriptInterpreterPython::OSPlugin_RegisterInfo(
1470     StructuredData::ObjectSP os_plugin_object_sp) {
1471   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1472 
1473   static char callee_name[] = "get_register_info";
1474 
1475   if (!os_plugin_object_sp)
1476     return StructuredData::DictionarySP();
1477 
1478   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1479   if (!generic)
1480     return nullptr;
1481 
1482   PythonObject implementor(PyRefType::Borrowed,
1483                            (PyObject *)generic->GetValue());
1484 
1485   if (!implementor.IsAllocated())
1486     return StructuredData::DictionarySP();
1487 
1488   PythonObject pmeth(PyRefType::Owned,
1489                      PyObject_GetAttrString(implementor.get(), callee_name));
1490 
1491   if (PyErr_Occurred())
1492     PyErr_Clear();
1493 
1494   if (!pmeth.IsAllocated())
1495     return StructuredData::DictionarySP();
1496 
1497   if (PyCallable_Check(pmeth.get()) == 0) {
1498     if (PyErr_Occurred())
1499       PyErr_Clear();
1500 
1501     return StructuredData::DictionarySP();
1502   }
1503 
1504   if (PyErr_Occurred())
1505     PyErr_Clear();
1506 
1507   // right now we know this function exists and is callable..
1508   PythonObject py_return(
1509       PyRefType::Owned,
1510       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
1511 
1512   // if it fails, print the error but otherwise go on
1513   if (PyErr_Occurred()) {
1514     PyErr_Print();
1515     PyErr_Clear();
1516   }
1517   if (py_return.get()) {
1518     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1519     return result_dict.CreateStructuredDictionary();
1520   }
1521   return StructuredData::DictionarySP();
1522 }
1523 
1524 StructuredData::ArraySP ScriptInterpreterPython::OSPlugin_ThreadsInfo(
1525     StructuredData::ObjectSP os_plugin_object_sp) {
1526   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1527 
1528   static char callee_name[] = "get_thread_info";
1529 
1530   if (!os_plugin_object_sp)
1531     return StructuredData::ArraySP();
1532 
1533   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1534   if (!generic)
1535     return nullptr;
1536 
1537   PythonObject implementor(PyRefType::Borrowed,
1538                            (PyObject *)generic->GetValue());
1539 
1540   if (!implementor.IsAllocated())
1541     return StructuredData::ArraySP();
1542 
1543   PythonObject pmeth(PyRefType::Owned,
1544                      PyObject_GetAttrString(implementor.get(), callee_name));
1545 
1546   if (PyErr_Occurred())
1547     PyErr_Clear();
1548 
1549   if (!pmeth.IsAllocated())
1550     return StructuredData::ArraySP();
1551 
1552   if (PyCallable_Check(pmeth.get()) == 0) {
1553     if (PyErr_Occurred())
1554       PyErr_Clear();
1555 
1556     return StructuredData::ArraySP();
1557   }
1558 
1559   if (PyErr_Occurred())
1560     PyErr_Clear();
1561 
1562   // right now we know this function exists and is callable..
1563   PythonObject py_return(
1564       PyRefType::Owned,
1565       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
1566 
1567   // if it fails, print the error but otherwise go on
1568   if (PyErr_Occurred()) {
1569     PyErr_Print();
1570     PyErr_Clear();
1571   }
1572 
1573   if (py_return.get()) {
1574     PythonList result_list(PyRefType::Borrowed, py_return.get());
1575     return result_list.CreateStructuredArray();
1576   }
1577   return StructuredData::ArraySP();
1578 }
1579 
1580 // GetPythonValueFormatString provides a system independent type safe way to
1581 // convert a variable's type into a python value format. Python value formats
1582 // are defined in terms of builtin C types and could change from system to
1583 // as the underlying typedef for uint* types, size_t, off_t and other values
1584 // change.
1585 
1586 template <typename T> const char *GetPythonValueFormatString(T t) {
1587   assert(!"Unhandled type passed to GetPythonValueFormatString(T), make a "
1588           "specialization of GetPythonValueFormatString() to support this "
1589           "type.");
1590   return nullptr;
1591 }
1592 template <> const char *GetPythonValueFormatString(char *) { return "s"; }
1593 template <> const char *GetPythonValueFormatString(char) { return "b"; }
1594 template <> const char *GetPythonValueFormatString(unsigned char) {
1595   return "B";
1596 }
1597 template <> const char *GetPythonValueFormatString(short) { return "h"; }
1598 template <> const char *GetPythonValueFormatString(unsigned short) {
1599   return "H";
1600 }
1601 template <> const char *GetPythonValueFormatString(int) { return "i"; }
1602 template <> const char *GetPythonValueFormatString(unsigned int) { return "I"; }
1603 template <> const char *GetPythonValueFormatString(long) { return "l"; }
1604 template <> const char *GetPythonValueFormatString(unsigned long) {
1605   return "k";
1606 }
1607 template <> const char *GetPythonValueFormatString(long long) { return "L"; }
1608 template <> const char *GetPythonValueFormatString(unsigned long long) {
1609   return "K";
1610 }
1611 template <> const char *GetPythonValueFormatString(float t) { return "f"; }
1612 template <> const char *GetPythonValueFormatString(double t) { return "d"; }
1613 
1614 StructuredData::StringSP ScriptInterpreterPython::OSPlugin_RegisterContextData(
1615     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
1616   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1617 
1618   static char callee_name[] = "get_register_data";
1619   static char *param_format =
1620       const_cast<char *>(GetPythonValueFormatString(tid));
1621 
1622   if (!os_plugin_object_sp)
1623     return StructuredData::StringSP();
1624 
1625   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1626   if (!generic)
1627     return nullptr;
1628   PythonObject implementor(PyRefType::Borrowed,
1629                            (PyObject *)generic->GetValue());
1630 
1631   if (!implementor.IsAllocated())
1632     return StructuredData::StringSP();
1633 
1634   PythonObject pmeth(PyRefType::Owned,
1635                      PyObject_GetAttrString(implementor.get(), callee_name));
1636 
1637   if (PyErr_Occurred())
1638     PyErr_Clear();
1639 
1640   if (!pmeth.IsAllocated())
1641     return StructuredData::StringSP();
1642 
1643   if (PyCallable_Check(pmeth.get()) == 0) {
1644     if (PyErr_Occurred())
1645       PyErr_Clear();
1646     return StructuredData::StringSP();
1647   }
1648 
1649   if (PyErr_Occurred())
1650     PyErr_Clear();
1651 
1652   // right now we know this function exists and is callable..
1653   PythonObject py_return(
1654       PyRefType::Owned,
1655       PyObject_CallMethod(implementor.get(), callee_name, param_format, tid));
1656 
1657   // if it fails, print the error but otherwise go on
1658   if (PyErr_Occurred()) {
1659     PyErr_Print();
1660     PyErr_Clear();
1661   }
1662 
1663   if (py_return.get()) {
1664     PythonBytes result(PyRefType::Borrowed, py_return.get());
1665     return result.CreateStructuredString();
1666   }
1667   return StructuredData::StringSP();
1668 }
1669 
1670 StructuredData::DictionarySP ScriptInterpreterPython::OSPlugin_CreateThread(
1671     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
1672     lldb::addr_t context) {
1673   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1674 
1675   static char callee_name[] = "create_thread";
1676   std::string param_format;
1677   param_format += GetPythonValueFormatString(tid);
1678   param_format += GetPythonValueFormatString(context);
1679 
1680   if (!os_plugin_object_sp)
1681     return StructuredData::DictionarySP();
1682 
1683   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1684   if (!generic)
1685     return nullptr;
1686 
1687   PythonObject implementor(PyRefType::Borrowed,
1688                            (PyObject *)generic->GetValue());
1689 
1690   if (!implementor.IsAllocated())
1691     return StructuredData::DictionarySP();
1692 
1693   PythonObject pmeth(PyRefType::Owned,
1694                      PyObject_GetAttrString(implementor.get(), callee_name));
1695 
1696   if (PyErr_Occurred())
1697     PyErr_Clear();
1698 
1699   if (!pmeth.IsAllocated())
1700     return StructuredData::DictionarySP();
1701 
1702   if (PyCallable_Check(pmeth.get()) == 0) {
1703     if (PyErr_Occurred())
1704       PyErr_Clear();
1705     return StructuredData::DictionarySP();
1706   }
1707 
1708   if (PyErr_Occurred())
1709     PyErr_Clear();
1710 
1711   // right now we know this function exists and is callable..
1712   PythonObject py_return(PyRefType::Owned,
1713                          PyObject_CallMethod(implementor.get(), callee_name,
1714                                              &param_format[0], tid, context));
1715 
1716   // if it fails, print the error but otherwise go on
1717   if (PyErr_Occurred()) {
1718     PyErr_Print();
1719     PyErr_Clear();
1720   }
1721 
1722   if (py_return.get()) {
1723     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1724     return result_dict.CreateStructuredDictionary();
1725   }
1726   return StructuredData::DictionarySP();
1727 }
1728 
1729 StructuredData::ObjectSP ScriptInterpreterPython::CreateScriptedThreadPlan(
1730     const char *class_name, lldb::ThreadPlanSP thread_plan_sp) {
1731   if (class_name == nullptr || class_name[0] == '\0')
1732     return StructuredData::ObjectSP();
1733 
1734   if (!thread_plan_sp.get())
1735     return StructuredData::ObjectSP();
1736 
1737   Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
1738   ScriptInterpreter *script_interpreter =
1739       debugger.GetCommandInterpreter().GetScriptInterpreter();
1740   ScriptInterpreterPython *python_interpreter =
1741       static_cast<ScriptInterpreterPython *>(script_interpreter);
1742 
1743   if (!script_interpreter)
1744     return StructuredData::ObjectSP();
1745 
1746   void *ret_val;
1747 
1748   {
1749     Locker py_lock(this,
1750                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1751 
1752     ret_val = g_swig_thread_plan_script(
1753         class_name, python_interpreter->m_dictionary_name.c_str(),
1754         thread_plan_sp);
1755   }
1756 
1757   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
1758 }
1759 
1760 bool ScriptInterpreterPython::ScriptedThreadPlanExplainsStop(
1761     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1762   bool explains_stop = true;
1763   StructuredData::Generic *generic = nullptr;
1764   if (implementor_sp)
1765     generic = implementor_sp->GetAsGeneric();
1766   if (generic) {
1767     Locker py_lock(this,
1768                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1769     explains_stop = g_swig_call_thread_plan(
1770         generic->GetValue(), "explains_stop", event, script_error);
1771     if (script_error)
1772       return true;
1773   }
1774   return explains_stop;
1775 }
1776 
1777 bool ScriptInterpreterPython::ScriptedThreadPlanShouldStop(
1778     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1779   bool should_stop = true;
1780   StructuredData::Generic *generic = nullptr;
1781   if (implementor_sp)
1782     generic = implementor_sp->GetAsGeneric();
1783   if (generic) {
1784     Locker py_lock(this,
1785                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1786     should_stop = g_swig_call_thread_plan(generic->GetValue(), "should_stop",
1787                                           event, script_error);
1788     if (script_error)
1789       return true;
1790   }
1791   return should_stop;
1792 }
1793 
1794 bool ScriptInterpreterPython::ScriptedThreadPlanIsStale(
1795     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1796   bool is_stale = true;
1797   StructuredData::Generic *generic = nullptr;
1798   if (implementor_sp)
1799     generic = implementor_sp->GetAsGeneric();
1800   if (generic) {
1801     Locker py_lock(this,
1802                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1803     is_stale = g_swig_call_thread_plan(generic->GetValue(), "is_stale", nullptr,
1804                                        script_error);
1805     if (script_error)
1806       return true;
1807   }
1808   return is_stale;
1809 }
1810 
1811 lldb::StateType ScriptInterpreterPython::ScriptedThreadPlanGetRunState(
1812     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1813   bool should_step = false;
1814   StructuredData::Generic *generic = nullptr;
1815   if (implementor_sp)
1816     generic = implementor_sp->GetAsGeneric();
1817   if (generic) {
1818     Locker py_lock(this,
1819                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1820     should_step = g_swig_call_thread_plan(generic->GetValue(), "should_step",
1821                                           NULL, script_error);
1822     if (script_error)
1823       should_step = true;
1824   }
1825   if (should_step)
1826     return lldb::eStateStepping;
1827   else
1828     return lldb::eStateRunning;
1829 }
1830 
1831 StructuredData::ObjectSP
1832 ScriptInterpreterPython::LoadPluginModule(const FileSpec &file_spec,
1833                                           lldb_private::Error &error) {
1834   if (!file_spec.Exists()) {
1835     error.SetErrorString("no such file");
1836     return StructuredData::ObjectSP();
1837   }
1838 
1839   StructuredData::ObjectSP module_sp;
1840 
1841   if (LoadScriptingModule(file_spec.GetPath().c_str(), true, true, error,
1842                           &module_sp))
1843     return module_sp;
1844 
1845   return StructuredData::ObjectSP();
1846 }
1847 
1848 StructuredData::DictionarySP ScriptInterpreterPython::GetDynamicSettings(
1849     StructuredData::ObjectSP plugin_module_sp, Target *target,
1850     const char *setting_name, lldb_private::Error &error) {
1851   if (!plugin_module_sp || !target || !setting_name || !setting_name[0] ||
1852       !g_swig_plugin_get)
1853     return StructuredData::DictionarySP();
1854   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
1855   if (!generic)
1856     return StructuredData::DictionarySP();
1857 
1858   PythonObject reply_pyobj;
1859   {
1860     Locker py_lock(this,
1861                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1862     TargetSP target_sp(target->shared_from_this());
1863     reply_pyobj.Reset(PyRefType::Owned,
1864                       (PyObject *)g_swig_plugin_get(generic->GetValue(),
1865                                                     setting_name, target_sp));
1866   }
1867 
1868   PythonDictionary py_dict(PyRefType::Borrowed, reply_pyobj.get());
1869   return py_dict.CreateStructuredDictionary();
1870 }
1871 
1872 StructuredData::ObjectSP
1873 ScriptInterpreterPython::CreateSyntheticScriptedProvider(
1874     const char *class_name, lldb::ValueObjectSP valobj) {
1875   if (class_name == nullptr || class_name[0] == '\0')
1876     return StructuredData::ObjectSP();
1877 
1878   if (!valobj.get())
1879     return StructuredData::ObjectSP();
1880 
1881   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
1882   Target *target = exe_ctx.GetTargetPtr();
1883 
1884   if (!target)
1885     return StructuredData::ObjectSP();
1886 
1887   Debugger &debugger = target->GetDebugger();
1888   ScriptInterpreter *script_interpreter =
1889       debugger.GetCommandInterpreter().GetScriptInterpreter();
1890   ScriptInterpreterPython *python_interpreter =
1891       (ScriptInterpreterPython *)script_interpreter;
1892 
1893   if (!script_interpreter)
1894     return StructuredData::ObjectSP();
1895 
1896   void *ret_val = nullptr;
1897 
1898   {
1899     Locker py_lock(this,
1900                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1901     ret_val = g_swig_synthetic_script(
1902         class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
1903   }
1904 
1905   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
1906 }
1907 
1908 StructuredData::GenericSP
1909 ScriptInterpreterPython::CreateScriptCommandObject(const char *class_name) {
1910   DebuggerSP debugger_sp(
1911       GetCommandInterpreter().GetDebugger().shared_from_this());
1912 
1913   if (class_name == nullptr || class_name[0] == '\0')
1914     return StructuredData::GenericSP();
1915 
1916   if (!debugger_sp.get())
1917     return StructuredData::GenericSP();
1918 
1919   void *ret_val;
1920 
1921   {
1922     Locker py_lock(this,
1923                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1924     ret_val =
1925         g_swig_create_cmd(class_name, m_dictionary_name.c_str(), debugger_sp);
1926   }
1927 
1928   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
1929 }
1930 
1931 bool ScriptInterpreterPython::GenerateTypeScriptFunction(
1932     const char *oneliner, std::string &output, const void *name_token) {
1933   StringList input;
1934   input.SplitIntoLines(oneliner, strlen(oneliner));
1935   return GenerateTypeScriptFunction(input, output, name_token);
1936 }
1937 
1938 bool ScriptInterpreterPython::GenerateTypeSynthClass(const char *oneliner,
1939                                                      std::string &output,
1940                                                      const void *name_token) {
1941   StringList input;
1942   input.SplitIntoLines(oneliner, strlen(oneliner));
1943   return GenerateTypeSynthClass(input, output, name_token);
1944 }
1945 
1946 Error ScriptInterpreterPython::GenerateBreakpointCommandCallbackData(
1947     StringList &user_input, std::string &output) {
1948   static uint32_t num_created_functions = 0;
1949   user_input.RemoveBlankLines();
1950   StreamString sstr;
1951   Error error;
1952   if (user_input.GetSize() == 0) {
1953     error.SetErrorString("No input data.");
1954     return error;
1955   }
1956 
1957   std::string auto_generated_function_name(GenerateUniqueName(
1958       "lldb_autogen_python_bp_callback_func_", num_created_functions));
1959   sstr.Printf("def %s (frame, bp_loc, internal_dict):",
1960               auto_generated_function_name.c_str());
1961 
1962   error = GenerateFunction(sstr.GetData(), user_input);
1963   if (!error.Success())
1964     return error;
1965 
1966   // Store the name of the auto-generated function to be called.
1967   output.assign(auto_generated_function_name);
1968   return error;
1969 }
1970 
1971 bool ScriptInterpreterPython::GenerateWatchpointCommandCallbackData(
1972     StringList &user_input, std::string &output) {
1973   static uint32_t num_created_functions = 0;
1974   user_input.RemoveBlankLines();
1975   StreamString sstr;
1976 
1977   if (user_input.GetSize() == 0)
1978     return false;
1979 
1980   std::string auto_generated_function_name(GenerateUniqueName(
1981       "lldb_autogen_python_wp_callback_func_", num_created_functions));
1982   sstr.Printf("def %s (frame, wp, internal_dict):",
1983               auto_generated_function_name.c_str());
1984 
1985   if (!GenerateFunction(sstr.GetData(), user_input).Success())
1986     return false;
1987 
1988   // Store the name of the auto-generated function to be called.
1989   output.assign(auto_generated_function_name);
1990   return true;
1991 }
1992 
1993 bool ScriptInterpreterPython::GetScriptedSummary(
1994     const char *python_function_name, lldb::ValueObjectSP valobj,
1995     StructuredData::ObjectSP &callee_wrapper_sp,
1996     const TypeSummaryOptions &options, std::string &retval) {
1997 
1998   Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION);
1999 
2000   if (!valobj.get()) {
2001     retval.assign("<no object>");
2002     return false;
2003   }
2004 
2005   void *old_callee = nullptr;
2006   StructuredData::Generic *generic = nullptr;
2007   if (callee_wrapper_sp) {
2008     generic = callee_wrapper_sp->GetAsGeneric();
2009     if (generic)
2010       old_callee = generic->GetValue();
2011   }
2012   void *new_callee = old_callee;
2013 
2014   bool ret_val;
2015   if (python_function_name && *python_function_name) {
2016     {
2017       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
2018                                Locker::NoSTDIN);
2019       {
2020         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
2021 
2022         Timer scoped_timer("g_swig_typescript_callback",
2023                            "g_swig_typescript_callback");
2024         ret_val = g_swig_typescript_callback(
2025             python_function_name, GetSessionDictionary().get(), valobj,
2026             &new_callee, options_sp, retval);
2027       }
2028     }
2029   } else {
2030     retval.assign("<no function name>");
2031     return false;
2032   }
2033 
2034   if (new_callee && old_callee != new_callee)
2035     callee_wrapper_sp.reset(new StructuredPythonObject(new_callee));
2036 
2037   return ret_val;
2038 }
2039 
2040 void ScriptInterpreterPython::Clear() {
2041   // Release any global variables that might have strong references to
2042   // LLDB objects when clearing the python script interpreter.
2043   Locker locker(this, ScriptInterpreterPython::Locker::AcquireLock,
2044                 ScriptInterpreterPython::Locker::FreeAcquiredLock);
2045 
2046   // This may be called as part of Py_Finalize.  In that case the modules are
2047   // destroyed in random
2048   // order and we can't guarantee that we can access these.
2049   if (Py_IsInitialized())
2050     PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
2051                        "= None; lldb.thread = None; lldb.frame = None");
2052 }
2053 
2054 bool ScriptInterpreterPython::BreakpointCallbackFunction(
2055     void *baton, StoppointCallbackContext *context, user_id_t break_id,
2056     user_id_t break_loc_id) {
2057   BreakpointOptions::CommandData *bp_option_data =
2058       (BreakpointOptions::CommandData *)baton;
2059   const char *python_function_name = bp_option_data->script_source.c_str();
2060 
2061   if (!context)
2062     return true;
2063 
2064   ExecutionContext exe_ctx(context->exe_ctx_ref);
2065   Target *target = exe_ctx.GetTargetPtr();
2066 
2067   if (!target)
2068     return true;
2069 
2070   Debugger &debugger = target->GetDebugger();
2071   ScriptInterpreter *script_interpreter =
2072       debugger.GetCommandInterpreter().GetScriptInterpreter();
2073   ScriptInterpreterPython *python_interpreter =
2074       (ScriptInterpreterPython *)script_interpreter;
2075 
2076   if (!script_interpreter)
2077     return true;
2078 
2079   if (python_function_name && python_function_name[0]) {
2080     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2081     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2082     if (breakpoint_sp) {
2083       const BreakpointLocationSP bp_loc_sp(
2084           breakpoint_sp->FindLocationByID(break_loc_id));
2085 
2086       if (stop_frame_sp && bp_loc_sp) {
2087         bool ret_val = true;
2088         {
2089           Locker py_lock(python_interpreter, Locker::AcquireLock |
2090                                                  Locker::InitSession |
2091                                                  Locker::NoSTDIN);
2092           ret_val = g_swig_breakpoint_callback(
2093               python_function_name,
2094               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2095               bp_loc_sp);
2096         }
2097         return ret_val;
2098       }
2099     }
2100   }
2101   // We currently always true so we stop in case anything goes wrong when
2102   // trying to call the script function
2103   return true;
2104 }
2105 
2106 bool ScriptInterpreterPython::WatchpointCallbackFunction(
2107     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2108   WatchpointOptions::CommandData *wp_option_data =
2109       (WatchpointOptions::CommandData *)baton;
2110   const char *python_function_name = wp_option_data->script_source.c_str();
2111 
2112   if (!context)
2113     return true;
2114 
2115   ExecutionContext exe_ctx(context->exe_ctx_ref);
2116   Target *target = exe_ctx.GetTargetPtr();
2117 
2118   if (!target)
2119     return true;
2120 
2121   Debugger &debugger = target->GetDebugger();
2122   ScriptInterpreter *script_interpreter =
2123       debugger.GetCommandInterpreter().GetScriptInterpreter();
2124   ScriptInterpreterPython *python_interpreter =
2125       (ScriptInterpreterPython *)script_interpreter;
2126 
2127   if (!script_interpreter)
2128     return true;
2129 
2130   if (python_function_name && python_function_name[0]) {
2131     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2132     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2133     if (wp_sp) {
2134       if (stop_frame_sp && wp_sp) {
2135         bool ret_val = true;
2136         {
2137           Locker py_lock(python_interpreter, Locker::AcquireLock |
2138                                                  Locker::InitSession |
2139                                                  Locker::NoSTDIN);
2140           ret_val = g_swig_watchpoint_callback(
2141               python_function_name,
2142               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2143               wp_sp);
2144         }
2145         return ret_val;
2146       }
2147     }
2148   }
2149   // We currently always true so we stop in case anything goes wrong when
2150   // trying to call the script function
2151   return true;
2152 }
2153 
2154 size_t ScriptInterpreterPython::CalculateNumChildren(
2155     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
2156   if (!implementor_sp)
2157     return 0;
2158   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2159   if (!generic)
2160     return 0;
2161   void *implementor = generic->GetValue();
2162   if (!implementor)
2163     return 0;
2164 
2165   if (!g_swig_calc_children)
2166     return 0;
2167 
2168   size_t ret_val = 0;
2169 
2170   {
2171     Locker py_lock(this,
2172                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2173     ret_val = g_swig_calc_children(implementor, max);
2174   }
2175 
2176   return ret_val;
2177 }
2178 
2179 lldb::ValueObjectSP ScriptInterpreterPython::GetChildAtIndex(
2180     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
2181   if (!implementor_sp)
2182     return lldb::ValueObjectSP();
2183 
2184   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2185   if (!generic)
2186     return lldb::ValueObjectSP();
2187   void *implementor = generic->GetValue();
2188   if (!implementor)
2189     return lldb::ValueObjectSP();
2190 
2191   if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
2192     return lldb::ValueObjectSP();
2193 
2194   lldb::ValueObjectSP ret_val;
2195 
2196   {
2197     Locker py_lock(this,
2198                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2199     void *child_ptr = g_swig_get_child_index(implementor, idx);
2200     if (child_ptr != nullptr && child_ptr != Py_None) {
2201       lldb::SBValue *sb_value_ptr =
2202           (lldb::SBValue *)g_swig_cast_to_sbvalue(child_ptr);
2203       if (sb_value_ptr == nullptr)
2204         Py_XDECREF(child_ptr);
2205       else
2206         ret_val = g_swig_get_valobj_sp_from_sbvalue(sb_value_ptr);
2207     } else {
2208       Py_XDECREF(child_ptr);
2209     }
2210   }
2211 
2212   return ret_val;
2213 }
2214 
2215 int ScriptInterpreterPython::GetIndexOfChildWithName(
2216     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
2217   if (!implementor_sp)
2218     return UINT32_MAX;
2219 
2220   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2221   if (!generic)
2222     return UINT32_MAX;
2223   void *implementor = generic->GetValue();
2224   if (!implementor)
2225     return UINT32_MAX;
2226 
2227   if (!g_swig_get_index_child)
2228     return UINT32_MAX;
2229 
2230   int ret_val = UINT32_MAX;
2231 
2232   {
2233     Locker py_lock(this,
2234                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2235     ret_val = g_swig_get_index_child(implementor, child_name);
2236   }
2237 
2238   return ret_val;
2239 }
2240 
2241 bool ScriptInterpreterPython::UpdateSynthProviderInstance(
2242     const StructuredData::ObjectSP &implementor_sp) {
2243   bool ret_val = false;
2244 
2245   if (!implementor_sp)
2246     return ret_val;
2247 
2248   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2249   if (!generic)
2250     return ret_val;
2251   void *implementor = generic->GetValue();
2252   if (!implementor)
2253     return ret_val;
2254 
2255   if (!g_swig_update_provider)
2256     return ret_val;
2257 
2258   {
2259     Locker py_lock(this,
2260                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2261     ret_val = g_swig_update_provider(implementor);
2262   }
2263 
2264   return ret_val;
2265 }
2266 
2267 bool ScriptInterpreterPython::MightHaveChildrenSynthProviderInstance(
2268     const StructuredData::ObjectSP &implementor_sp) {
2269   bool ret_val = false;
2270 
2271   if (!implementor_sp)
2272     return ret_val;
2273 
2274   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2275   if (!generic)
2276     return ret_val;
2277   void *implementor = generic->GetValue();
2278   if (!implementor)
2279     return ret_val;
2280 
2281   if (!g_swig_mighthavechildren_provider)
2282     return ret_val;
2283 
2284   {
2285     Locker py_lock(this,
2286                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2287     ret_val = g_swig_mighthavechildren_provider(implementor);
2288   }
2289 
2290   return ret_val;
2291 }
2292 
2293 lldb::ValueObjectSP ScriptInterpreterPython::GetSyntheticValue(
2294     const StructuredData::ObjectSP &implementor_sp) {
2295   lldb::ValueObjectSP ret_val(nullptr);
2296 
2297   if (!implementor_sp)
2298     return ret_val;
2299 
2300   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2301   if (!generic)
2302     return ret_val;
2303   void *implementor = generic->GetValue();
2304   if (!implementor)
2305     return ret_val;
2306 
2307   if (!g_swig_getvalue_provider || !g_swig_cast_to_sbvalue ||
2308       !g_swig_get_valobj_sp_from_sbvalue)
2309     return ret_val;
2310 
2311   {
2312     Locker py_lock(this,
2313                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2314     void *child_ptr = g_swig_getvalue_provider(implementor);
2315     if (child_ptr != nullptr && child_ptr != Py_None) {
2316       lldb::SBValue *sb_value_ptr =
2317           (lldb::SBValue *)g_swig_cast_to_sbvalue(child_ptr);
2318       if (sb_value_ptr == nullptr)
2319         Py_XDECREF(child_ptr);
2320       else
2321         ret_val = g_swig_get_valobj_sp_from_sbvalue(sb_value_ptr);
2322     } else {
2323       Py_XDECREF(child_ptr);
2324     }
2325   }
2326 
2327   return ret_val;
2328 }
2329 
2330 ConstString ScriptInterpreterPython::GetSyntheticTypeName(
2331     const StructuredData::ObjectSP &implementor_sp) {
2332   Locker py_lock(this,
2333                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2334 
2335   static char callee_name[] = "get_type_name";
2336 
2337   ConstString ret_val;
2338   bool got_string = false;
2339   std::string buffer;
2340 
2341   if (!implementor_sp)
2342     return ret_val;
2343 
2344   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2345   if (!generic)
2346     return ret_val;
2347   PythonObject implementor(PyRefType::Borrowed,
2348                            (PyObject *)generic->GetValue());
2349   if (!implementor.IsAllocated())
2350     return ret_val;
2351 
2352   PythonObject pmeth(PyRefType::Owned,
2353                      PyObject_GetAttrString(implementor.get(), callee_name));
2354 
2355   if (PyErr_Occurred())
2356     PyErr_Clear();
2357 
2358   if (!pmeth.IsAllocated())
2359     return ret_val;
2360 
2361   if (PyCallable_Check(pmeth.get()) == 0) {
2362     if (PyErr_Occurred())
2363       PyErr_Clear();
2364     return ret_val;
2365   }
2366 
2367   if (PyErr_Occurred())
2368     PyErr_Clear();
2369 
2370   // right now we know this function exists and is callable..
2371   PythonObject py_return(
2372       PyRefType::Owned,
2373       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
2374 
2375   // if it fails, print the error but otherwise go on
2376   if (PyErr_Occurred()) {
2377     PyErr_Print();
2378     PyErr_Clear();
2379   }
2380 
2381   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2382     PythonString py_string(PyRefType::Borrowed, py_return.get());
2383     llvm::StringRef return_data(py_string.GetString());
2384     if (!return_data.empty()) {
2385       buffer.assign(return_data.data(), return_data.size());
2386       got_string = true;
2387     }
2388   }
2389 
2390   if (got_string)
2391     ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
2392 
2393   return ret_val;
2394 }
2395 
2396 bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function,
2397                                                      Process *process,
2398                                                      std::string &output,
2399                                                      Error &error) {
2400   bool ret_val;
2401   if (!process) {
2402     error.SetErrorString("no process");
2403     return false;
2404   }
2405   if (!impl_function || !impl_function[0]) {
2406     error.SetErrorString("no function to execute");
2407     return false;
2408   }
2409   if (!g_swig_run_script_keyword_process) {
2410     error.SetErrorString("internal helper function missing");
2411     return false;
2412   }
2413   {
2414     ProcessSP process_sp(process->shared_from_this());
2415     Locker py_lock(this,
2416                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2417     ret_val = g_swig_run_script_keyword_process(
2418         impl_function, m_dictionary_name.c_str(), process_sp, output);
2419     if (!ret_val)
2420       error.SetErrorString("python script evaluation failed");
2421   }
2422   return ret_val;
2423 }
2424 
2425 bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function,
2426                                                      Thread *thread,
2427                                                      std::string &output,
2428                                                      Error &error) {
2429   bool ret_val;
2430   if (!thread) {
2431     error.SetErrorString("no thread");
2432     return false;
2433   }
2434   if (!impl_function || !impl_function[0]) {
2435     error.SetErrorString("no function to execute");
2436     return false;
2437   }
2438   if (!g_swig_run_script_keyword_thread) {
2439     error.SetErrorString("internal helper function missing");
2440     return false;
2441   }
2442   {
2443     ThreadSP thread_sp(thread->shared_from_this());
2444     Locker py_lock(this,
2445                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2446     ret_val = g_swig_run_script_keyword_thread(
2447         impl_function, m_dictionary_name.c_str(), thread_sp, output);
2448     if (!ret_val)
2449       error.SetErrorString("python script evaluation failed");
2450   }
2451   return ret_val;
2452 }
2453 
2454 bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function,
2455                                                      Target *target,
2456                                                      std::string &output,
2457                                                      Error &error) {
2458   bool ret_val;
2459   if (!target) {
2460     error.SetErrorString("no thread");
2461     return false;
2462   }
2463   if (!impl_function || !impl_function[0]) {
2464     error.SetErrorString("no function to execute");
2465     return false;
2466   }
2467   if (!g_swig_run_script_keyword_target) {
2468     error.SetErrorString("internal helper function missing");
2469     return false;
2470   }
2471   {
2472     TargetSP target_sp(target->shared_from_this());
2473     Locker py_lock(this,
2474                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2475     ret_val = g_swig_run_script_keyword_target(
2476         impl_function, m_dictionary_name.c_str(), target_sp, output);
2477     if (!ret_val)
2478       error.SetErrorString("python script evaluation failed");
2479   }
2480   return ret_val;
2481 }
2482 
2483 bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function,
2484                                                      StackFrame *frame,
2485                                                      std::string &output,
2486                                                      Error &error) {
2487   bool ret_val;
2488   if (!frame) {
2489     error.SetErrorString("no frame");
2490     return false;
2491   }
2492   if (!impl_function || !impl_function[0]) {
2493     error.SetErrorString("no function to execute");
2494     return false;
2495   }
2496   if (!g_swig_run_script_keyword_frame) {
2497     error.SetErrorString("internal helper function missing");
2498     return false;
2499   }
2500   {
2501     StackFrameSP frame_sp(frame->shared_from_this());
2502     Locker py_lock(this,
2503                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2504     ret_val = g_swig_run_script_keyword_frame(
2505         impl_function, m_dictionary_name.c_str(), frame_sp, output);
2506     if (!ret_val)
2507       error.SetErrorString("python script evaluation failed");
2508   }
2509   return ret_val;
2510 }
2511 
2512 bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function,
2513                                                      ValueObject *value,
2514                                                      std::string &output,
2515                                                      Error &error) {
2516   bool ret_val;
2517   if (!value) {
2518     error.SetErrorString("no value");
2519     return false;
2520   }
2521   if (!impl_function || !impl_function[0]) {
2522     error.SetErrorString("no function to execute");
2523     return false;
2524   }
2525   if (!g_swig_run_script_keyword_value) {
2526     error.SetErrorString("internal helper function missing");
2527     return false;
2528   }
2529   {
2530     ValueObjectSP value_sp(value->GetSP());
2531     Locker py_lock(this,
2532                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2533     ret_val = g_swig_run_script_keyword_value(
2534         impl_function, m_dictionary_name.c_str(), value_sp, output);
2535     if (!ret_val)
2536       error.SetErrorString("python script evaluation failed");
2537   }
2538   return ret_val;
2539 }
2540 
2541 uint64_t replace_all(std::string &str, const std::string &oldStr,
2542                      const std::string &newStr) {
2543   size_t pos = 0;
2544   uint64_t matches = 0;
2545   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2546     matches++;
2547     str.replace(pos, oldStr.length(), newStr);
2548     pos += newStr.length();
2549   }
2550   return matches;
2551 }
2552 
2553 bool ScriptInterpreterPython::LoadScriptingModule(
2554     const char *pathname, bool can_reload, bool init_session,
2555     lldb_private::Error &error, StructuredData::ObjectSP *module_sp) {
2556   if (!pathname || !pathname[0]) {
2557     error.SetErrorString("invalid pathname");
2558     return false;
2559   }
2560 
2561   if (!g_swig_call_module_init) {
2562     error.SetErrorString("internal helper function missing");
2563     return false;
2564   }
2565 
2566   lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
2567 
2568   {
2569     FileSpec target_file(pathname, true);
2570     std::string basename(target_file.GetFilename().GetCString());
2571 
2572     StreamString command_stream;
2573 
2574     // Before executing Python code, lock the GIL.
2575     Locker py_lock(this, Locker::AcquireLock |
2576                              (init_session ? Locker::InitSession : 0) |
2577                              Locker::NoSTDIN,
2578                    Locker::FreeAcquiredLock |
2579                        (init_session ? Locker::TearDownSession : 0));
2580 
2581     if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
2582         target_file.GetFileType() == FileSpec::eFileTypeUnknown) {
2583       // if not a valid file of any sort, check if it might be a filename still
2584       // dot can't be used but / and \ can, and if either is found, reject
2585       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2586         error.SetErrorString("invalid pathname");
2587         return false;
2588       }
2589       basename = pathname; // not a filename, probably a package of some sort,
2590                            // let it go through
2591     } else if (target_file.GetFileType() == FileSpec::eFileTypeDirectory ||
2592                target_file.GetFileType() == FileSpec::eFileTypeRegular ||
2593                target_file.GetFileType() == FileSpec::eFileTypeSymbolicLink) {
2594       std::string directory = target_file.GetDirectory().GetCString();
2595       replace_all(directory, "\\", "\\\\");
2596       replace_all(directory, "'", "\\'");
2597 
2598       // now make sure that Python has "directory" in the search path
2599       StreamString command_stream;
2600       command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
2601                             "sys.path.insert(1,'%s');\n\n",
2602                             directory.c_str(), directory.c_str());
2603       bool syspath_retval =
2604           ExecuteMultipleLines(command_stream.GetData(),
2605                                ScriptInterpreter::ExecuteScriptOptions()
2606                                    .SetEnableIO(false)
2607                                    .SetSetLLDBGlobals(false))
2608               .Success();
2609       if (!syspath_retval) {
2610         error.SetErrorString("Python sys.path handling failed");
2611         return false;
2612       }
2613 
2614       // strip .py or .pyc extension
2615       ConstString extension = target_file.GetFileNameExtension();
2616       if (extension) {
2617         if (::strcmp(extension.GetCString(), "py") == 0)
2618           basename.resize(basename.length() - 3);
2619         else if (::strcmp(extension.GetCString(), "pyc") == 0)
2620           basename.resize(basename.length() - 4);
2621       }
2622     } else {
2623       error.SetErrorString("no known way to import this module specification");
2624       return false;
2625     }
2626 
2627     // check if the module is already import-ed
2628     command_stream.Clear();
2629     command_stream.Printf("sys.modules.__contains__('%s')", basename.c_str());
2630     bool does_contain = false;
2631     // this call will succeed if the module was ever imported in any Debugger in
2632     // the lifetime of the process
2633     // in which this LLDB framework is living
2634     bool was_imported_globally =
2635         (ExecuteOneLineWithReturn(
2636              command_stream.GetData(),
2637              ScriptInterpreterPython::eScriptReturnTypeBool, &does_contain,
2638              ScriptInterpreter::ExecuteScriptOptions()
2639                  .SetEnableIO(false)
2640                  .SetSetLLDBGlobals(false)) &&
2641          does_contain);
2642     // this call will fail if the module was not imported in this Debugger
2643     // before
2644     command_stream.Clear();
2645     command_stream.Printf("sys.getrefcount(%s)", basename.c_str());
2646     bool was_imported_locally = GetSessionDictionary()
2647                                     .GetItemForKey(PythonString(basename))
2648                                     .IsAllocated();
2649 
2650     bool was_imported = (was_imported_globally || was_imported_locally);
2651 
2652     if (was_imported == true && can_reload == false) {
2653       error.SetErrorString("module already imported");
2654       return false;
2655     }
2656 
2657     // now actually do the import
2658     command_stream.Clear();
2659 
2660     if (was_imported) {
2661       if (!was_imported_locally)
2662         command_stream.Printf("import %s ; reload_module(%s)", basename.c_str(),
2663                               basename.c_str());
2664       else
2665         command_stream.Printf("reload_module(%s)", basename.c_str());
2666     } else
2667       command_stream.Printf("import %s", basename.c_str());
2668 
2669     error = ExecuteMultipleLines(command_stream.GetData(),
2670                                  ScriptInterpreter::ExecuteScriptOptions()
2671                                      .SetEnableIO(false)
2672                                      .SetSetLLDBGlobals(false));
2673     if (error.Fail())
2674       return false;
2675 
2676     // if we are here, everything worked
2677     // call __lldb_init_module(debugger,dict)
2678     if (!g_swig_call_module_init(basename.c_str(), m_dictionary_name.c_str(),
2679                                  debugger_sp)) {
2680       error.SetErrorString("calling __lldb_init_module failed");
2681       return false;
2682     }
2683 
2684     if (module_sp) {
2685       // everything went just great, now set the module object
2686       command_stream.Clear();
2687       command_stream.Printf("%s", basename.c_str());
2688       void *module_pyobj = nullptr;
2689       if (ExecuteOneLineWithReturn(
2690               command_stream.GetData(),
2691               ScriptInterpreter::eScriptReturnTypeOpaqueObject,
2692               &module_pyobj) &&
2693           module_pyobj)
2694         module_sp->reset(new StructuredPythonObject(module_pyobj));
2695     }
2696 
2697     return true;
2698   }
2699 }
2700 
2701 bool ScriptInterpreterPython::IsReservedWord(const char *word) {
2702   if (!word || !word[0])
2703     return false;
2704 
2705   llvm::StringRef word_sr(word);
2706 
2707   // filter out a few characters that would just confuse us
2708   // and that are clearly not keyword material anyway
2709   if (word_sr.find_first_of("'\"") != llvm::StringRef::npos)
2710     return false;
2711 
2712   StreamString command_stream;
2713   command_stream.Printf("keyword.iskeyword('%s')", word);
2714   bool result;
2715   ExecuteScriptOptions options;
2716   options.SetEnableIO(false);
2717   options.SetMaskoutErrors(true);
2718   options.SetSetLLDBGlobals(false);
2719   if (ExecuteOneLineWithReturn(command_stream.GetData(),
2720                                ScriptInterpreter::eScriptReturnTypeBool,
2721                                &result, options))
2722     return result;
2723   return false;
2724 }
2725 
2726 ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler(
2727     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2728     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2729       m_old_asynch(debugger_sp->GetAsyncExecution()) {
2730   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2731     m_debugger_sp->SetAsyncExecution(false);
2732   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2733     m_debugger_sp->SetAsyncExecution(true);
2734 }
2735 
2736 ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler() {
2737   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2738     m_debugger_sp->SetAsyncExecution(m_old_asynch);
2739 }
2740 
2741 bool ScriptInterpreterPython::RunScriptBasedCommand(
2742     const char *impl_function, const char *args,
2743     ScriptedCommandSynchronicity synchronicity,
2744     lldb_private::CommandReturnObject &cmd_retobj, Error &error,
2745     const lldb_private::ExecutionContext &exe_ctx) {
2746   if (!impl_function) {
2747     error.SetErrorString("no function to execute");
2748     return false;
2749   }
2750 
2751   if (!g_swig_call_command) {
2752     error.SetErrorString("no helper function to run scripted commands");
2753     return false;
2754   }
2755 
2756   lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
2757   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2758 
2759   if (!debugger_sp.get()) {
2760     error.SetErrorString("invalid Debugger pointer");
2761     return false;
2762   }
2763 
2764   bool ret_val = false;
2765 
2766   std::string err_msg;
2767 
2768   {
2769     Locker py_lock(this,
2770                    Locker::AcquireLock | Locker::InitSession |
2771                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2772                    Locker::FreeLock | Locker::TearDownSession);
2773 
2774     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2775 
2776     ret_val =
2777         g_swig_call_command(impl_function, m_dictionary_name.c_str(),
2778                             debugger_sp, args, cmd_retobj, exe_ctx_ref_sp);
2779   }
2780 
2781   if (!ret_val)
2782     error.SetErrorString("unable to execute script function");
2783   else
2784     error.Clear();
2785 
2786   return ret_val;
2787 }
2788 
2789 bool ScriptInterpreterPython::RunScriptBasedCommand(
2790     StructuredData::GenericSP impl_obj_sp, const char *args,
2791     ScriptedCommandSynchronicity synchronicity,
2792     lldb_private::CommandReturnObject &cmd_retobj, Error &error,
2793     const lldb_private::ExecutionContext &exe_ctx) {
2794   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2795     error.SetErrorString("no function to execute");
2796     return false;
2797   }
2798 
2799   if (!g_swig_call_command_object) {
2800     error.SetErrorString("no helper function to run scripted commands");
2801     return false;
2802   }
2803 
2804   lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
2805   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2806 
2807   if (!debugger_sp.get()) {
2808     error.SetErrorString("invalid Debugger pointer");
2809     return false;
2810   }
2811 
2812   bool ret_val = false;
2813 
2814   std::string err_msg;
2815 
2816   {
2817     Locker py_lock(this,
2818                    Locker::AcquireLock | Locker::InitSession |
2819                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2820                    Locker::FreeLock | Locker::TearDownSession);
2821 
2822     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2823 
2824     ret_val = g_swig_call_command_object(impl_obj_sp->GetValue(), debugger_sp,
2825                                          args, cmd_retobj, exe_ctx_ref_sp);
2826   }
2827 
2828   if (!ret_val)
2829     error.SetErrorString("unable to execute script function");
2830   else
2831     error.Clear();
2832 
2833   return ret_val;
2834 }
2835 
2836 // in Python, a special attribute __doc__ contains the docstring
2837 // for an object (function, method, class, ...) if any is defined
2838 // Otherwise, the attribute's value is None
2839 bool ScriptInterpreterPython::GetDocumentationForItem(const char *item,
2840                                                       std::string &dest) {
2841   dest.clear();
2842   if (!item || !*item)
2843     return false;
2844   std::string command(item);
2845   command += ".__doc__";
2846 
2847   char *result_ptr = nullptr; // Python is going to point this to valid data if
2848                               // ExecuteOneLineWithReturn returns successfully
2849 
2850   if (ExecuteOneLineWithReturn(
2851           command.c_str(), ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
2852           &result_ptr,
2853           ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false))) {
2854     if (result_ptr)
2855       dest.assign(result_ptr);
2856     return true;
2857   } else {
2858     StreamString str_stream;
2859     str_stream.Printf(
2860         "Function %s was not found. Containing module might be missing.", item);
2861     dest.assign(str_stream.GetData());
2862     return false;
2863   }
2864 }
2865 
2866 bool ScriptInterpreterPython::GetShortHelpForCommandObject(
2867     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2868   bool got_string = false;
2869   dest.clear();
2870 
2871   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2872 
2873   static char callee_name[] = "get_short_help";
2874 
2875   if (!cmd_obj_sp)
2876     return false;
2877 
2878   PythonObject implementor(PyRefType::Borrowed,
2879                            (PyObject *)cmd_obj_sp->GetValue());
2880 
2881   if (!implementor.IsAllocated())
2882     return false;
2883 
2884   PythonObject pmeth(PyRefType::Owned,
2885                      PyObject_GetAttrString(implementor.get(), callee_name));
2886 
2887   if (PyErr_Occurred())
2888     PyErr_Clear();
2889 
2890   if (!pmeth.IsAllocated())
2891     return false;
2892 
2893   if (PyCallable_Check(pmeth.get()) == 0) {
2894     if (PyErr_Occurred())
2895       PyErr_Clear();
2896     return false;
2897   }
2898 
2899   if (PyErr_Occurred())
2900     PyErr_Clear();
2901 
2902   // right now we know this function exists and is callable..
2903   PythonObject py_return(
2904       PyRefType::Owned,
2905       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
2906 
2907   // if it fails, print the error but otherwise go on
2908   if (PyErr_Occurred()) {
2909     PyErr_Print();
2910     PyErr_Clear();
2911   }
2912 
2913   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2914     PythonString py_string(PyRefType::Borrowed, py_return.get());
2915     llvm::StringRef return_data(py_string.GetString());
2916     dest.assign(return_data.data(), return_data.size());
2917     got_string = true;
2918   }
2919   return got_string;
2920 }
2921 
2922 uint32_t ScriptInterpreterPython::GetFlagsForCommandObject(
2923     StructuredData::GenericSP cmd_obj_sp) {
2924   uint32_t result = 0;
2925 
2926   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2927 
2928   static char callee_name[] = "get_flags";
2929 
2930   if (!cmd_obj_sp)
2931     return result;
2932 
2933   PythonObject implementor(PyRefType::Borrowed,
2934                            (PyObject *)cmd_obj_sp->GetValue());
2935 
2936   if (!implementor.IsAllocated())
2937     return result;
2938 
2939   PythonObject pmeth(PyRefType::Owned,
2940                      PyObject_GetAttrString(implementor.get(), callee_name));
2941 
2942   if (PyErr_Occurred())
2943     PyErr_Clear();
2944 
2945   if (!pmeth.IsAllocated())
2946     return result;
2947 
2948   if (PyCallable_Check(pmeth.get()) == 0) {
2949     if (PyErr_Occurred())
2950       PyErr_Clear();
2951     return result;
2952   }
2953 
2954   if (PyErr_Occurred())
2955     PyErr_Clear();
2956 
2957   // right now we know this function exists and is callable..
2958   PythonObject py_return(
2959       PyRefType::Owned,
2960       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
2961 
2962   // if it fails, print the error but otherwise go on
2963   if (PyErr_Occurred()) {
2964     PyErr_Print();
2965     PyErr_Clear();
2966   }
2967 
2968   if (py_return.IsAllocated() && PythonInteger::Check(py_return.get())) {
2969     PythonInteger int_value(PyRefType::Borrowed, py_return.get());
2970     result = int_value.GetInteger();
2971   }
2972 
2973   return result;
2974 }
2975 
2976 bool ScriptInterpreterPython::GetLongHelpForCommandObject(
2977     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2978   bool got_string = false;
2979   dest.clear();
2980 
2981   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2982 
2983   static char callee_name[] = "get_long_help";
2984 
2985   if (!cmd_obj_sp)
2986     return false;
2987 
2988   PythonObject implementor(PyRefType::Borrowed,
2989                            (PyObject *)cmd_obj_sp->GetValue());
2990 
2991   if (!implementor.IsAllocated())
2992     return false;
2993 
2994   PythonObject pmeth(PyRefType::Owned,
2995                      PyObject_GetAttrString(implementor.get(), callee_name));
2996 
2997   if (PyErr_Occurred())
2998     PyErr_Clear();
2999 
3000   if (!pmeth.IsAllocated())
3001     return false;
3002 
3003   if (PyCallable_Check(pmeth.get()) == 0) {
3004     if (PyErr_Occurred())
3005       PyErr_Clear();
3006 
3007     return false;
3008   }
3009 
3010   if (PyErr_Occurred())
3011     PyErr_Clear();
3012 
3013   // right now we know this function exists and is callable..
3014   PythonObject py_return(
3015       PyRefType::Owned,
3016       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3017 
3018   // if it fails, print the error but otherwise go on
3019   if (PyErr_Occurred()) {
3020     PyErr_Print();
3021     PyErr_Clear();
3022   }
3023 
3024   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3025     PythonString str(PyRefType::Borrowed, py_return.get());
3026     llvm::StringRef str_data(str.GetString());
3027     dest.assign(str_data.data(), str_data.size());
3028     got_string = true;
3029   }
3030 
3031   return got_string;
3032 }
3033 
3034 std::unique_ptr<ScriptInterpreterLocker>
3035 ScriptInterpreterPython::AcquireInterpreterLock() {
3036   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3037       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3038       Locker::FreeLock | Locker::TearDownSession));
3039   return py_lock;
3040 }
3041 
3042 void ScriptInterpreterPython::InitializeInterpreter(
3043     SWIGInitCallback swig_init_callback,
3044     SWIGBreakpointCallbackFunction swig_breakpoint_callback,
3045     SWIGWatchpointCallbackFunction swig_watchpoint_callback,
3046     SWIGPythonTypeScriptCallbackFunction swig_typescript_callback,
3047     SWIGPythonCreateSyntheticProvider swig_synthetic_script,
3048     SWIGPythonCreateCommandObject swig_create_cmd,
3049     SWIGPythonCalculateNumChildren swig_calc_children,
3050     SWIGPythonGetChildAtIndex swig_get_child_index,
3051     SWIGPythonGetIndexOfChildWithName swig_get_index_child,
3052     SWIGPythonCastPyObjectToSBValue swig_cast_to_sbvalue,
3053     SWIGPythonGetValueObjectSPFromSBValue swig_get_valobj_sp_from_sbvalue,
3054     SWIGPythonUpdateSynthProviderInstance swig_update_provider,
3055     SWIGPythonMightHaveChildrenSynthProviderInstance
3056         swig_mighthavechildren_provider,
3057     SWIGPythonGetValueSynthProviderInstance swig_getvalue_provider,
3058     SWIGPythonCallCommand swig_call_command,
3059     SWIGPythonCallCommandObject swig_call_command_object,
3060     SWIGPythonCallModuleInit swig_call_module_init,
3061     SWIGPythonCreateOSPlugin swig_create_os_plugin,
3062     SWIGPythonScriptKeyword_Process swig_run_script_keyword_process,
3063     SWIGPythonScriptKeyword_Thread swig_run_script_keyword_thread,
3064     SWIGPythonScriptKeyword_Target swig_run_script_keyword_target,
3065     SWIGPythonScriptKeyword_Frame swig_run_script_keyword_frame,
3066     SWIGPythonScriptKeyword_Value swig_run_script_keyword_value,
3067     SWIGPython_GetDynamicSetting swig_plugin_get,
3068     SWIGPythonCreateScriptedThreadPlan swig_thread_plan_script,
3069     SWIGPythonCallThreadPlan swig_call_thread_plan) {
3070   g_swig_init_callback = swig_init_callback;
3071   g_swig_breakpoint_callback = swig_breakpoint_callback;
3072   g_swig_watchpoint_callback = swig_watchpoint_callback;
3073   g_swig_typescript_callback = swig_typescript_callback;
3074   g_swig_synthetic_script = swig_synthetic_script;
3075   g_swig_create_cmd = swig_create_cmd;
3076   g_swig_calc_children = swig_calc_children;
3077   g_swig_get_child_index = swig_get_child_index;
3078   g_swig_get_index_child = swig_get_index_child;
3079   g_swig_cast_to_sbvalue = swig_cast_to_sbvalue;
3080   g_swig_get_valobj_sp_from_sbvalue = swig_get_valobj_sp_from_sbvalue;
3081   g_swig_update_provider = swig_update_provider;
3082   g_swig_mighthavechildren_provider = swig_mighthavechildren_provider;
3083   g_swig_getvalue_provider = swig_getvalue_provider;
3084   g_swig_call_command = swig_call_command;
3085   g_swig_call_command_object = swig_call_command_object;
3086   g_swig_call_module_init = swig_call_module_init;
3087   g_swig_create_os_plugin = swig_create_os_plugin;
3088   g_swig_run_script_keyword_process = swig_run_script_keyword_process;
3089   g_swig_run_script_keyword_thread = swig_run_script_keyword_thread;
3090   g_swig_run_script_keyword_target = swig_run_script_keyword_target;
3091   g_swig_run_script_keyword_frame = swig_run_script_keyword_frame;
3092   g_swig_run_script_keyword_value = swig_run_script_keyword_value;
3093   g_swig_plugin_get = swig_plugin_get;
3094   g_swig_thread_plan_script = swig_thread_plan_script;
3095   g_swig_call_thread_plan = swig_call_thread_plan;
3096 }
3097 
3098 void ScriptInterpreterPython::InitializePrivate() {
3099   if (g_initialized)
3100     return;
3101 
3102   g_initialized = true;
3103 
3104   Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION);
3105 
3106   // RAII-based initialization which correctly handles multiple-initialization,
3107   // version-
3108   // specific differences among Python 2 and Python 3, and saving and restoring
3109   // various
3110   // other pieces of state that can get mucked with during initialization.
3111   InitializePythonRAII initialize_guard;
3112 
3113   if (g_swig_init_callback)
3114     g_swig_init_callback();
3115 
3116   // Update the path python uses to search for modules to include the current
3117   // directory.
3118 
3119   PyRun_SimpleString("import sys");
3120   AddToSysPath(AddLocation::End, ".");
3121 
3122   FileSpec file_spec;
3123   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
3124   // that use
3125   // a backslash as the path separator, this will result in executing python
3126   // code containing
3127   // paths with unescaped backslashes.  But Python also accepts forward slashes,
3128   // so to make
3129   // life easier we just use that.
3130   if (HostInfo::GetLLDBPath(ePathTypePythonDir, file_spec))
3131     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3132   if (HostInfo::GetLLDBPath(ePathTypeLLDBShlibDir, file_spec))
3133     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3134 
3135   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3136                      "lldb.embedded_interpreter; from "
3137                      "lldb.embedded_interpreter import run_python_interpreter; "
3138                      "from lldb.embedded_interpreter import run_one_line");
3139 }
3140 
3141 void ScriptInterpreterPython::AddToSysPath(AddLocation location,
3142                                            std::string path) {
3143   std::string path_copy;
3144 
3145   std::string statement;
3146   if (location == AddLocation::Beginning) {
3147     statement.assign("sys.path.insert(0,\"");
3148     statement.append(path);
3149     statement.append("\")");
3150   } else {
3151     statement.assign("sys.path.append(\"");
3152     statement.append(path);
3153     statement.append("\")");
3154   }
3155   PyRun_SimpleString(statement.c_str());
3156 }
3157 
3158 // void
3159 // ScriptInterpreterPython::Terminate ()
3160 //{
3161 //    // We are intentionally NOT calling Py_Finalize here (this would be the
3162 //    logical place to call it).  Calling
3163 //    // Py_Finalize here causes test suite runs to seg fault:  The test suite
3164 //    runs in Python.  It registers
3165 //    // SBDebugger::Terminate to be called 'at_exit'.  When the test suite
3166 //    Python harness finishes up, it calls
3167 //    // Py_Finalize, which calls all the 'at_exit' registered functions.
3168 //    SBDebugger::Terminate calls Debugger::Terminate,
3169 //    // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate,
3170 //    which calls
3171 //    // ScriptInterpreterPython::Terminate.  So if we call Py_Finalize here, we
3172 //    end up with Py_Finalize being called from
3173 //    // within Py_Finalize, which results in a seg fault.
3174 //    //
3175 //    // Since this function only gets called when lldb is shutting down and
3176 //    going away anyway, the fact that we don't
3177 //    // actually call Py_Finalize should not cause any problems (everything
3178 //    should shut down/go away anyway when the
3179 //    // process exits).
3180 //    //
3181 ////    Py_Finalize ();
3182 //}
3183 
3184 #endif // #ifdef LLDB_DISABLE_PYTHON
3185