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