blob: bbaa8b9ad06299d197afa884adc1cb16292a45a7 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- 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// In order to guarantee correct working with Python, Python.h *MUST* be
Greg Clayton17f5afe2011-02-05 02:56:16 +000011// the *FIRST* header file included in ScriptInterpreterPython.h, and that
12// must be the *FIRST* header file included here.
Chris Lattner24943d22010-06-08 16:52:24 +000013
14#include "lldb/Interpreter/ScriptInterpreterPython.h"
15
Chris Lattner24943d22010-06-08 16:52:24 +000016#include <stdlib.h>
17#include <stdio.h>
18
19#include <string>
20
Enrico Granata91544802011-09-06 19:20:51 +000021#include "lldb/API/SBValue.h"
Greg Clayton63094e02010-06-23 01:19:29 +000022#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner24943d22010-06-08 16:52:24 +000023#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Core/Timer.h"
25#include "lldb/Host/Host.h"
26#include "lldb/Interpreter/CommandInterpreter.h"
27#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton5144f382010-10-07 17:14:24 +000028#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000029
Chris Lattner24943d22010-06-08 16:52:24 +000030using namespace lldb;
31using namespace lldb_private;
32
Greg Claytone86cbb92011-03-22 01:14:58 +000033
34static ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL;
35static ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL;
Enrico Granataf7a9b142011-07-15 02:26:42 +000036static ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL;
Enrico Granata9ae7cef2011-07-24 00:14:56 +000037static ScriptInterpreter::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = NULL;
38static ScriptInterpreter::SWIGPythonCalculateNumChildren g_swig_calc_children = NULL;
39static ScriptInterpreter::SWIGPythonGetChildAtIndex g_swig_get_child_index = NULL;
40static ScriptInterpreter::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = NULL;
41static ScriptInterpreter::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = NULL;
Enrico Granata979e20d2011-07-29 19:53:35 +000042static ScriptInterpreter::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = NULL;
Enrico Granatac2a28252011-08-16 16:49:25 +000043static ScriptInterpreter::SWIGPythonCallCommand g_swig_call_command = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +000044
45static int
46_check_and_flush (FILE *stream)
47{
48 int prev_fail = ferror (stream);
49 return fflush (stream) || prev_fail ? EOF : 0;
50}
51
Caroline Tice202f6b82011-01-17 21:55:19 +000052static Predicate<lldb::tid_t> &
53PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +000054{
Caroline Tice202f6b82011-01-17 21:55:19 +000055 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
56 return g_interpreter_is_running;
57}
58
59static bool
60CurrentThreadHasPythonLock ()
61{
62 TimeValue timeout;
63
64 timeout = TimeValue::Now(); // Don't wait any time.
65
66 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
67}
68
69static bool
70GetPythonLock (uint32_t seconds_to_wait)
71{
72
73 TimeValue timeout;
74
75 if (seconds_to_wait != UINT32_MAX)
76 {
77 timeout = TimeValue::Now();
78 timeout.OffsetWithSeconds (seconds_to_wait);
79 }
80
81 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
82 Host::GetCurrentThreadID(), &timeout, NULL);
83}
84
85static void
86ReleasePythonLock ()
87{
88 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +000089}
90
Enrico Granata91544802011-09-06 19:20:51 +000091ScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *pi,
92 FILE* tmp_fh,
93 bool ns) :
94 m_need_session(ns),
95 m_release_lock(false),
96 m_python_interpreter(pi),
97 m_tmp_fh(tmp_fh)
98{
99 // if Enter/LeaveSession() must be called, then m_python_interpreter must be != NULL
100 assert(m_need_session && m_python_interpreter);
101 if (!CurrentThreadHasPythonLock())
102 {
103 while (!GetPythonLock (1))
104 if (tmp_fh)
105 fprintf (tmp_fh,
106 "Python interpreter locked on another thread; waiting to acquire lock...\n");
107 m_release_lock = true;
108 }
109 if (m_need_session)
110 m_python_interpreter->EnterSession ();
111}
112
113ScriptInterpreterPython::Locker::~Locker()
114{
115 if (m_need_session)
116 m_python_interpreter->LeaveSession ();
117 if (m_release_lock)
118 ReleasePythonLock ();
119}
120
Greg Clayton63094e02010-06-23 01:19:29 +0000121ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000122 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000123 m_embedded_python_pty (),
124 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +0000125 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000126 m_new_sysout (NULL),
127 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000128 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000129 m_session_is_active (false),
130 m_pty_slave_is_open (false),
131 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000132{
133
Greg Clayton7c330d62011-01-27 01:01:10 +0000134 static int g_initialized = false;
135
136 if (!g_initialized)
137 {
138 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000139 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000140 }
141
Caroline Tice202f6b82011-01-17 21:55:19 +0000142 bool safe_to_run = false;
143 bool need_to_release_lock = true;
144 int interval = 5; // Number of seconds to try getting the Python lock before timing out.
145
146 // We don't dare exit this function without finishing setting up the script interpreter, so we must wait until
147 // we can get the Python lock.
148
149 if (CurrentThreadHasPythonLock())
150 {
151 safe_to_run = true;
152 need_to_release_lock = false;
153 }
154
155 while (!safe_to_run)
156 {
157 safe_to_run = GetPythonLock (interval);
158 if (!safe_to_run)
159 {
160 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
161 fprintf (tmp_fh,
162 "Python interpreter is locked on another thread; "
163 "please release interpreter in order to continue.\n");
164 interval = interval * 2;
165 }
166 }
167
Caroline Tice0aa2e552011-01-14 00:29:16 +0000168 m_dictionary_name.append("_dict");
169 StreamString run_string;
170 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
171 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000172
Caroline Tice0aa2e552011-01-14 00:29:16 +0000173 run_string.Clear();
174 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
175 PyRun_SimpleString (run_string.GetData());
176
177 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
178 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
179 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
180 // call to Debugger::Terminate is made, the ref-count has the correct value.
181 //
182 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
183 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000184
Caroline Tice0aa2e552011-01-14 00:29:16 +0000185 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000186
Caroline Tice0aa2e552011-01-14 00:29:16 +0000187 run_string.Clear();
188 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
189 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000190
Caroline Tice0aa2e552011-01-14 00:29:16 +0000191 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000192
Caroline Tice0aa2e552011-01-14 00:29:16 +0000193 if (new_count > old_count)
194 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000195
Caroline Tice0aa2e552011-01-14 00:29:16 +0000196 run_string.Clear();
197 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
198 PyRun_SimpleString (run_string.GetData());
199
200 run_string.Clear();
201 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
202 interpreter.GetDebugger().GetID());
203 PyRun_SimpleString (run_string.GetData());
204
Enrico Granata074e3b62011-08-17 19:07:52 +0000205 run_string.Clear();
Enrico Granata960691f2011-08-22 17:34:47 +0000206 run_string.Printf ("run_one_line (%s, 'import gnu_libstdcpp')", m_dictionary_name.c_str(),
Enrico Granata074e3b62011-08-17 19:07:52 +0000207 interpreter.GetDebugger().GetID());
208 PyRun_SimpleString (run_string.GetData());
209
Caroline Tice0aa2e552011-01-14 00:29:16 +0000210 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000211 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000212 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000213 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000214
215 if (need_to_release_lock)
216 ReleasePythonLock();
Chris Lattner24943d22010-06-08 16:52:24 +0000217}
218
219ScriptInterpreterPython::~ScriptInterpreterPython ()
220{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000221 Debugger &debugger = GetCommandInterpreter().GetDebugger();
222
223 if (m_embedded_thread_input_reader_sp.get() != NULL)
224 {
225 m_embedded_thread_input_reader_sp->SetIsDone (true);
226 m_embedded_python_pty.CloseSlaveFileDescriptor();
227 m_pty_slave_is_open = false;
228 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
229 m_embedded_thread_input_reader_sp.reset();
230 debugger.PopInputReader (reader_sp);
231 }
232
233 if (m_new_sysout)
234 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000235 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
236 if (!CurrentThreadHasPythonLock ())
237 {
238 while (!GetPythonLock (1))
239 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
240 Py_DECREF (m_new_sysout);
241 ReleasePythonLock ();
242 }
243 else
244 Py_DECREF (m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000245 }
Chris Lattner24943d22010-06-08 16:52:24 +0000246}
247
Caroline Tice0aa2e552011-01-14 00:29:16 +0000248void
249ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
250{
251 if (fh == NULL)
252 return;
253
254 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000255
Caroline Tice202f6b82011-01-17 21:55:19 +0000256 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +0000257
258 Locker py_lock(this, tmp_fh);
259
260 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000261}
262
263void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000264ScriptInterpreterPython::SaveTerminalState (int fd)
265{
266 // Python mucks with the terminal state of STDIN. If we can possibly avoid
267 // this by setting the file handles up correctly prior to entering the
268 // interpreter we should. For now we save and restore the terminal state
269 // on the input file handle.
270 m_terminal_state.Save (fd, false);
271}
272
273void
274ScriptInterpreterPython::RestoreTerminalState ()
275{
276 // Python mucks with the terminal state of STDIN. If we can possibly avoid
277 // this by setting the file handles up correctly prior to entering the
278 // interpreter we should. For now we save and restore the terminal state
279 // on the input file handle.
280 m_terminal_state.Restore();
281}
282
283
284
285void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000286ScriptInterpreterPython::LeaveSession ()
287{
288 m_session_is_active = false;
289}
290
291void
292ScriptInterpreterPython::EnterSession ()
293{
294 // If we have already entered the session, without having officially 'left' it, then there is no need to
295 // 'enter' it again.
296
297 if (m_session_is_active)
298 return;
299
300 m_session_is_active = true;
301
Caroline Tice202f6b82011-01-17 21:55:19 +0000302 StreamString run_string;
303
304 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
305 GetCommandInterpreter().GetDebugger().GetID());
306 PyRun_SimpleString (run_string.GetData());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000307 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +0000308
Caroline Tice0aa2e552011-01-14 00:29:16 +0000309
Caroline Tice6af65cb2011-05-03 21:21:50 +0000310 run_string.Printf ("run_one_line (%s, 'lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%d)')",
311 m_dictionary_name.c_str(),
312 GetCommandInterpreter().GetDebugger().GetID());
313 PyRun_SimpleString (run_string.GetData());
314 run_string.Clear();
315
316
317 ExecutionContext exe_ctx = m_interpreter.GetDebugger().GetSelectedExecutionContext();
318
319 if (exe_ctx.target)
320 run_string.Printf ("run_one_line (%s, 'lldb.target = lldb.debugger.GetSelectedTarget()')",
321 m_dictionary_name.c_str());
322 else
323 run_string.Printf ("run_one_line (%s, 'lldb.target = None')", m_dictionary_name.c_str());
324 PyRun_SimpleString (run_string.GetData());
325 run_string.Clear();
326
327 if (exe_ctx.process)
328 run_string.Printf ("run_one_line (%s, 'lldb.process = lldb.target.GetProcess()')", m_dictionary_name.c_str());
329 else
330 run_string.Printf ("run_one_line (%s, 'lldb.process = None')", m_dictionary_name.c_str());
331 PyRun_SimpleString (run_string.GetData());
332 run_string.Clear();
333
334 if (exe_ctx.thread)
335 run_string.Printf ("run_one_line (%s, 'lldb.thread = lldb.process.GetSelectedThread ()')",
336 m_dictionary_name.c_str());
337 else
338 run_string.Printf ("run_one_line (%s, 'lldb.thread = None')", m_dictionary_name.c_str());
339 PyRun_SimpleString (run_string.GetData());
340 run_string.Clear();
341
342 if (exe_ctx.frame)
343 run_string.Printf ("run_one_line (%s, 'lldb.frame = lldb.thread.GetSelectedFrame ()')",
344 m_dictionary_name.c_str());
345 else
346 run_string.Printf ("run_one_line (%s, 'lldb.frame = None')", m_dictionary_name.c_str());
347 PyRun_SimpleString (run_string.GetData());
348 run_string.Clear();
349
Caroline Tice0aa2e552011-01-14 00:29:16 +0000350 PyObject *sysmod = PyImport_AddModule ("sys");
351 PyObject *sysdict = PyModule_GetDict (sysmod);
352
353 if ((m_new_sysout != NULL)
354 && (sysmod != NULL)
355 && (sysdict != NULL))
356 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
357
358 if (PyErr_Occurred())
359 PyErr_Clear ();
360
Caroline Tice0aa2e552011-01-14 00:29:16 +0000361 if (!m_pty_slave_is_open)
362 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000363 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000364 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
365 m_pty_slave_name.c_str());
366 PyRun_SimpleString (run_string.GetData());
367 m_pty_slave_is_open = true;
368
369 run_string.Clear();
370 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
371 PyRun_SimpleString (run_string.GetData());
372 }
373}
374
375
Johnny Chen60dde642010-07-30 22:33:14 +0000376bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000377ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000378{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000379 if (!m_valid_session)
380 return false;
381
Caroline Tice0aa2e552011-01-14 00:29:16 +0000382
Caroline Tice0aa2e552011-01-14 00:29:16 +0000383
Caroline Tice4a461da2011-01-14 21:09:29 +0000384 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
385 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
386 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
387 // method to pass the command string directly down to Python.
388
389
Caroline Tice202f6b82011-01-17 21:55:19 +0000390 bool need_to_release_lock = true;
391
392 if (CurrentThreadHasPythonLock())
393 need_to_release_lock = false;
394 else if (!GetPythonLock (1))
395 {
396 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
397 "Python interpreter is currently locked by another thread; unable to process command.\n");
398 return false;
399 }
400
401 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000402 bool success = false;
403
Greg Clayton63094e02010-06-23 01:19:29 +0000404 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000405 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000406 // Find the correct script interpreter dictionary in the main module.
407 PyObject *main_mod = PyImport_AddModule ("__main__");
408 PyObject *script_interpreter_dict = NULL;
409 if (main_mod != NULL)
410 {
411 PyObject *main_dict = PyModule_GetDict (main_mod);
412 if ((main_dict != NULL)
413 && PyDict_Check (main_dict))
414 {
415 // Go through the main dictionary looking for the correct python script interpreter dictionary
416 PyObject *key, *value;
417 Py_ssize_t pos = 0;
418
419 while (PyDict_Next (main_dict, &pos, &key, &value))
420 {
421 // We have stolen references to the key and value objects in the dictionary; we need to increment
422 // them now so that Python's garbage collector doesn't collect them out from under us.
423 Py_INCREF (key);
424 Py_INCREF (value);
425 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
426 {
427 script_interpreter_dict = value;
428 break;
429 }
430 }
431 }
432
433 if (script_interpreter_dict != NULL)
434 {
435 PyObject *pfunc = NULL;
436 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
437 if (pmod != NULL)
438 {
439 PyObject *pmod_dict = PyModule_GetDict (pmod);
440 if ((pmod_dict != NULL)
441 && PyDict_Check (pmod_dict))
442 {
443 PyObject *key, *value;
444 Py_ssize_t pos = 0;
445
446 while (PyDict_Next (pmod_dict, &pos, &key, &value))
447 {
448 Py_INCREF (key);
449 Py_INCREF (value);
450 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
451 {
452 pfunc = value;
453 break;
454 }
455 }
456
457 PyObject *string_arg = PyString_FromString (command);
458 if (pfunc && string_arg && PyCallable_Check (pfunc))
459 {
460 PyObject *pargs = PyTuple_New (2);
461 if (pargs != NULL)
462 {
463 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
464 PyTuple_SetItem (pargs, 1, string_arg);
465 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
466 Py_DECREF (pargs);
467 if (pvalue != NULL)
468 {
469 Py_DECREF (pvalue);
470 success = true;
471 }
472 else if (PyErr_Occurred ())
473 {
474 PyErr_Print();
475 PyErr_Clear();
476 }
477 }
478 }
479 }
480 }
481 Py_INCREF (script_interpreter_dict);
482 }
483 }
Greg Clayton63094e02010-06-23 01:19:29 +0000484
Caroline Tice0aa2e552011-01-14 00:29:16 +0000485 LeaveSession ();
486
Caroline Tice202f6b82011-01-17 21:55:19 +0000487 if (need_to_release_lock)
488 ReleasePythonLock();
489
Caroline Tice4a461da2011-01-14 21:09:29 +0000490 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000491 return true;
492
493 // The one-liner failed. Append the error message.
494 if (result)
495 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
496 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000497 }
Johnny Chen60dde642010-07-30 22:33:14 +0000498
Caroline Tice0aa2e552011-01-14 00:29:16 +0000499 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000500
501 if (need_to_release_lock)
502 ReleasePythonLock ();
503
Johnny Chen60dde642010-07-30 22:33:14 +0000504 if (result)
505 result->AppendError ("empty command passed to python\n");
506 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000507}
508
509
510
511size_t
512ScriptInterpreterPython::InputReaderCallback
513(
514 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000515 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000516 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000517 const char *bytes,
518 size_t bytes_len
519)
520{
Caroline Tice2ade6112010-11-10 19:18:14 +0000521 lldb::thread_t embedded_interpreter_thread;
522 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
523
Chris Lattner24943d22010-06-08 16:52:24 +0000524 if (baton == NULL)
525 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000526
527 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
528
529 if (script_interpreter->m_script_lang != eScriptLanguagePython)
530 return 0;
531
Caroline Tice892fadd2011-06-16 16:27:19 +0000532 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
533 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
534
Chris Lattner24943d22010-06-08 16:52:24 +0000535 switch (notification)
536 {
537 case eInputReaderActivate:
538 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000539 if (!batch_mode)
540 {
541 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
542 out_stream->Flush();
543 }
Greg Clayton58928562011-02-09 01:08:52 +0000544
Chris Lattner24943d22010-06-08 16:52:24 +0000545 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000546 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
547 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000548 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000549
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000550 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000551
Caroline Tice202f6b82011-01-17 21:55:19 +0000552 if (!CurrentThreadHasPythonLock())
553 {
554 while (!GetPythonLock(1))
555 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000556 out_stream->Printf ("Python interpreter locked on another thread; waiting to acquire lock...\n");
557 out_stream->Flush();
Caroline Tice202f6b82011-01-17 21:55:19 +0000558 }
559 script_interpreter->EnterSession ();
560 ReleasePythonLock();
561 }
562 else
563 script_interpreter->EnterSession ();
564
Caroline Tice2ade6112010-11-10 19:18:14 +0000565 char error_str[1024];
566 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
567 sizeof(error_str)))
568 {
569 if (log)
570 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
571 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
572 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
573 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
574 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000575 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000576 {
577 if (log)
578 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
579 Error detach_error;
580 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
581 }
582 else
583 {
584 if (log)
585 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
586 reader.SetIsDone (true);
587 }
588 }
589 else
590 {
591 if (log)
592 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
593 reader.SetIsDone (true);
594 }
Chris Lattner24943d22010-06-08 16:52:24 +0000595 }
596 break;
597
598 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000599 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000600 break;
601
602 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000603 if (!CurrentThreadHasPythonLock())
604 {
605 while (!GetPythonLock(1))
606 {
607 // Wait until lock is acquired.
608 }
609 script_interpreter->EnterSession ();
610 ReleasePythonLock();
611 }
612 else
613 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000614 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000615
Caroline Tice4a348082011-05-02 20:41:46 +0000616 case eInputReaderAsynchronousOutputWritten:
617 break;
618
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000619 case eInputReaderInterrupt:
620 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
621 break;
622
623 case eInputReaderEndOfFile:
624 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
625 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000626
627 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000628 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000629 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000630 if (log)
631 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
632 bytes_len);
633 if (bytes && bytes_len)
634 {
635 if ((int) bytes[0] == 4)
636 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
637 else
638 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
639 }
640 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000641 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000642 else
643 {
644 if (log)
645 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
646 bytes,
647 bytes_len);
648 reader.SetIsDone (true);
649 }
650
Chris Lattner24943d22010-06-08 16:52:24 +0000651 break;
652
653 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000654 script_interpreter->LeaveSession ();
655
Chris Lattner24943d22010-06-08 16:52:24 +0000656 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000657 if (log)
658 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000659
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000660 script_interpreter->RestoreTerminalState ();
661
Caroline Tice2ade6112010-11-10 19:18:14 +0000662 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000663 break;
664 }
665
666 return bytes_len;
667}
668
669
670void
Greg Clayton238c0a12010-09-18 01:14:36 +0000671ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000672{
673 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
674
Caroline Tice0aa2e552011-01-14 00:29:16 +0000675 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000676
677 // At the moment, the only time the debugger does not have an input file handle is when this is called
678 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
679 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
680 // do it.
681
Greg Clayton58928562011-02-09 01:08:52 +0000682 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000683 return;
684
Greg Clayton63094e02010-06-23 01:19:29 +0000685 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000686 if (reader_sp)
687 {
688 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
689 this, // baton
690 eInputReaderGranularityLine, // token size, to pass to callback function
691 NULL, // end token
692 NULL, // prompt
693 true)); // echo input
694
695 if (error.Success())
696 {
Greg Clayton63094e02010-06-23 01:19:29 +0000697 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000698 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000699 }
700 }
701}
702
703bool
704ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
705 ScriptInterpreter::ReturnType return_type,
706 void *ret_value)
707{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000708
Caroline Tice202f6b82011-01-17 21:55:19 +0000709 bool need_to_release_lock = true;
710
711 if (CurrentThreadHasPythonLock())
712 need_to_release_lock = false;
713 else if (!GetPythonLock (1))
714 {
715 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
716 "Python interpreter is currently locked by another thread; unable to process command.\n");
717 return false;
718 }
719
720 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000721
Chris Lattner24943d22010-06-08 16:52:24 +0000722 PyObject *py_return = NULL;
723 PyObject *mainmod = PyImport_AddModule ("__main__");
724 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000725 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000726 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000727 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000728 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000729 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000730
731 if (PyDict_Check (globals))
732 {
733 PyObject *key, *value;
734 Py_ssize_t pos = 0;
735
736 int i = 0;
737 while (PyDict_Next (globals, &pos, &key, &value))
738 {
739 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
740 // so that Python's garbage collector doesn't collect them out from under us.
741 Py_INCREF (key);
742 Py_INCREF (value);
743 char *c_str = PyString_AsString (key);
744 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
745 locals = value;
746 ++i;
747 }
748 }
Chris Lattner24943d22010-06-08 16:52:24 +0000749
Caroline Tice0aa2e552011-01-14 00:29:16 +0000750 if (locals == NULL)
751 {
752 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
753 should_decrement_locals = true;
754 }
755
756 if (locals == NULL)
757 {
758 locals = globals;
759 should_decrement_locals = false;
760 }
761
762 py_error = PyErr_Occurred();
763 if (py_error != NULL)
764 PyErr_Clear();
765
Chris Lattner24943d22010-06-08 16:52:24 +0000766 if (in_string != NULL)
767 {
768 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
769 if (py_return == NULL)
770 {
771 py_error = PyErr_Occurred ();
772 if (py_error != NULL)
773 PyErr_Clear ();
774
775 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
776 }
777
Caroline Tice0aa2e552011-01-14 00:29:16 +0000778 if (locals != NULL
779 && should_decrement_locals)
780 Py_DECREF (locals);
781
Chris Lattner24943d22010-06-08 16:52:24 +0000782 if (py_return != NULL)
783 {
784 switch (return_type)
785 {
786 case eCharPtr: // "char *"
787 {
788 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000789 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000790 break;
791 }
Enrico Granatac2a28252011-08-16 16:49:25 +0000792 case eCharStrOrNone: // char* or NULL if py_return == Py_None
793 {
794 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000795 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000796 break;
797 }
Chris Lattner24943d22010-06-08 16:52:24 +0000798 case eBool:
799 {
800 const char format[2] = "b";
801 success = PyArg_Parse (py_return, format, (bool *) ret_value);
802 break;
803 }
804 case eShortInt:
805 {
806 const char format[2] = "h";
807 success = PyArg_Parse (py_return, format, (short *) ret_value);
808 break;
809 }
810 case eShortIntUnsigned:
811 {
812 const char format[2] = "H";
813 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
814 break;
815 }
816 case eInt:
817 {
818 const char format[2] = "i";
819 success = PyArg_Parse (py_return, format, (int *) ret_value);
820 break;
821 }
822 case eIntUnsigned:
823 {
824 const char format[2] = "I";
825 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
826 break;
827 }
828 case eLongInt:
829 {
830 const char format[2] = "l";
831 success = PyArg_Parse (py_return, format, (long *) ret_value);
832 break;
833 }
834 case eLongIntUnsigned:
835 {
836 const char format[2] = "k";
837 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
838 break;
839 }
840 case eLongLong:
841 {
842 const char format[2] = "L";
843 success = PyArg_Parse (py_return, format, (long long *) ret_value);
844 break;
845 }
846 case eLongLongUnsigned:
847 {
848 const char format[2] = "K";
849 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
850 break;
851 }
852 case eFloat:
853 {
854 const char format[2] = "f";
855 success = PyArg_Parse (py_return, format, (float *) ret_value);
856 break;
857 }
858 case eDouble:
859 {
860 const char format[2] = "d";
861 success = PyArg_Parse (py_return, format, (double *) ret_value);
862 break;
863 }
864 case eChar:
865 {
866 const char format[2] = "c";
867 success = PyArg_Parse (py_return, format, (char *) ret_value);
868 break;
869 }
870 default:
871 {}
872 }
873 Py_DECREF (py_return);
874 if (success)
875 ret_success = true;
876 else
877 ret_success = false;
878 }
879 }
880
881 py_error = PyErr_Occurred();
882 if (py_error != NULL)
883 {
884 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
885 PyErr_Print ();
886 PyErr_Clear();
887 ret_success = false;
888 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000889
890 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000891
Caroline Tice202f6b82011-01-17 21:55:19 +0000892 if (need_to_release_lock)
893 ReleasePythonLock();
894
Chris Lattner24943d22010-06-08 16:52:24 +0000895 return ret_success;
896}
897
898bool
899ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
900{
Caroline Tice202f6b82011-01-17 21:55:19 +0000901 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
902 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000903
Caroline Tice202f6b82011-01-17 21:55:19 +0000904 if (CurrentThreadHasPythonLock())
905 need_to_release_lock = false;
906 else
907 {
908 while (!GetPythonLock (1))
909 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
910 }
911
912 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000913
Chris Lattner24943d22010-06-08 16:52:24 +0000914 bool success = false;
915 PyObject *py_return = NULL;
916 PyObject *mainmod = PyImport_AddModule ("__main__");
917 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000918 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000919 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000920 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000921
Caroline Tice0aa2e552011-01-14 00:29:16 +0000922 if (PyDict_Check (globals))
923 {
924 PyObject *key, *value;
925 Py_ssize_t pos = 0;
926
927 while (PyDict_Next (globals, &pos, &key, &value))
928 {
929 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
930 // so that Python's garbage collector doesn't collect them out from under us.
931 Py_INCREF (key);
932 Py_INCREF (value);
933 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
934 locals = value;
935 }
936 }
937
938 if (locals == NULL)
939 {
940 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
941 should_decrement_locals = true;
942 }
943
944 if (locals == NULL)
945 {
946 locals = globals;
947 should_decrement_locals = false;
948 }
949
950 py_error = PyErr_Occurred();
951 if (py_error != NULL)
952 PyErr_Clear();
953
Chris Lattner24943d22010-06-08 16:52:24 +0000954 if (in_string != NULL)
955 {
956 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
957 if (compiled_node)
958 {
959 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
960 if (compiled_code)
961 {
962 py_return = PyEval_EvalCode (compiled_code, globals, locals);
963 if (py_return != NULL)
964 {
965 success = true;
966 Py_DECREF (py_return);
967 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000968 if (locals && should_decrement_locals)
969 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000970 }
971 }
972 }
973
974 py_error = PyErr_Occurred ();
975 if (py_error != NULL)
976 {
977 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
978 PyErr_Print ();
979 PyErr_Clear();
980 success = false;
981 }
982
Caroline Tice0aa2e552011-01-14 00:29:16 +0000983 LeaveSession ();
984
Caroline Tice202f6b82011-01-17 21:55:19 +0000985 if (need_to_release_lock)
986 ReleasePythonLock();
987
Chris Lattner24943d22010-06-08 16:52:24 +0000988 return success;
989}
990
991static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
992
993size_t
994ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
995(
996 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000997 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000998 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000999 const char *bytes,
1000 size_t bytes_len
1001)
1002{
Caroline Tice892fadd2011-06-16 16:27:19 +00001003 static StringList commands_in_progress;
1004
1005 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1006 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1007
Chris Lattner24943d22010-06-08 16:52:24 +00001008 switch (notification)
1009 {
1010 case eInputReaderActivate:
1011 {
1012 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +00001013 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +00001014 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001015 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001016 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +00001017 out_stream->Printf ("%s", reader.GetPrompt());
1018 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001019 }
1020 }
1021 break;
1022
1023 case eInputReaderDeactivate:
1024 break;
1025
1026 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001027 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001028 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001029 out_stream->Printf ("%s", reader.GetPrompt());
1030 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001031 }
Chris Lattner24943d22010-06-08 16:52:24 +00001032 break;
1033
Caroline Tice4a348082011-05-02 20:41:46 +00001034 case eInputReaderAsynchronousOutputWritten:
1035 break;
1036
Chris Lattner24943d22010-06-08 16:52:24 +00001037 case eInputReaderGotToken:
1038 {
1039 std::string temp_string (bytes, bytes_len);
1040 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001041 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001042 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001043 out_stream->Printf ("%s", reader.GetPrompt());
1044 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001045 }
Chris Lattner24943d22010-06-08 16:52:24 +00001046 }
1047 break;
1048
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001049 case eInputReaderEndOfFile:
1050 case eInputReaderInterrupt:
1051 // Control-c (SIGINT) & control-d both mean finish & exit.
1052 reader.SetIsDone(true);
1053
1054 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1055 if (notification == eInputReaderInterrupt)
1056 commands_in_progress.Clear();
1057
1058 // Fall through here...
1059
Chris Lattner24943d22010-06-08 16:52:24 +00001060 case eInputReaderDone:
1061 {
1062 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1063 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1064 data_ap->user_source.AppendList (commands_in_progress);
1065 if (data_ap.get())
1066 {
Greg Clayton63094e02010-06-23 01:19:29 +00001067 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001068 if (interpreter)
1069 {
1070 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1071 data_ap->script_source))
1072 {
1073 if (data_ap->script_source.GetSize() == 1)
1074 {
1075 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1076 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1077 }
1078 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001079 else if (!batch_mode)
1080 {
1081 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1082 out_stream->Flush();
1083 }
Chris Lattner24943d22010-06-08 16:52:24 +00001084 }
1085 else
1086 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001087 if (!batch_mode)
1088 {
1089 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1090 out_stream->Flush();
1091 }
Chris Lattner24943d22010-06-08 16:52:24 +00001092 }
1093 }
1094 }
1095 break;
1096
1097 }
1098
1099 return bytes_len;
1100}
1101
1102void
Greg Clayton238c0a12010-09-18 01:14:36 +00001103ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001104 CommandReturnObject &result)
1105{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001106 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1107
Greg Clayton63094e02010-06-23 01:19:29 +00001108 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001109
1110 if (reader_sp)
1111 {
1112 Error err = reader_sp->Initialize (
1113 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1114 bp_options, // baton
1115 eInputReaderGranularityLine, // token size, for feeding data to callback function
1116 "DONE", // end token
1117 "> ", // prompt
1118 true); // echo input
1119
1120 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001121 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001122 else
1123 {
1124 result.AppendError (err.AsCString());
1125 result.SetStatus (eReturnStatusFailed);
1126 }
1127 }
1128 else
1129 {
1130 result.AppendError("out of memory");
1131 result.SetStatus (eReturnStatusFailed);
1132 }
1133}
1134
Johnny Chen3e0571b2010-09-11 00:23:59 +00001135// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001136void
Greg Clayton238c0a12010-09-18 01:14:36 +00001137ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001138 const char *oneliner)
1139{
1140 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1141
1142 // It's necessary to set both user_source and script_source to the oneliner.
1143 // The former is used to generate callback description (as in breakpoint command list)
1144 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001145
Johnny Chend1c2dca2010-09-10 18:21:10 +00001146 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001147
Caroline Tice5136f942010-09-27 21:35:15 +00001148 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1149 {
1150 if (data_ap->script_source.GetSize() == 1)
1151 {
1152 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1153 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1154 }
1155 }
1156
Johnny Chend1c2dca2010-09-10 18:21:10 +00001157 return;
1158}
1159
Chris Lattner24943d22010-06-08 16:52:24 +00001160bool
1161ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1162{
1163 // Convert StringList to one long, newline delimited, const char *.
1164 std::string function_def_string;
1165
1166 int num_lines = function_def.GetSize();
1167
1168 for (int i = 0; i < num_lines; ++i)
1169 {
1170 function_def_string.append (function_def.GetStringAtIndex(i));
1171 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1172 function_def_string.append ("\n");
1173
1174 }
1175
1176 return ExecuteMultipleLines (function_def_string.c_str());
1177}
1178
Enrico Granataf7a9b142011-07-15 02:26:42 +00001179// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1180// use this code to generate their functions
1181bool
1182ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1183{
1184 int num_lines = input.GetSize ();
1185 if (num_lines == 0)
1186 return false;
1187 StreamString sstr;
1188 StringList auto_generated_function;
1189 auto_generated_function.AppendString (signature.c_str());
1190 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1191 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1192 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1193 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1194 // global dictionary.
1195
1196 // Wrap everything up inside the function, increasing the indentation.
1197
1198 for (int i = 0; i < num_lines; ++i)
1199 {
1200 sstr.Clear ();
1201 sstr.Printf (" %s", input.GetStringAtIndex (i));
1202 auto_generated_function.AppendString (sstr.GetData());
1203 }
1204 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1205 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1206 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1207 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1208
1209 // Verify that the results are valid Python.
1210
1211 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1212 return false;
1213
1214 return true;
1215
1216}
1217
1218// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1219// given to generated functions, of course)
1220bool
1221ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output)
1222{
1223 static int num_created_functions = 0;
1224 user_input.RemoveBlankLines ();
1225 int num_lines = user_input.GetSize ();
1226 StreamString sstr;
1227
1228 // Check to see if we have any data; if not, just return.
1229 if (user_input.GetSize() == 0)
1230 return false;
1231
1232 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1233 // ValueObject as parameter to the function.
1234
1235 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1236 ++num_created_functions;
1237 std::string auto_generated_function_name = sstr.GetData();
1238
1239 sstr.Clear();
1240 StringList auto_generated_function;
1241
1242 // Create the function name & definition string.
1243
1244 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1245 auto_generated_function.AppendString (sstr.GetData());
1246
1247 // Pre-pend code for setting up the session dictionary.
1248
1249 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1250 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1251 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1252 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1253 // global dictionary.
1254
1255 // Wrap everything up inside the function, increasing the indentation.
1256
1257 for (int i = 0; i < num_lines; ++i)
1258 {
1259 sstr.Clear ();
1260 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1261 auto_generated_function.AppendString (sstr.GetData());
1262 }
1263
1264 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1265 // got written to the values in the global dictionary, not the session dictionary).
1266
1267 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1268 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1269 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1270 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1271
1272 // Verify that the results are valid Python.
1273
1274 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1275 return false;
1276
1277 // Store the name of the auto-generated function to be called.
1278
1279 output.AppendString (auto_generated_function_name.c_str());
1280 return true;
1281}
1282
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001283bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001284ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, StringList &output)
1285{
1286 static int num_created_functions = 0;
1287 user_input.RemoveBlankLines ();
1288 int num_lines = user_input.GetSize ();
1289 StreamString sstr;
1290
1291 // Check to see if we have any data; if not, just return.
1292 if (user_input.GetSize() == 0)
1293 return false;
1294
1295 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1296 // ValueObject as parameter to the function.
1297
1298 sstr.Printf ("lldb_autogen_python_cmd_alias_func_%d", num_created_functions);
1299 ++num_created_functions;
1300 std::string auto_generated_function_name = sstr.GetData();
1301
1302 sstr.Clear();
1303 StringList auto_generated_function;
1304
1305 // Create the function name & definition string.
1306
1307 sstr.Printf ("def %s (debugger, args, dict):", auto_generated_function_name.c_str());
1308 auto_generated_function.AppendString (sstr.GetData());
1309
1310 // Pre-pend code for setting up the session dictionary.
1311
1312 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1313 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1314 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1315 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1316 // global dictionary.
1317
1318 // Wrap everything up inside the function, increasing the indentation.
1319
1320 for (int i = 0; i < num_lines; ++i)
1321 {
1322 sstr.Clear ();
1323 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1324 auto_generated_function.AppendString (sstr.GetData());
1325 }
1326
1327 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1328 // got written to the values in the global dictionary, not the session dictionary).
1329
1330 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1331 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1332 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1333 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1334
1335 // Verify that the results are valid Python.
1336
1337 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1338 return false;
1339
1340 // Store the name of the auto-generated function to be called.
1341
1342 output.AppendString (auto_generated_function_name.c_str());
1343 return true;
1344}
1345
1346
1347bool
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001348ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output)
1349{
1350 static int num_created_classes = 0;
1351 user_input.RemoveBlankLines ();
1352 int num_lines = user_input.GetSize ();
1353 StreamString sstr;
1354
1355 // Check to see if we have any data; if not, just return.
1356 if (user_input.GetSize() == 0)
1357 return false;
1358
1359 // Wrap all user input into a Python class
1360
1361 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1362 ++num_created_classes;
1363 std::string auto_generated_class_name = sstr.GetData();
1364
1365 sstr.Clear();
1366 StringList auto_generated_class;
1367
1368 // Create the function name & definition string.
1369
1370 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1371 auto_generated_class.AppendString (sstr.GetData());
1372
1373 // Wrap everything up inside the class, increasing the indentation.
1374
1375 for (int i = 0; i < num_lines; ++i)
1376 {
1377 sstr.Clear ();
1378 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1379 auto_generated_class.AppendString (sstr.GetData());
1380 }
1381
1382
1383 // Verify that the results are valid Python.
1384 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1385 // (TODO: rename that method to ExportDefinitionToInterpreter)
1386 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1387 return false;
1388
1389 // Store the name of the auto-generated class
1390
1391 output.AppendString (auto_generated_class_name.c_str());
1392 return true;
1393}
1394
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001395void*
1396ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1397 lldb::ValueObjectSP valobj)
1398{
1399 if (class_name.empty())
1400 return NULL;
1401
1402 if (!valobj.get())
1403 return NULL;
1404
Enrico Granata979e20d2011-07-29 19:53:35 +00001405 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001406
1407 if (!target)
1408 return NULL;
1409
1410 Debugger &debugger = target->GetDebugger();
1411 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1412 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1413
1414 if (!script_interpreter)
1415 return NULL;
1416
1417 void* ret_val;
1418
1419 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001420
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001421 {
Enrico Granata91544802011-09-06 19:20:51 +00001422 Locker py_lock(this, tmp_fh);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001423 ret_val = g_swig_synthetic_script (class_name,
1424 python_interpreter->m_dictionary_name.c_str(),
1425 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001426 }
1427
1428 return ret_val;
1429}
1430
Enrico Granataf7a9b142011-07-15 02:26:42 +00001431bool
1432ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output)
1433{
1434 StringList input(oneliner);
1435 return GenerateTypeScriptFunction(input, output);
1436}
1437
Chris Lattner24943d22010-06-08 16:52:24 +00001438bool
1439ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1440{
1441 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001442 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001443 int num_lines = user_input.GetSize ();
1444 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001445
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001446 // Check to see if we have any data; if not, just return.
1447 if (user_input.GetSize() == 0)
1448 return false;
1449
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001450 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1451 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001452
Caroline Ticeb447e842010-09-21 19:25:28 +00001453
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001454 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1455 ++num_created_functions;
1456 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001457
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001458 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001459 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001460
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001461 // Create the function name & definition string.
1462
Caroline Tice0aa2e552011-01-14 00:29:16 +00001463 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001464 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001465
1466 // Pre-pend code for setting up the session dictionary.
1467
1468 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1469 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1470 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1471 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1472 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001473
1474 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001475
1476 for (int i = 0; i < num_lines; ++i)
1477 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001478 sstr.Clear ();
1479 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1480 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001481 }
Chris Lattner24943d22010-06-08 16:52:24 +00001482
Caroline Tice0aa2e552011-01-14 00:29:16 +00001483 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1484 // got written to the values in the global dictionary, not the session dictionary).
1485
1486 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1487 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1488 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1489 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1490
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001491 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001492
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001493 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001494 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001495 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001496 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001497
1498 // Store the name of the auto-generated function to be called.
1499
1500 callback_data.AppendString (auto_generated_function_name.c_str());
1501 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001502}
1503
Enrico Granataf7a9b142011-07-15 02:26:42 +00001504std::string
1505ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1506 lldb::ValueObjectSP valobj)
1507{
1508
1509 if (!python_function_name || !(*python_function_name))
1510 return "<no function>";
1511
1512 if (!valobj.get())
1513 return "<no object>";
1514
Enrico Granata979e20d2011-07-29 19:53:35 +00001515 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001516
1517 if (!target)
1518 return "<no target>";
1519
1520 Debugger &debugger = target->GetDebugger();
1521 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1522 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1523
1524 if (!script_interpreter)
1525 return "<no python>";
1526
1527 std::string ret_val;
1528
1529 if (python_function_name
1530 && *python_function_name)
1531 {
1532 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001533
Enrico Granataf7a9b142011-07-15 02:26:42 +00001534 {
Enrico Granata91544802011-09-06 19:20:51 +00001535 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001536 ret_val = g_swig_typescript_callback (python_function_name,
1537 python_interpreter->m_dictionary_name.c_str(),
1538 valobj);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001539 }
1540 }
1541 else
1542 return "<no function name>";
1543
1544 return ret_val;
1545
1546}
1547
Greg Clayton5144f382010-10-07 17:14:24 +00001548bool
1549ScriptInterpreterPython::BreakpointCallbackFunction
1550(
1551 void *baton,
1552 StoppointCallbackContext *context,
1553 user_id_t break_id,
1554 user_id_t break_loc_id
1555)
1556{
1557 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1558 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001559
1560 if (!context)
1561 return true;
1562
1563 Target *target = context->exe_ctx.target;
1564
1565 if (!target)
1566 return true;
1567
1568 Debugger &debugger = target->GetDebugger();
1569 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1570 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1571
1572 if (!script_interpreter)
1573 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001574
1575 if (python_function_name != NULL
1576 && python_function_name[0] != '\0')
1577 {
1578 Thread *thread = context->exe_ctx.thread;
Greg Claytone86cbb92011-03-22 01:14:58 +00001579 const StackFrameSP stop_frame_sp (thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame));
Greg Clayton5144f382010-10-07 17:14:24 +00001580 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001581 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001582 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001583 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1584
1585 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001586 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001587 bool ret_val = true;
1588 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001589
Greg Claytone86cbb92011-03-22 01:14:58 +00001590 {
Enrico Granata91544802011-09-06 19:20:51 +00001591 Locker py_lock(python_interpreter, tmp_fh);
Greg Claytone86cbb92011-03-22 01:14:58 +00001592 ret_val = g_swig_breakpoint_callback (python_function_name,
1593 python_interpreter->m_dictionary_name.c_str(),
1594 stop_frame_sp,
1595 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001596 }
1597 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001598 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001599 }
Greg Clayton5144f382010-10-07 17:14:24 +00001600 }
1601 // We currently always true so we stop in case anything goes wrong when
1602 // trying to call the script function
1603 return true;
1604}
Caroline Tice2ade6112010-11-10 19:18:14 +00001605
1606lldb::thread_result_t
1607ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1608{
1609 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1610
1611 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1612
1613 if (log)
1614 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1615
1616 char error_str[1024];
1617 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001618 bool need_to_release_lock = true;
1619 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001620
Caroline Tice202f6b82011-01-17 21:55:19 +00001621 if (CurrentThreadHasPythonLock())
1622 {
1623 safe_to_run = true;
1624 need_to_release_lock = false;
1625 }
1626 else
1627 {
1628 int interval = 1;
1629 safe_to_run = GetPythonLock (interval);
1630 while (!safe_to_run)
1631 {
1632 interval = interval * 2;
1633 safe_to_run = GetPythonLock (interval);
1634 }
1635 }
1636
1637 if (pty_slave_name != NULL && safe_to_run)
1638 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001639 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001640
Caroline Tice202f6b82011-01-17 21:55:19 +00001641 script_interpreter->EnterSession ();
1642
Caroline Tice0aa2e552011-01-14 00:29:16 +00001643 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1644 PyRun_SimpleString (run_string.GetData());
1645 run_string.Clear ();
1646
1647 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1648 PyRun_SimpleString (run_string.GetData());
1649 run_string.Clear ();
1650
1651 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1652 PyRun_SimpleString (run_string.GetData());
1653 run_string.Clear ();
1654
1655 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1656 pty_slave_name);
1657 PyRun_SimpleString (run_string.GetData());
1658 run_string.Clear ();
1659
Johnny Chen8054ba32011-03-11 00:28:50 +00001660 // The following call drops into the embedded interpreter loop and stays there until the
1661 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001662
Caroline Ticece207c12011-03-11 00:21:55 +00001663 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001664 // the ability to run multi-threaded stuff, so we need to surround the call to the embedded interpreter with
Caroline Ticece207c12011-03-11 00:21:55 +00001665 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1666
1667 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1668 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1669 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1670 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1671 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1672 // hang (it's happened before).
1673
Caroline Tice9d352ce2011-03-07 23:24:28 +00001674 Py_BEGIN_ALLOW_THREADS
1675 PyGILState_STATE gstate = PyGILState_Ensure();
1676
Caroline Tice0aa2e552011-01-14 00:29:16 +00001677 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1678 PyRun_SimpleString (run_string.GetData());
1679 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001680
Caroline Tice9d352ce2011-03-07 23:24:28 +00001681 PyGILState_Release (gstate);
1682 Py_END_ALLOW_THREADS
1683
Caroline Tice0aa2e552011-01-14 00:29:16 +00001684 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1685 PyRun_SimpleString (run_string.GetData());
1686 run_string.Clear();
1687
1688 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1689 PyRun_SimpleString (run_string.GetData());
1690 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001691
1692 script_interpreter->LeaveSession ();
1693
Caroline Tice2ade6112010-11-10 19:18:14 +00001694 }
1695
Caroline Tice202f6b82011-01-17 21:55:19 +00001696 if (!safe_to_run)
1697 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1698 "Python interpreter locked on another thread; unable to acquire lock.\n");
1699
1700 if (need_to_release_lock)
1701 ReleasePythonLock ();
1702
Caroline Tice2ade6112010-11-10 19:18:14 +00001703 if (script_interpreter->m_embedded_thread_input_reader_sp)
1704 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1705
1706 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001707
1708 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001709
1710 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1711 if (log)
1712 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1713
1714
Johnny Chen8054ba32011-03-11 00:28:50 +00001715 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001716 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001717 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1718 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1719 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001720
Caroline Tice2ade6112010-11-10 19:18:14 +00001721 return NULL;
1722}
1723
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001724uint32_t
1725ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1726{
1727 if (!implementor)
1728 return 0;
1729
1730 if (!g_swig_calc_children)
1731 return 0;
1732
1733 ScriptInterpreterPython *python_interpreter = this;
1734
1735 uint32_t ret_val = 0;
1736
1737 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001738
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001739 {
Enrico Granata91544802011-09-06 19:20:51 +00001740 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001741 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001742 }
1743
1744 return ret_val;
1745}
1746
Enrico Granata91544802011-09-06 19:20:51 +00001747lldb::ValueObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001748ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1749{
1750 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001751 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001752
Enrico Granata91544802011-09-06 19:20:51 +00001753 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1754 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001755
1756 ScriptInterpreterPython *python_interpreter = this;
1757
Enrico Granata91544802011-09-06 19:20:51 +00001758 void* child_ptr = NULL;
1759 lldb::SBValue* value_sb = NULL;
1760 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001761
1762 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001763
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001764 {
Enrico Granata91544802011-09-06 19:20:51 +00001765 Locker py_lock(python_interpreter, tmp_fh);
1766 child_ptr = g_swig_get_child_index (implementor,idx);
1767 if (child_ptr != NULL && child_ptr != Py_None)
1768 {
1769 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1770 if (value_sb == NULL)
1771 Py_XDECREF(child_ptr);
1772 else
1773 ret_val = value_sb->get_sp();
1774 }
1775 else
1776 {
1777 Py_XDECREF(child_ptr);
1778 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001779 }
1780
1781 return ret_val;
1782}
1783
1784int
1785ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1786{
1787 if (!implementor)
1788 return UINT32_MAX;
1789
1790 if (!g_swig_get_index_child)
1791 return UINT32_MAX;
1792
1793 ScriptInterpreterPython *python_interpreter = this;
1794
1795 int ret_val = UINT32_MAX;
1796
1797 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001798
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001799 {
Enrico Granata91544802011-09-06 19:20:51 +00001800 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001801 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001802 }
1803
1804 return ret_val;
1805}
1806
Enrico Granata979e20d2011-07-29 19:53:35 +00001807void
1808ScriptInterpreterPython::UpdateSynthProviderInstance (void* implementor)
1809{
1810 if (!implementor)
1811 return;
1812
1813 if (!g_swig_update_provider)
1814 return;
1815
1816 ScriptInterpreterPython *python_interpreter = this;
1817
1818 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001819
Enrico Granata979e20d2011-07-29 19:53:35 +00001820 {
Enrico Granata91544802011-09-06 19:20:51 +00001821 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granata979e20d2011-07-29 19:53:35 +00001822 g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001823 }
1824
1825 return;
1826}
1827
Enrico Granatac2a28252011-08-16 16:49:25 +00001828bool
1829ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1830 const char* args,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001831 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001832 Error& error)
1833{
1834 if (!impl_function)
1835 {
1836 error.SetErrorString("no function to execute");
1837 return false;
1838 }
1839
1840 if (!g_swig_call_command)
1841 {
1842 error.SetErrorString("no helper function to run scripted commands");
1843 return false;
1844 }
1845
1846 ScriptInterpreterPython *python_interpreter = this;
Enrico Granata3370f0c2011-08-19 23:56:34 +00001847
Enrico Granatac2a28252011-08-16 16:49:25 +00001848 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
1849
1850 bool ret_val;
1851
1852 std::string err_msg;
1853
1854 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001855
Enrico Granatac2a28252011-08-16 16:49:25 +00001856 {
Enrico Granata91544802011-09-06 19:20:51 +00001857 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granatac2a28252011-08-16 16:49:25 +00001858 ret_val = g_swig_call_command (impl_function,
1859 python_interpreter->m_dictionary_name.c_str(),
1860 debugger_sp,
1861 args,
1862 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001863 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001864 }
1865
1866 if (!ret_val)
1867 error.SetErrorString(err_msg.c_str());
1868 else
1869 error.Clear();
Enrico Granata3370f0c2011-08-19 23:56:34 +00001870
Enrico Granatac2a28252011-08-16 16:49:25 +00001871 return ret_val;
1872
1873
1874 return true;
1875
1876}
1877
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001878// in Python, a special attribute __doc__ contains the docstring
1879// for an object (function, method, class, ...) if any is defined
1880// Otherwise, the attribute's value is None
1881std::string
1882ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1883{
1884 std::string command(item);
1885 command += ".__doc__";
1886
1887 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1888
1889 if (ExecuteOneLineWithReturn (command.c_str(),
1890 ScriptInterpreter::eCharStrOrNone,
1891 &result_ptr) && result_ptr)
1892 {
1893 return std::string(result_ptr);
1894 }
1895 else
1896 return std::string("");
1897}
Caroline Tice2ade6112010-11-10 19:18:14 +00001898
Caroline Tice0aa2e552011-01-14 00:29:16 +00001899void
Greg Claytone86cbb92011-03-22 01:14:58 +00001900ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00001901 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001902 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
1903 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
1904 SWIGPythonCalculateNumChildren python_swig_calc_children,
1905 SWIGPythonGetChildAtIndex python_swig_get_child_index,
1906 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
Enrico Granata979e20d2011-07-29 19:53:35 +00001907 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue,
Enrico Granatac2a28252011-08-16 16:49:25 +00001908 SWIGPythonUpdateSynthProviderInstance python_swig_update_provider,
1909 SWIGPythonCallCommand python_swig_call_command)
Greg Claytone86cbb92011-03-22 01:14:58 +00001910{
1911 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001912 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1913 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001914 g_swig_synthetic_script = python_swig_synthetic_script;
1915 g_swig_calc_children = python_swig_calc_children;
1916 g_swig_get_child_index = python_swig_get_child_index;
1917 g_swig_get_index_child = python_swig_get_index_child;
1918 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Enrico Granata979e20d2011-07-29 19:53:35 +00001919 g_swig_update_provider = python_swig_update_provider;
Enrico Granatac2a28252011-08-16 16:49:25 +00001920 g_swig_call_command = python_swig_call_command;
Greg Claytone86cbb92011-03-22 01:14:58 +00001921}
1922
1923void
1924ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001925{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001926 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1927
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001928 // Python will muck with STDIN terminal state, so save off any current TTY
1929 // settings so we can restore them.
1930 TerminalState stdin_tty_state;
1931 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001932
Caroline Tice9d352ce2011-03-07 23:24:28 +00001933 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001934 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001935
Greg Claytone86cbb92011-03-22 01:14:58 +00001936 // Initialize SWIG after setting up python
1937 assert (g_swig_init_callback != NULL);
1938 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001939
1940 // Update the path python uses to search for modules to include the current directory.
1941
Caroline Ticed4d92832011-06-13 21:33:00 +00001942 PyRun_SimpleString ("import sys");
1943 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001944
1945 // Find the module that owns this code and use that path we get to
1946 // set the sys.path appropriately.
1947
1948 FileSpec file_spec;
1949 char python_dir_path[PATH_MAX];
1950 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1951 {
1952 std::string python_path("sys.path.insert(0,\"");
1953 size_t orig_len = python_path.length();
1954 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1955 {
1956 python_path.append (python_dir_path);
1957 python_path.append ("\")");
1958 PyRun_SimpleString (python_path.c_str());
1959 python_path.resize (orig_len);
1960 }
1961
1962 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1963 {
1964 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1965 {
1966 python_path.append (python_dir_path);
1967 python_path.append ("\")");
1968 PyRun_SimpleString (python_path.c_str());
1969 python_path.resize (orig_len);
1970 }
1971 }
1972 }
1973
Jim Ingham4dfa5112011-08-22 19:10:09 +00001974 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001975
Caroline Ticed4d92832011-06-13 21:33:00 +00001976 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001977
Caroline Ticed4d92832011-06-13 21:33:00 +00001978 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1979 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00001980 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001981
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001982 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001983}
1984
Greg Claytone86cbb92011-03-22 01:14:58 +00001985//void
1986//ScriptInterpreterPython::Terminate ()
1987//{
1988// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1989// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1990// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1991// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1992// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1993// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1994// // within Py_Finalize, which results in a seg fault.
1995// //
1996// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1997// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1998// // process exits).
1999// //
2000//// Py_Finalize ();
2001//}