blob: 588e2c15651360818886482fcf9fd280f022f403 [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
Greg Clayton5144f382010-10-07 17:14:24 +000021#include "lldb/API/SBFrame.h"
22#include "lldb/API/SBBreakpointLocation.h"
Enrico Granata3370f0c2011-08-19 23:56:34 +000023#include "lldb/API/SBCommandReturnObject.h"
Greg Clayton63094e02010-06-23 01:19:29 +000024#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner24943d22010-06-08 16:52:24 +000025#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000026#include "lldb/Core/Timer.h"
27#include "lldb/Host/Host.h"
28#include "lldb/Interpreter/CommandInterpreter.h"
29#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton5144f382010-10-07 17:14:24 +000030#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000031
Chris Lattner24943d22010-06-08 16:52:24 +000032using namespace lldb;
33using namespace lldb_private;
34
Greg Claytone86cbb92011-03-22 01:14:58 +000035
36static ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL;
37static ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL;
Enrico Granataf7a9b142011-07-15 02:26:42 +000038static ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL;
Enrico Granata9ae7cef2011-07-24 00:14:56 +000039static ScriptInterpreter::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = NULL;
40static ScriptInterpreter::SWIGPythonCalculateNumChildren g_swig_calc_children = NULL;
41static ScriptInterpreter::SWIGPythonGetChildAtIndex g_swig_get_child_index = NULL;
42static ScriptInterpreter::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = NULL;
43static ScriptInterpreter::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = NULL;
Enrico Granata979e20d2011-07-29 19:53:35 +000044static ScriptInterpreter::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = NULL;
Enrico Granatac2a28252011-08-16 16:49:25 +000045static ScriptInterpreter::SWIGPythonCallCommand g_swig_call_command = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +000046
47static int
48_check_and_flush (FILE *stream)
49{
50 int prev_fail = ferror (stream);
51 return fflush (stream) || prev_fail ? EOF : 0;
52}
53
Caroline Tice202f6b82011-01-17 21:55:19 +000054static Predicate<lldb::tid_t> &
55PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +000056{
Caroline Tice202f6b82011-01-17 21:55:19 +000057 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
58 return g_interpreter_is_running;
59}
60
61static bool
62CurrentThreadHasPythonLock ()
63{
64 TimeValue timeout;
65
66 timeout = TimeValue::Now(); // Don't wait any time.
67
68 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
69}
70
71static bool
72GetPythonLock (uint32_t seconds_to_wait)
73{
74
75 TimeValue timeout;
76
77 if (seconds_to_wait != UINT32_MAX)
78 {
79 timeout = TimeValue::Now();
80 timeout.OffsetWithSeconds (seconds_to_wait);
81 }
82
83 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
84 Host::GetCurrentThreadID(), &timeout, NULL);
85}
86
87static void
88ReleasePythonLock ()
89{
90 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +000091}
92
Greg Clayton63094e02010-06-23 01:19:29 +000093ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +000094 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +000095 m_embedded_python_pty (),
96 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +000097 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +000098 m_new_sysout (NULL),
99 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000100 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000101 m_session_is_active (false),
102 m_pty_slave_is_open (false),
103 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000104{
105
Greg Clayton7c330d62011-01-27 01:01:10 +0000106 static int g_initialized = false;
107
108 if (!g_initialized)
109 {
110 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000111 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000112 }
113
Caroline Tice202f6b82011-01-17 21:55:19 +0000114 bool safe_to_run = false;
115 bool need_to_release_lock = true;
116 int interval = 5; // Number of seconds to try getting the Python lock before timing out.
117
118 // We don't dare exit this function without finishing setting up the script interpreter, so we must wait until
119 // we can get the Python lock.
120
121 if (CurrentThreadHasPythonLock())
122 {
123 safe_to_run = true;
124 need_to_release_lock = false;
125 }
126
127 while (!safe_to_run)
128 {
129 safe_to_run = GetPythonLock (interval);
130 if (!safe_to_run)
131 {
132 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
133 fprintf (tmp_fh,
134 "Python interpreter is locked on another thread; "
135 "please release interpreter in order to continue.\n");
136 interval = interval * 2;
137 }
138 }
139
Caroline Tice0aa2e552011-01-14 00:29:16 +0000140 m_dictionary_name.append("_dict");
141 StreamString run_string;
142 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
143 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000144
Caroline Tice0aa2e552011-01-14 00:29:16 +0000145 run_string.Clear();
146 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
147 PyRun_SimpleString (run_string.GetData());
148
149 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
150 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
151 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
152 // call to Debugger::Terminate is made, the ref-count has the correct value.
153 //
154 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
155 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000156
Caroline Tice0aa2e552011-01-14 00:29:16 +0000157 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000158
Caroline Tice0aa2e552011-01-14 00:29:16 +0000159 run_string.Clear();
160 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
161 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000162
Caroline Tice0aa2e552011-01-14 00:29:16 +0000163 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000164
Caroline Tice0aa2e552011-01-14 00:29:16 +0000165 if (new_count > old_count)
166 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000167
Caroline Tice0aa2e552011-01-14 00:29:16 +0000168 run_string.Clear();
169 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
170 PyRun_SimpleString (run_string.GetData());
171
172 run_string.Clear();
173 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
174 interpreter.GetDebugger().GetID());
175 PyRun_SimpleString (run_string.GetData());
176
Enrico Granata074e3b62011-08-17 19:07:52 +0000177 run_string.Clear();
Enrico Granataf501c592011-08-17 22:13:59 +0000178 run_string.Printf ("run_one_line (%s, 'from gnu_libstdcpp import *')", m_dictionary_name.c_str(),
Enrico Granata074e3b62011-08-17 19:07:52 +0000179 interpreter.GetDebugger().GetID());
180 PyRun_SimpleString (run_string.GetData());
181
Caroline Tice0aa2e552011-01-14 00:29:16 +0000182 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000183 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000184 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000185 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000186
187 if (need_to_release_lock)
188 ReleasePythonLock();
Chris Lattner24943d22010-06-08 16:52:24 +0000189}
190
191ScriptInterpreterPython::~ScriptInterpreterPython ()
192{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000193 Debugger &debugger = GetCommandInterpreter().GetDebugger();
194
195 if (m_embedded_thread_input_reader_sp.get() != NULL)
196 {
197 m_embedded_thread_input_reader_sp->SetIsDone (true);
198 m_embedded_python_pty.CloseSlaveFileDescriptor();
199 m_pty_slave_is_open = false;
200 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
201 m_embedded_thread_input_reader_sp.reset();
202 debugger.PopInputReader (reader_sp);
203 }
204
205 if (m_new_sysout)
206 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000207 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
208 if (!CurrentThreadHasPythonLock ())
209 {
210 while (!GetPythonLock (1))
211 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
212 Py_DECREF (m_new_sysout);
213 ReleasePythonLock ();
214 }
215 else
216 Py_DECREF (m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000217 }
Chris Lattner24943d22010-06-08 16:52:24 +0000218}
219
Caroline Tice0aa2e552011-01-14 00:29:16 +0000220void
221ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
222{
223 if (fh == NULL)
224 return;
225
226 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000227
Caroline Tice202f6b82011-01-17 21:55:19 +0000228 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
229 if (!CurrentThreadHasPythonLock ())
230 {
231 while (!GetPythonLock (1))
232 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
233 EnterSession ();
234 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
235 LeaveSession ();
236 ReleasePythonLock ();
237 }
238 else
239 {
240 EnterSession ();
241 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
242 LeaveSession ();
243 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000244}
245
246void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000247ScriptInterpreterPython::SaveTerminalState (int fd)
248{
249 // Python mucks with the terminal state of STDIN. If we can possibly avoid
250 // this by setting the file handles up correctly prior to entering the
251 // interpreter we should. For now we save and restore the terminal state
252 // on the input file handle.
253 m_terminal_state.Save (fd, false);
254}
255
256void
257ScriptInterpreterPython::RestoreTerminalState ()
258{
259 // Python mucks with the terminal state of STDIN. If we can possibly avoid
260 // this by setting the file handles up correctly prior to entering the
261 // interpreter we should. For now we save and restore the terminal state
262 // on the input file handle.
263 m_terminal_state.Restore();
264}
265
266
267
268void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000269ScriptInterpreterPython::LeaveSession ()
270{
271 m_session_is_active = false;
272}
273
274void
275ScriptInterpreterPython::EnterSession ()
276{
277 // If we have already entered the session, without having officially 'left' it, then there is no need to
278 // 'enter' it again.
279
280 if (m_session_is_active)
281 return;
282
283 m_session_is_active = true;
284
Caroline Tice202f6b82011-01-17 21:55:19 +0000285 StreamString run_string;
286
287 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
288 GetCommandInterpreter().GetDebugger().GetID());
289 PyRun_SimpleString (run_string.GetData());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000290 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +0000291
Caroline Tice0aa2e552011-01-14 00:29:16 +0000292
Caroline Tice6af65cb2011-05-03 21:21:50 +0000293 run_string.Printf ("run_one_line (%s, 'lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%d)')",
294 m_dictionary_name.c_str(),
295 GetCommandInterpreter().GetDebugger().GetID());
296 PyRun_SimpleString (run_string.GetData());
297 run_string.Clear();
298
299
300 ExecutionContext exe_ctx = m_interpreter.GetDebugger().GetSelectedExecutionContext();
301
302 if (exe_ctx.target)
303 run_string.Printf ("run_one_line (%s, 'lldb.target = lldb.debugger.GetSelectedTarget()')",
304 m_dictionary_name.c_str());
305 else
306 run_string.Printf ("run_one_line (%s, 'lldb.target = None')", m_dictionary_name.c_str());
307 PyRun_SimpleString (run_string.GetData());
308 run_string.Clear();
309
310 if (exe_ctx.process)
311 run_string.Printf ("run_one_line (%s, 'lldb.process = lldb.target.GetProcess()')", m_dictionary_name.c_str());
312 else
313 run_string.Printf ("run_one_line (%s, 'lldb.process = None')", m_dictionary_name.c_str());
314 PyRun_SimpleString (run_string.GetData());
315 run_string.Clear();
316
317 if (exe_ctx.thread)
318 run_string.Printf ("run_one_line (%s, 'lldb.thread = lldb.process.GetSelectedThread ()')",
319 m_dictionary_name.c_str());
320 else
321 run_string.Printf ("run_one_line (%s, 'lldb.thread = None')", m_dictionary_name.c_str());
322 PyRun_SimpleString (run_string.GetData());
323 run_string.Clear();
324
325 if (exe_ctx.frame)
326 run_string.Printf ("run_one_line (%s, 'lldb.frame = lldb.thread.GetSelectedFrame ()')",
327 m_dictionary_name.c_str());
328 else
329 run_string.Printf ("run_one_line (%s, 'lldb.frame = None')", m_dictionary_name.c_str());
330 PyRun_SimpleString (run_string.GetData());
331 run_string.Clear();
332
Caroline Tice0aa2e552011-01-14 00:29:16 +0000333 PyObject *sysmod = PyImport_AddModule ("sys");
334 PyObject *sysdict = PyModule_GetDict (sysmod);
335
336 if ((m_new_sysout != NULL)
337 && (sysmod != NULL)
338 && (sysdict != NULL))
339 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
340
341 if (PyErr_Occurred())
342 PyErr_Clear ();
343
Caroline Tice0aa2e552011-01-14 00:29:16 +0000344 if (!m_pty_slave_is_open)
345 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000346 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000347 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
348 m_pty_slave_name.c_str());
349 PyRun_SimpleString (run_string.GetData());
350 m_pty_slave_is_open = true;
351
352 run_string.Clear();
353 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
354 PyRun_SimpleString (run_string.GetData());
355 }
356}
357
358
Johnny Chen60dde642010-07-30 22:33:14 +0000359bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000360ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000361{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000362 if (!m_valid_session)
363 return false;
364
Caroline Tice0aa2e552011-01-14 00:29:16 +0000365
Caroline Tice0aa2e552011-01-14 00:29:16 +0000366
Caroline Tice4a461da2011-01-14 21:09:29 +0000367 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
368 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
369 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
370 // method to pass the command string directly down to Python.
371
372
Caroline Tice202f6b82011-01-17 21:55:19 +0000373 bool need_to_release_lock = true;
374
375 if (CurrentThreadHasPythonLock())
376 need_to_release_lock = false;
377 else if (!GetPythonLock (1))
378 {
379 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
380 "Python interpreter is currently locked by another thread; unable to process command.\n");
381 return false;
382 }
383
384 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000385 bool success = false;
386
Greg Clayton63094e02010-06-23 01:19:29 +0000387 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000388 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000389 // Find the correct script interpreter dictionary in the main module.
390 PyObject *main_mod = PyImport_AddModule ("__main__");
391 PyObject *script_interpreter_dict = NULL;
392 if (main_mod != NULL)
393 {
394 PyObject *main_dict = PyModule_GetDict (main_mod);
395 if ((main_dict != NULL)
396 && PyDict_Check (main_dict))
397 {
398 // Go through the main dictionary looking for the correct python script interpreter dictionary
399 PyObject *key, *value;
400 Py_ssize_t pos = 0;
401
402 while (PyDict_Next (main_dict, &pos, &key, &value))
403 {
404 // We have stolen references to the key and value objects in the dictionary; we need to increment
405 // them now so that Python's garbage collector doesn't collect them out from under us.
406 Py_INCREF (key);
407 Py_INCREF (value);
408 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
409 {
410 script_interpreter_dict = value;
411 break;
412 }
413 }
414 }
415
416 if (script_interpreter_dict != NULL)
417 {
418 PyObject *pfunc = NULL;
419 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
420 if (pmod != NULL)
421 {
422 PyObject *pmod_dict = PyModule_GetDict (pmod);
423 if ((pmod_dict != NULL)
424 && PyDict_Check (pmod_dict))
425 {
426 PyObject *key, *value;
427 Py_ssize_t pos = 0;
428
429 while (PyDict_Next (pmod_dict, &pos, &key, &value))
430 {
431 Py_INCREF (key);
432 Py_INCREF (value);
433 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
434 {
435 pfunc = value;
436 break;
437 }
438 }
439
440 PyObject *string_arg = PyString_FromString (command);
441 if (pfunc && string_arg && PyCallable_Check (pfunc))
442 {
443 PyObject *pargs = PyTuple_New (2);
444 if (pargs != NULL)
445 {
446 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
447 PyTuple_SetItem (pargs, 1, string_arg);
448 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
449 Py_DECREF (pargs);
450 if (pvalue != NULL)
451 {
452 Py_DECREF (pvalue);
453 success = true;
454 }
455 else if (PyErr_Occurred ())
456 {
457 PyErr_Print();
458 PyErr_Clear();
459 }
460 }
461 }
462 }
463 }
464 Py_INCREF (script_interpreter_dict);
465 }
466 }
Greg Clayton63094e02010-06-23 01:19:29 +0000467
Caroline Tice0aa2e552011-01-14 00:29:16 +0000468 LeaveSession ();
469
Caroline Tice202f6b82011-01-17 21:55:19 +0000470 if (need_to_release_lock)
471 ReleasePythonLock();
472
Caroline Tice4a461da2011-01-14 21:09:29 +0000473 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000474 return true;
475
476 // The one-liner failed. Append the error message.
477 if (result)
478 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
479 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000480 }
Johnny Chen60dde642010-07-30 22:33:14 +0000481
Caroline Tice0aa2e552011-01-14 00:29:16 +0000482 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000483
484 if (need_to_release_lock)
485 ReleasePythonLock ();
486
Johnny Chen60dde642010-07-30 22:33:14 +0000487 if (result)
488 result->AppendError ("empty command passed to python\n");
489 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000490}
491
492
493
494size_t
495ScriptInterpreterPython::InputReaderCallback
496(
497 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000498 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000499 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000500 const char *bytes,
501 size_t bytes_len
502)
503{
Caroline Tice2ade6112010-11-10 19:18:14 +0000504 lldb::thread_t embedded_interpreter_thread;
505 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
506
Chris Lattner24943d22010-06-08 16:52:24 +0000507 if (baton == NULL)
508 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000509
510 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
511
512 if (script_interpreter->m_script_lang != eScriptLanguagePython)
513 return 0;
514
Caroline Tice892fadd2011-06-16 16:27:19 +0000515 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
516 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
517
Chris Lattner24943d22010-06-08 16:52:24 +0000518 switch (notification)
519 {
520 case eInputReaderActivate:
521 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000522 if (!batch_mode)
523 {
524 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
525 out_stream->Flush();
526 }
Greg Clayton58928562011-02-09 01:08:52 +0000527
Chris Lattner24943d22010-06-08 16:52:24 +0000528 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000529 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
530 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000531 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000532
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000533 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000534
Caroline Tice202f6b82011-01-17 21:55:19 +0000535 if (!CurrentThreadHasPythonLock())
536 {
537 while (!GetPythonLock(1))
538 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000539 out_stream->Printf ("Python interpreter locked on another thread; waiting to acquire lock...\n");
540 out_stream->Flush();
Caroline Tice202f6b82011-01-17 21:55:19 +0000541 }
542 script_interpreter->EnterSession ();
543 ReleasePythonLock();
544 }
545 else
546 script_interpreter->EnterSession ();
547
Caroline Tice2ade6112010-11-10 19:18:14 +0000548 char error_str[1024];
549 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
550 sizeof(error_str)))
551 {
552 if (log)
553 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
554 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
555 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
556 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
557 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000558 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000559 {
560 if (log)
561 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
562 Error detach_error;
563 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
564 }
565 else
566 {
567 if (log)
568 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
569 reader.SetIsDone (true);
570 }
571 }
572 else
573 {
574 if (log)
575 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
576 reader.SetIsDone (true);
577 }
Chris Lattner24943d22010-06-08 16:52:24 +0000578 }
579 break;
580
581 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000582 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000583 break;
584
585 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000586 if (!CurrentThreadHasPythonLock())
587 {
588 while (!GetPythonLock(1))
589 {
590 // Wait until lock is acquired.
591 }
592 script_interpreter->EnterSession ();
593 ReleasePythonLock();
594 }
595 else
596 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000597 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000598
Caroline Tice4a348082011-05-02 20:41:46 +0000599 case eInputReaderAsynchronousOutputWritten:
600 break;
601
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000602 case eInputReaderInterrupt:
603 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
604 break;
605
606 case eInputReaderEndOfFile:
607 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
608 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000609
610 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000611 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000612 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000613 if (log)
614 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
615 bytes_len);
616 if (bytes && bytes_len)
617 {
618 if ((int) bytes[0] == 4)
619 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
620 else
621 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
622 }
623 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000624 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000625 else
626 {
627 if (log)
628 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
629 bytes,
630 bytes_len);
631 reader.SetIsDone (true);
632 }
633
Chris Lattner24943d22010-06-08 16:52:24 +0000634 break;
635
636 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000637 script_interpreter->LeaveSession ();
638
Chris Lattner24943d22010-06-08 16:52:24 +0000639 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000640 if (log)
641 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000642
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000643 script_interpreter->RestoreTerminalState ();
644
Caroline Tice2ade6112010-11-10 19:18:14 +0000645 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000646 break;
647 }
648
649 return bytes_len;
650}
651
652
653void
Greg Clayton238c0a12010-09-18 01:14:36 +0000654ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000655{
656 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
657
Caroline Tice0aa2e552011-01-14 00:29:16 +0000658 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000659
660 // At the moment, the only time the debugger does not have an input file handle is when this is called
661 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
662 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
663 // do it.
664
Greg Clayton58928562011-02-09 01:08:52 +0000665 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000666 return;
667
Greg Clayton63094e02010-06-23 01:19:29 +0000668 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000669 if (reader_sp)
670 {
671 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
672 this, // baton
673 eInputReaderGranularityLine, // token size, to pass to callback function
674 NULL, // end token
675 NULL, // prompt
676 true)); // echo input
677
678 if (error.Success())
679 {
Greg Clayton63094e02010-06-23 01:19:29 +0000680 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000681 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000682 }
683 }
684}
685
686bool
687ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
688 ScriptInterpreter::ReturnType return_type,
689 void *ret_value)
690{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000691
Caroline Tice202f6b82011-01-17 21:55:19 +0000692 bool need_to_release_lock = true;
693
694 if (CurrentThreadHasPythonLock())
695 need_to_release_lock = false;
696 else if (!GetPythonLock (1))
697 {
698 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
699 "Python interpreter is currently locked by another thread; unable to process command.\n");
700 return false;
701 }
702
703 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000704
Chris Lattner24943d22010-06-08 16:52:24 +0000705 PyObject *py_return = NULL;
706 PyObject *mainmod = PyImport_AddModule ("__main__");
707 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000708 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000709 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000710 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000711 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000712 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000713
714 if (PyDict_Check (globals))
715 {
716 PyObject *key, *value;
717 Py_ssize_t pos = 0;
718
719 int i = 0;
720 while (PyDict_Next (globals, &pos, &key, &value))
721 {
722 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
723 // so that Python's garbage collector doesn't collect them out from under us.
724 Py_INCREF (key);
725 Py_INCREF (value);
726 char *c_str = PyString_AsString (key);
727 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
728 locals = value;
729 ++i;
730 }
731 }
Chris Lattner24943d22010-06-08 16:52:24 +0000732
Caroline Tice0aa2e552011-01-14 00:29:16 +0000733 if (locals == NULL)
734 {
735 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
736 should_decrement_locals = true;
737 }
738
739 if (locals == NULL)
740 {
741 locals = globals;
742 should_decrement_locals = false;
743 }
744
745 py_error = PyErr_Occurred();
746 if (py_error != NULL)
747 PyErr_Clear();
748
Chris Lattner24943d22010-06-08 16:52:24 +0000749 if (in_string != NULL)
750 {
751 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
752 if (py_return == NULL)
753 {
754 py_error = PyErr_Occurred ();
755 if (py_error != NULL)
756 PyErr_Clear ();
757
758 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
759 }
760
Caroline Tice0aa2e552011-01-14 00:29:16 +0000761 if (locals != NULL
762 && should_decrement_locals)
763 Py_DECREF (locals);
764
Chris Lattner24943d22010-06-08 16:52:24 +0000765 if (py_return != NULL)
766 {
767 switch (return_type)
768 {
769 case eCharPtr: // "char *"
770 {
771 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000772 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000773 break;
774 }
Enrico Granatac2a28252011-08-16 16:49:25 +0000775 case eCharStrOrNone: // char* or NULL if py_return == Py_None
776 {
777 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000778 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000779 break;
780 }
Chris Lattner24943d22010-06-08 16:52:24 +0000781 case eBool:
782 {
783 const char format[2] = "b";
784 success = PyArg_Parse (py_return, format, (bool *) ret_value);
785 break;
786 }
787 case eShortInt:
788 {
789 const char format[2] = "h";
790 success = PyArg_Parse (py_return, format, (short *) ret_value);
791 break;
792 }
793 case eShortIntUnsigned:
794 {
795 const char format[2] = "H";
796 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
797 break;
798 }
799 case eInt:
800 {
801 const char format[2] = "i";
802 success = PyArg_Parse (py_return, format, (int *) ret_value);
803 break;
804 }
805 case eIntUnsigned:
806 {
807 const char format[2] = "I";
808 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
809 break;
810 }
811 case eLongInt:
812 {
813 const char format[2] = "l";
814 success = PyArg_Parse (py_return, format, (long *) ret_value);
815 break;
816 }
817 case eLongIntUnsigned:
818 {
819 const char format[2] = "k";
820 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
821 break;
822 }
823 case eLongLong:
824 {
825 const char format[2] = "L";
826 success = PyArg_Parse (py_return, format, (long long *) ret_value);
827 break;
828 }
829 case eLongLongUnsigned:
830 {
831 const char format[2] = "K";
832 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
833 break;
834 }
835 case eFloat:
836 {
837 const char format[2] = "f";
838 success = PyArg_Parse (py_return, format, (float *) ret_value);
839 break;
840 }
841 case eDouble:
842 {
843 const char format[2] = "d";
844 success = PyArg_Parse (py_return, format, (double *) ret_value);
845 break;
846 }
847 case eChar:
848 {
849 const char format[2] = "c";
850 success = PyArg_Parse (py_return, format, (char *) ret_value);
851 break;
852 }
853 default:
854 {}
855 }
856 Py_DECREF (py_return);
857 if (success)
858 ret_success = true;
859 else
860 ret_success = false;
861 }
862 }
863
864 py_error = PyErr_Occurred();
865 if (py_error != NULL)
866 {
867 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
868 PyErr_Print ();
869 PyErr_Clear();
870 ret_success = false;
871 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000872
873 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000874
Caroline Tice202f6b82011-01-17 21:55:19 +0000875 if (need_to_release_lock)
876 ReleasePythonLock();
877
Chris Lattner24943d22010-06-08 16:52:24 +0000878 return ret_success;
879}
880
881bool
882ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
883{
Caroline Tice202f6b82011-01-17 21:55:19 +0000884 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
885 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000886
Caroline Tice202f6b82011-01-17 21:55:19 +0000887 if (CurrentThreadHasPythonLock())
888 need_to_release_lock = false;
889 else
890 {
891 while (!GetPythonLock (1))
892 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
893 }
894
895 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000896
Chris Lattner24943d22010-06-08 16:52:24 +0000897 bool success = false;
898 PyObject *py_return = NULL;
899 PyObject *mainmod = PyImport_AddModule ("__main__");
900 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000901 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000902 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000903 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000904
Caroline Tice0aa2e552011-01-14 00:29:16 +0000905 if (PyDict_Check (globals))
906 {
907 PyObject *key, *value;
908 Py_ssize_t pos = 0;
909
910 while (PyDict_Next (globals, &pos, &key, &value))
911 {
912 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
913 // so that Python's garbage collector doesn't collect them out from under us.
914 Py_INCREF (key);
915 Py_INCREF (value);
916 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
917 locals = value;
918 }
919 }
920
921 if (locals == NULL)
922 {
923 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
924 should_decrement_locals = true;
925 }
926
927 if (locals == NULL)
928 {
929 locals = globals;
930 should_decrement_locals = false;
931 }
932
933 py_error = PyErr_Occurred();
934 if (py_error != NULL)
935 PyErr_Clear();
936
Chris Lattner24943d22010-06-08 16:52:24 +0000937 if (in_string != NULL)
938 {
939 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
940 if (compiled_node)
941 {
942 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
943 if (compiled_code)
944 {
945 py_return = PyEval_EvalCode (compiled_code, globals, locals);
946 if (py_return != NULL)
947 {
948 success = true;
949 Py_DECREF (py_return);
950 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000951 if (locals && should_decrement_locals)
952 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000953 }
954 }
955 }
956
957 py_error = PyErr_Occurred ();
958 if (py_error != NULL)
959 {
960 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
961 PyErr_Print ();
962 PyErr_Clear();
963 success = false;
964 }
965
Caroline Tice0aa2e552011-01-14 00:29:16 +0000966 LeaveSession ();
967
Caroline Tice202f6b82011-01-17 21:55:19 +0000968 if (need_to_release_lock)
969 ReleasePythonLock();
970
Chris Lattner24943d22010-06-08 16:52:24 +0000971 return success;
972}
973
974static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
975
976size_t
977ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
978(
979 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000980 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000981 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000982 const char *bytes,
983 size_t bytes_len
984)
985{
Caroline Tice892fadd2011-06-16 16:27:19 +0000986 static StringList commands_in_progress;
987
988 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
989 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
990
Chris Lattner24943d22010-06-08 16:52:24 +0000991 switch (notification)
992 {
993 case eInputReaderActivate:
994 {
995 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +0000996 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +0000997 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000998 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000999 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +00001000 out_stream->Printf ("%s", reader.GetPrompt());
1001 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001002 }
1003 }
1004 break;
1005
1006 case eInputReaderDeactivate:
1007 break;
1008
1009 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001010 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001011 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001012 out_stream->Printf ("%s", reader.GetPrompt());
1013 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001014 }
Chris Lattner24943d22010-06-08 16:52:24 +00001015 break;
1016
Caroline Tice4a348082011-05-02 20:41:46 +00001017 case eInputReaderAsynchronousOutputWritten:
1018 break;
1019
Chris Lattner24943d22010-06-08 16:52:24 +00001020 case eInputReaderGotToken:
1021 {
1022 std::string temp_string (bytes, bytes_len);
1023 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001024 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001025 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001026 out_stream->Printf ("%s", reader.GetPrompt());
1027 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001028 }
Chris Lattner24943d22010-06-08 16:52:24 +00001029 }
1030 break;
1031
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001032 case eInputReaderEndOfFile:
1033 case eInputReaderInterrupt:
1034 // Control-c (SIGINT) & control-d both mean finish & exit.
1035 reader.SetIsDone(true);
1036
1037 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1038 if (notification == eInputReaderInterrupt)
1039 commands_in_progress.Clear();
1040
1041 // Fall through here...
1042
Chris Lattner24943d22010-06-08 16:52:24 +00001043 case eInputReaderDone:
1044 {
1045 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1046 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1047 data_ap->user_source.AppendList (commands_in_progress);
1048 if (data_ap.get())
1049 {
Greg Clayton63094e02010-06-23 01:19:29 +00001050 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001051 if (interpreter)
1052 {
1053 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1054 data_ap->script_source))
1055 {
1056 if (data_ap->script_source.GetSize() == 1)
1057 {
1058 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1059 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1060 }
1061 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001062 else if (!batch_mode)
1063 {
1064 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1065 out_stream->Flush();
1066 }
Chris Lattner24943d22010-06-08 16:52:24 +00001067 }
1068 else
1069 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001070 if (!batch_mode)
1071 {
1072 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1073 out_stream->Flush();
1074 }
Chris Lattner24943d22010-06-08 16:52:24 +00001075 }
1076 }
1077 }
1078 break;
1079
1080 }
1081
1082 return bytes_len;
1083}
1084
1085void
Greg Clayton238c0a12010-09-18 01:14:36 +00001086ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001087 CommandReturnObject &result)
1088{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001089 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1090
Greg Clayton63094e02010-06-23 01:19:29 +00001091 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001092
1093 if (reader_sp)
1094 {
1095 Error err = reader_sp->Initialize (
1096 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1097 bp_options, // baton
1098 eInputReaderGranularityLine, // token size, for feeding data to callback function
1099 "DONE", // end token
1100 "> ", // prompt
1101 true); // echo input
1102
1103 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001104 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001105 else
1106 {
1107 result.AppendError (err.AsCString());
1108 result.SetStatus (eReturnStatusFailed);
1109 }
1110 }
1111 else
1112 {
1113 result.AppendError("out of memory");
1114 result.SetStatus (eReturnStatusFailed);
1115 }
1116}
1117
Johnny Chen3e0571b2010-09-11 00:23:59 +00001118// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001119void
Greg Clayton238c0a12010-09-18 01:14:36 +00001120ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001121 const char *oneliner)
1122{
1123 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1124
1125 // It's necessary to set both user_source and script_source to the oneliner.
1126 // The former is used to generate callback description (as in breakpoint command list)
1127 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001128
Johnny Chend1c2dca2010-09-10 18:21:10 +00001129 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001130
Caroline Tice5136f942010-09-27 21:35:15 +00001131 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1132 {
1133 if (data_ap->script_source.GetSize() == 1)
1134 {
1135 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1136 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1137 }
1138 }
1139
Johnny Chend1c2dca2010-09-10 18:21:10 +00001140 return;
1141}
1142
Chris Lattner24943d22010-06-08 16:52:24 +00001143bool
1144ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1145{
1146 // Convert StringList to one long, newline delimited, const char *.
1147 std::string function_def_string;
1148
1149 int num_lines = function_def.GetSize();
1150
1151 for (int i = 0; i < num_lines; ++i)
1152 {
1153 function_def_string.append (function_def.GetStringAtIndex(i));
1154 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1155 function_def_string.append ("\n");
1156
1157 }
1158
1159 return ExecuteMultipleLines (function_def_string.c_str());
1160}
1161
Enrico Granataf7a9b142011-07-15 02:26:42 +00001162// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1163// use this code to generate their functions
1164bool
1165ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1166{
1167 int num_lines = input.GetSize ();
1168 if (num_lines == 0)
1169 return false;
1170 StreamString sstr;
1171 StringList auto_generated_function;
1172 auto_generated_function.AppendString (signature.c_str());
1173 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1174 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1175 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1176 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1177 // global dictionary.
1178
1179 // Wrap everything up inside the function, increasing the indentation.
1180
1181 for (int i = 0; i < num_lines; ++i)
1182 {
1183 sstr.Clear ();
1184 sstr.Printf (" %s", input.GetStringAtIndex (i));
1185 auto_generated_function.AppendString (sstr.GetData());
1186 }
1187 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1188 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1189 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1190 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1191
1192 // Verify that the results are valid Python.
1193
1194 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1195 return false;
1196
1197 return true;
1198
1199}
1200
1201// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1202// given to generated functions, of course)
1203bool
1204ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output)
1205{
1206 static int num_created_functions = 0;
1207 user_input.RemoveBlankLines ();
1208 int num_lines = user_input.GetSize ();
1209 StreamString sstr;
1210
1211 // Check to see if we have any data; if not, just return.
1212 if (user_input.GetSize() == 0)
1213 return false;
1214
1215 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1216 // ValueObject as parameter to the function.
1217
1218 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1219 ++num_created_functions;
1220 std::string auto_generated_function_name = sstr.GetData();
1221
1222 sstr.Clear();
1223 StringList auto_generated_function;
1224
1225 // Create the function name & definition string.
1226
1227 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1228 auto_generated_function.AppendString (sstr.GetData());
1229
1230 // Pre-pend code for setting up the session dictionary.
1231
1232 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1233 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1234 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1235 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1236 // global dictionary.
1237
1238 // Wrap everything up inside the function, increasing the indentation.
1239
1240 for (int i = 0; i < num_lines; ++i)
1241 {
1242 sstr.Clear ();
1243 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1244 auto_generated_function.AppendString (sstr.GetData());
1245 }
1246
1247 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1248 // got written to the values in the global dictionary, not the session dictionary).
1249
1250 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1251 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1252 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1253 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1254
1255 // Verify that the results are valid Python.
1256
1257 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1258 return false;
1259
1260 // Store the name of the auto-generated function to be called.
1261
1262 output.AppendString (auto_generated_function_name.c_str());
1263 return true;
1264}
1265
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001266bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001267ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, StringList &output)
1268{
1269 static int num_created_functions = 0;
1270 user_input.RemoveBlankLines ();
1271 int num_lines = user_input.GetSize ();
1272 StreamString sstr;
1273
1274 // Check to see if we have any data; if not, just return.
1275 if (user_input.GetSize() == 0)
1276 return false;
1277
1278 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1279 // ValueObject as parameter to the function.
1280
1281 sstr.Printf ("lldb_autogen_python_cmd_alias_func_%d", num_created_functions);
1282 ++num_created_functions;
1283 std::string auto_generated_function_name = sstr.GetData();
1284
1285 sstr.Clear();
1286 StringList auto_generated_function;
1287
1288 // Create the function name & definition string.
1289
1290 sstr.Printf ("def %s (debugger, args, dict):", auto_generated_function_name.c_str());
1291 auto_generated_function.AppendString (sstr.GetData());
1292
1293 // Pre-pend code for setting up the session dictionary.
1294
1295 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1296 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1297 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1298 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1299 // global dictionary.
1300
1301 // Wrap everything up inside the function, increasing the indentation.
1302
1303 for (int i = 0; i < num_lines; ++i)
1304 {
1305 sstr.Clear ();
1306 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1307 auto_generated_function.AppendString (sstr.GetData());
1308 }
1309
1310 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1311 // got written to the values in the global dictionary, not the session dictionary).
1312
1313 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1314 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1315 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1316 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1317
1318 // Verify that the results are valid Python.
1319
1320 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1321 return false;
1322
1323 // Store the name of the auto-generated function to be called.
1324
1325 output.AppendString (auto_generated_function_name.c_str());
1326 return true;
1327}
1328
1329
1330bool
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001331ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output)
1332{
1333 static int num_created_classes = 0;
1334 user_input.RemoveBlankLines ();
1335 int num_lines = user_input.GetSize ();
1336 StreamString sstr;
1337
1338 // Check to see if we have any data; if not, just return.
1339 if (user_input.GetSize() == 0)
1340 return false;
1341
1342 // Wrap all user input into a Python class
1343
1344 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1345 ++num_created_classes;
1346 std::string auto_generated_class_name = sstr.GetData();
1347
1348 sstr.Clear();
1349 StringList auto_generated_class;
1350
1351 // Create the function name & definition string.
1352
1353 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1354 auto_generated_class.AppendString (sstr.GetData());
1355
1356 // Wrap everything up inside the class, increasing the indentation.
1357
1358 for (int i = 0; i < num_lines; ++i)
1359 {
1360 sstr.Clear ();
1361 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1362 auto_generated_class.AppendString (sstr.GetData());
1363 }
1364
1365
1366 // Verify that the results are valid Python.
1367 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1368 // (TODO: rename that method to ExportDefinitionToInterpreter)
1369 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1370 return false;
1371
1372 // Store the name of the auto-generated class
1373
1374 output.AppendString (auto_generated_class_name.c_str());
1375 return true;
1376}
1377
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001378void*
1379ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1380 lldb::ValueObjectSP valobj)
1381{
1382 if (class_name.empty())
1383 return NULL;
1384
1385 if (!valobj.get())
1386 return NULL;
1387
Enrico Granata979e20d2011-07-29 19:53:35 +00001388 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001389
1390 if (!target)
1391 return NULL;
1392
1393 Debugger &debugger = target->GetDebugger();
1394 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1395 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1396
1397 if (!script_interpreter)
1398 return NULL;
1399
1400 void* ret_val;
1401
1402 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1403 if (CurrentThreadHasPythonLock())
1404 {
1405 python_interpreter->EnterSession ();
1406 ret_val = g_swig_synthetic_script (class_name,
1407 python_interpreter->m_dictionary_name.c_str(),
1408 valobj);
1409 python_interpreter->LeaveSession ();
1410 }
1411 else
1412 {
1413 while (!GetPythonLock (1))
1414 fprintf (tmp_fh,
1415 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1416 python_interpreter->EnterSession ();
1417 ret_val = g_swig_synthetic_script (class_name,
1418 python_interpreter->m_dictionary_name.c_str(),
1419 valobj);
1420 python_interpreter->LeaveSession ();
1421 ReleasePythonLock ();
1422 }
1423
1424 return ret_val;
1425}
1426
Enrico Granataf7a9b142011-07-15 02:26:42 +00001427bool
1428ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output)
1429{
1430 StringList input(oneliner);
1431 return GenerateTypeScriptFunction(input, output);
1432}
1433
Chris Lattner24943d22010-06-08 16:52:24 +00001434bool
1435ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1436{
1437 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001438 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001439 int num_lines = user_input.GetSize ();
1440 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001441
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001442 // Check to see if we have any data; if not, just return.
1443 if (user_input.GetSize() == 0)
1444 return false;
1445
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001446 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1447 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001448
Caroline Ticeb447e842010-09-21 19:25:28 +00001449
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001450 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1451 ++num_created_functions;
1452 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001453
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001454 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001455 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001456
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001457 // Create the function name & definition string.
1458
Caroline Tice0aa2e552011-01-14 00:29:16 +00001459 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001460 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001461
1462 // Pre-pend code for setting up the session dictionary.
1463
1464 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1465 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1466 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1467 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1468 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001469
1470 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001471
1472 for (int i = 0; i < num_lines; ++i)
1473 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001474 sstr.Clear ();
1475 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1476 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001477 }
Chris Lattner24943d22010-06-08 16:52:24 +00001478
Caroline Tice0aa2e552011-01-14 00:29:16 +00001479 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1480 // got written to the values in the global dictionary, not the session dictionary).
1481
1482 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1483 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1484 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1485 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1486
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001487 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001488
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001489 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001490 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001491 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001492 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001493
1494 // Store the name of the auto-generated function to be called.
1495
1496 callback_data.AppendString (auto_generated_function_name.c_str());
1497 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001498}
1499
Enrico Granataf7a9b142011-07-15 02:26:42 +00001500std::string
1501ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1502 lldb::ValueObjectSP valobj)
1503{
1504
1505 if (!python_function_name || !(*python_function_name))
1506 return "<no function>";
1507
1508 if (!valobj.get())
1509 return "<no object>";
1510
Enrico Granata979e20d2011-07-29 19:53:35 +00001511 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001512
1513 if (!target)
1514 return "<no target>";
1515
1516 Debugger &debugger = target->GetDebugger();
1517 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1518 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1519
1520 if (!script_interpreter)
1521 return "<no python>";
1522
1523 std::string ret_val;
1524
1525 if (python_function_name
1526 && *python_function_name)
1527 {
1528 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1529 if (CurrentThreadHasPythonLock())
1530 {
1531 python_interpreter->EnterSession ();
1532 ret_val = g_swig_typescript_callback (python_function_name,
1533 python_interpreter->m_dictionary_name.c_str(),
1534 valobj);
1535 python_interpreter->LeaveSession ();
1536 }
1537 else
1538 {
1539 while (!GetPythonLock (1))
1540 fprintf (tmp_fh,
1541 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1542 python_interpreter->EnterSession ();
1543 ret_val = g_swig_typescript_callback (python_function_name,
1544 python_interpreter->m_dictionary_name.c_str(),
1545 valobj);
1546 python_interpreter->LeaveSession ();
1547 ReleasePythonLock ();
1548 }
1549 }
1550 else
1551 return "<no function name>";
1552
1553 return ret_val;
1554
1555}
1556
Greg Clayton5144f382010-10-07 17:14:24 +00001557bool
1558ScriptInterpreterPython::BreakpointCallbackFunction
1559(
1560 void *baton,
1561 StoppointCallbackContext *context,
1562 user_id_t break_id,
1563 user_id_t break_loc_id
1564)
1565{
1566 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1567 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001568
1569 if (!context)
1570 return true;
1571
1572 Target *target = context->exe_ctx.target;
1573
1574 if (!target)
1575 return true;
1576
1577 Debugger &debugger = target->GetDebugger();
1578 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1579 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1580
1581 if (!script_interpreter)
1582 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001583
1584 if (python_function_name != NULL
1585 && python_function_name[0] != '\0')
1586 {
1587 Thread *thread = context->exe_ctx.thread;
Greg Claytone86cbb92011-03-22 01:14:58 +00001588 const StackFrameSP stop_frame_sp (thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame));
Greg Clayton5144f382010-10-07 17:14:24 +00001589 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001590 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001591 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001592 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1593
1594 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001595 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001596 bool ret_val = true;
1597 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1598 if (CurrentThreadHasPythonLock())
1599 {
1600 python_interpreter->EnterSession ();
1601 ret_val = g_swig_breakpoint_callback (python_function_name,
1602 python_interpreter->m_dictionary_name.c_str(),
1603 stop_frame_sp,
1604 bp_loc_sp);
1605 python_interpreter->LeaveSession ();
1606 }
1607 else
1608 {
1609 while (!GetPythonLock (1))
1610 fprintf (tmp_fh,
1611 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1612 python_interpreter->EnterSession ();
1613 ret_val = g_swig_breakpoint_callback (python_function_name,
1614 python_interpreter->m_dictionary_name.c_str(),
1615 stop_frame_sp,
1616 bp_loc_sp);
1617 python_interpreter->LeaveSession ();
1618 ReleasePythonLock ();
1619 }
1620 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001621 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001622 }
Greg Clayton5144f382010-10-07 17:14:24 +00001623 }
1624 // We currently always true so we stop in case anything goes wrong when
1625 // trying to call the script function
1626 return true;
1627}
Caroline Tice2ade6112010-11-10 19:18:14 +00001628
1629lldb::thread_result_t
1630ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1631{
1632 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1633
1634 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1635
1636 if (log)
1637 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1638
1639 char error_str[1024];
1640 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001641 bool need_to_release_lock = true;
1642 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001643
Caroline Tice202f6b82011-01-17 21:55:19 +00001644 if (CurrentThreadHasPythonLock())
1645 {
1646 safe_to_run = true;
1647 need_to_release_lock = false;
1648 }
1649 else
1650 {
1651 int interval = 1;
1652 safe_to_run = GetPythonLock (interval);
1653 while (!safe_to_run)
1654 {
1655 interval = interval * 2;
1656 safe_to_run = GetPythonLock (interval);
1657 }
1658 }
1659
1660 if (pty_slave_name != NULL && safe_to_run)
1661 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001662 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001663
Caroline Tice202f6b82011-01-17 21:55:19 +00001664 script_interpreter->EnterSession ();
1665
Caroline Tice0aa2e552011-01-14 00:29:16 +00001666 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1667 PyRun_SimpleString (run_string.GetData());
1668 run_string.Clear ();
1669
1670 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1671 PyRun_SimpleString (run_string.GetData());
1672 run_string.Clear ();
1673
1674 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1675 PyRun_SimpleString (run_string.GetData());
1676 run_string.Clear ();
1677
1678 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1679 pty_slave_name);
1680 PyRun_SimpleString (run_string.GetData());
1681 run_string.Clear ();
1682
Johnny Chen8054ba32011-03-11 00:28:50 +00001683 // The following call drops into the embedded interpreter loop and stays there until the
1684 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001685
Caroline Ticece207c12011-03-11 00:21:55 +00001686 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001687 // 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 +00001688 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1689
1690 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1691 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1692 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1693 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1694 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1695 // hang (it's happened before).
1696
Caroline Tice9d352ce2011-03-07 23:24:28 +00001697 Py_BEGIN_ALLOW_THREADS
1698 PyGILState_STATE gstate = PyGILState_Ensure();
1699
Caroline Tice0aa2e552011-01-14 00:29:16 +00001700 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1701 PyRun_SimpleString (run_string.GetData());
1702 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001703
Caroline Tice9d352ce2011-03-07 23:24:28 +00001704 PyGILState_Release (gstate);
1705 Py_END_ALLOW_THREADS
1706
Caroline Tice0aa2e552011-01-14 00:29:16 +00001707 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1708 PyRun_SimpleString (run_string.GetData());
1709 run_string.Clear();
1710
1711 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1712 PyRun_SimpleString (run_string.GetData());
1713 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001714
1715 script_interpreter->LeaveSession ();
1716
Caroline Tice2ade6112010-11-10 19:18:14 +00001717 }
1718
Caroline Tice202f6b82011-01-17 21:55:19 +00001719 if (!safe_to_run)
1720 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1721 "Python interpreter locked on another thread; unable to acquire lock.\n");
1722
1723 if (need_to_release_lock)
1724 ReleasePythonLock ();
1725
Caroline Tice2ade6112010-11-10 19:18:14 +00001726 if (script_interpreter->m_embedded_thread_input_reader_sp)
1727 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1728
1729 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001730
1731 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001732
1733 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1734 if (log)
1735 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1736
1737
Johnny Chen8054ba32011-03-11 00:28:50 +00001738 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001739 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001740 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1741 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1742 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001743
Caroline Tice2ade6112010-11-10 19:18:14 +00001744 return NULL;
1745}
1746
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001747uint32_t
1748ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1749{
1750 if (!implementor)
1751 return 0;
1752
1753 if (!g_swig_calc_children)
1754 return 0;
1755
1756 ScriptInterpreterPython *python_interpreter = this;
1757
1758 uint32_t ret_val = 0;
1759
1760 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1761 if (CurrentThreadHasPythonLock())
1762 {
1763 python_interpreter->EnterSession ();
1764 ret_val = g_swig_calc_children (implementor);
1765 python_interpreter->LeaveSession ();
1766 }
1767 else
1768 {
1769 while (!GetPythonLock (1))
1770 fprintf (tmp_fh,
1771 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1772 python_interpreter->EnterSession ();
1773 ret_val = g_swig_calc_children (implementor);
1774 python_interpreter->LeaveSession ();
1775 ReleasePythonLock ();
1776 }
1777
1778 return ret_val;
1779}
1780
1781void*
1782ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1783{
1784 if (!implementor)
1785 return 0;
1786
1787 if (!g_swig_get_child_index)
1788 return 0;
1789
1790 ScriptInterpreterPython *python_interpreter = this;
1791
1792 void* ret_val = NULL;
1793
1794 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1795 if (CurrentThreadHasPythonLock())
1796 {
1797 python_interpreter->EnterSession ();
1798 ret_val = g_swig_get_child_index (implementor,idx);
1799 python_interpreter->LeaveSession ();
1800 }
1801 else
1802 {
1803 while (!GetPythonLock (1))
1804 fprintf (tmp_fh,
1805 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1806 python_interpreter->EnterSession ();
1807 ret_val = g_swig_get_child_index (implementor,idx);
1808 python_interpreter->LeaveSession ();
1809 ReleasePythonLock ();
1810 }
1811
1812 return ret_val;
1813}
1814
1815int
1816ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1817{
1818 if (!implementor)
1819 return UINT32_MAX;
1820
1821 if (!g_swig_get_index_child)
1822 return UINT32_MAX;
1823
1824 ScriptInterpreterPython *python_interpreter = this;
1825
1826 int ret_val = UINT32_MAX;
1827
1828 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1829 if (CurrentThreadHasPythonLock())
1830 {
1831 python_interpreter->EnterSession ();
1832 ret_val = g_swig_get_index_child (implementor, child_name);
1833 python_interpreter->LeaveSession ();
1834 }
1835 else
1836 {
1837 while (!GetPythonLock (1))
1838 fprintf (tmp_fh,
1839 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1840 python_interpreter->EnterSession ();
1841 ret_val = g_swig_get_index_child (implementor, child_name);
1842 python_interpreter->LeaveSession ();
1843 ReleasePythonLock ();
1844 }
1845
1846 return ret_val;
1847}
1848
Enrico Granata979e20d2011-07-29 19:53:35 +00001849void
1850ScriptInterpreterPython::UpdateSynthProviderInstance (void* implementor)
1851{
1852 if (!implementor)
1853 return;
1854
1855 if (!g_swig_update_provider)
1856 return;
1857
1858 ScriptInterpreterPython *python_interpreter = this;
1859
1860 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1861 if (CurrentThreadHasPythonLock())
1862 {
1863 python_interpreter->EnterSession ();
1864 g_swig_update_provider (implementor);
1865 python_interpreter->LeaveSession ();
1866 }
1867 else
1868 {
1869 while (!GetPythonLock (1))
1870 fprintf (tmp_fh,
1871 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1872 python_interpreter->EnterSession ();
1873 g_swig_update_provider (implementor);
1874 python_interpreter->LeaveSession ();
1875 ReleasePythonLock ();
1876 }
1877
1878 return;
1879}
1880
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001881lldb::SBValue*
1882ScriptInterpreterPython::CastPyObjectToSBValue (void* data)
1883{
1884 if (!data)
1885 return NULL;
1886
1887 if (!g_swig_cast_to_sbvalue)
1888 return NULL;
1889
1890 ScriptInterpreterPython *python_interpreter = this;
1891
1892 lldb::SBValue* ret_val = NULL;
1893
1894 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1895 if (CurrentThreadHasPythonLock())
1896 {
1897 python_interpreter->EnterSession ();
1898 ret_val = g_swig_cast_to_sbvalue (data);
1899 python_interpreter->LeaveSession ();
1900 }
1901 else
1902 {
1903 while (!GetPythonLock (1))
1904 fprintf (tmp_fh,
1905 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1906 python_interpreter->EnterSession ();
1907 ret_val = g_swig_cast_to_sbvalue (data);
1908 python_interpreter->LeaveSession ();
1909 ReleasePythonLock ();
1910 }
1911
1912 return ret_val;
1913}
1914
Enrico Granatac2a28252011-08-16 16:49:25 +00001915bool
1916ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1917 const char* args,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001918 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001919 Error& error)
1920{
1921 if (!impl_function)
1922 {
1923 error.SetErrorString("no function to execute");
1924 return false;
1925 }
1926
1927 if (!g_swig_call_command)
1928 {
1929 error.SetErrorString("no helper function to run scripted commands");
1930 return false;
1931 }
1932
1933 ScriptInterpreterPython *python_interpreter = this;
Enrico Granata3370f0c2011-08-19 23:56:34 +00001934
Enrico Granatac2a28252011-08-16 16:49:25 +00001935 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
1936
1937 bool ret_val;
1938
1939 std::string err_msg;
1940
1941 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1942 if (CurrentThreadHasPythonLock())
1943 {
1944 python_interpreter->EnterSession ();
1945 ret_val = g_swig_call_command (impl_function,
1946 python_interpreter->m_dictionary_name.c_str(),
1947 debugger_sp,
1948 args,
1949 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001950 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001951 python_interpreter->LeaveSession ();
1952 }
1953 else
1954 {
1955 while (!GetPythonLock (1))
1956 fprintf (tmp_fh,
1957 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1958 python_interpreter->EnterSession ();
1959 ret_val = g_swig_call_command (impl_function,
1960 python_interpreter->m_dictionary_name.c_str(),
1961 debugger_sp,
1962 args,
1963 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001964 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001965 python_interpreter->LeaveSession ();
1966 ReleasePythonLock ();
1967 }
1968
1969 if (!ret_val)
1970 error.SetErrorString(err_msg.c_str());
1971 else
1972 error.Clear();
Enrico Granata3370f0c2011-08-19 23:56:34 +00001973
Enrico Granatac2a28252011-08-16 16:49:25 +00001974 return ret_val;
1975
1976
1977 return true;
1978
1979}
1980
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001981// in Python, a special attribute __doc__ contains the docstring
1982// for an object (function, method, class, ...) if any is defined
1983// Otherwise, the attribute's value is None
1984std::string
1985ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1986{
1987 std::string command(item);
1988 command += ".__doc__";
1989
1990 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1991
1992 if (ExecuteOneLineWithReturn (command.c_str(),
1993 ScriptInterpreter::eCharStrOrNone,
1994 &result_ptr) && result_ptr)
1995 {
1996 return std::string(result_ptr);
1997 }
1998 else
1999 return std::string("");
2000}
Caroline Tice2ade6112010-11-10 19:18:14 +00002001
Caroline Tice0aa2e552011-01-14 00:29:16 +00002002void
Greg Claytone86cbb92011-03-22 01:14:58 +00002003ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00002004 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002005 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
2006 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
2007 SWIGPythonCalculateNumChildren python_swig_calc_children,
2008 SWIGPythonGetChildAtIndex python_swig_get_child_index,
2009 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
Enrico Granata979e20d2011-07-29 19:53:35 +00002010 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue,
Enrico Granatac2a28252011-08-16 16:49:25 +00002011 SWIGPythonUpdateSynthProviderInstance python_swig_update_provider,
2012 SWIGPythonCallCommand python_swig_call_command)
Greg Claytone86cbb92011-03-22 01:14:58 +00002013{
2014 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00002015 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
2016 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002017 g_swig_synthetic_script = python_swig_synthetic_script;
2018 g_swig_calc_children = python_swig_calc_children;
2019 g_swig_get_child_index = python_swig_get_child_index;
2020 g_swig_get_index_child = python_swig_get_index_child;
2021 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Enrico Granata979e20d2011-07-29 19:53:35 +00002022 g_swig_update_provider = python_swig_update_provider;
Enrico Granatac2a28252011-08-16 16:49:25 +00002023 g_swig_call_command = python_swig_call_command;
Greg Claytone86cbb92011-03-22 01:14:58 +00002024}
2025
2026void
2027ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00002028{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002029 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
2030
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002031 // Python will muck with STDIN terminal state, so save off any current TTY
2032 // settings so we can restore them.
2033 TerminalState stdin_tty_state;
2034 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002035
2036 // Find the module that owns this code and use that path we get to
2037 // set the PYTHONPATH appropriately.
2038
2039 FileSpec file_spec;
2040 char python_dir_path[PATH_MAX];
2041 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
2042 {
2043 std::string python_path;
2044 const char *curr_python_path = ::getenv ("PYTHONPATH");
2045 if (curr_python_path)
2046 {
2047 // We have a current value for PYTHONPATH, so lets append to it
2048 python_path.append (curr_python_path);
2049 }
2050
2051 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2052 {
2053 if (!python_path.empty())
2054 python_path.append (1, ':');
2055 python_path.append (python_dir_path);
2056 }
2057
2058 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
2059 {
2060 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2061 {
2062 if (!python_path.empty())
2063 python_path.append (1, ':');
2064 python_path.append (python_dir_path);
2065 }
2066 }
2067 const char *pathon_path_env_cstr = python_path.c_str();
2068 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
2069 }
2070
Caroline Tice9d352ce2011-03-07 23:24:28 +00002071 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00002072 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002073
Greg Claytone86cbb92011-03-22 01:14:58 +00002074 // Initialize SWIG after setting up python
2075 assert (g_swig_init_callback != NULL);
2076 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002077
2078 // Update the path python uses to search for modules to include the current directory.
2079
Caroline Ticed4d92832011-06-13 21:33:00 +00002080 PyRun_SimpleString ("import sys");
2081 PyRun_SimpleString ("sys.path.append ('.')");
Caroline Tice0aa2e552011-01-14 00:29:16 +00002082
Caroline Ticed4d92832011-06-13 21:33:00 +00002083 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00002084
Caroline Ticed4d92832011-06-13 21:33:00 +00002085 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
2086 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
2087 PyRun_SimpleString ("import sys");
2088 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00002089
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002090 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002091}
2092
Greg Claytone86cbb92011-03-22 01:14:58 +00002093//void
2094//ScriptInterpreterPython::Terminate ()
2095//{
2096// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
2097// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
2098// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
2099// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
2100// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
2101// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
2102// // within Py_Finalize, which results in a seg fault.
2103// //
2104// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
2105// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
2106// // process exits).
2107// //
2108//// Py_Finalize ();
2109//}