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