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