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