blob: ba76849cc31c8f0c4c443f2f1f5e16425c2c6c23 [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"
Greg Clayton63094e02010-06-23 01:19:29 +000023#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000025#include "lldb/Core/Timer.h"
26#include "lldb/Host/Host.h"
27#include "lldb/Interpreter/CommandInterpreter.h"
28#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton5144f382010-10-07 17:14:24 +000029#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030
Chris Lattner24943d22010-06-08 16:52:24 +000031using namespace lldb;
32using namespace lldb_private;
33
Greg Claytone86cbb92011-03-22 01:14:58 +000034
35static ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL;
36static ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL;
Enrico Granataf7a9b142011-07-15 02:26:42 +000037static ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL;
Enrico Granata9ae7cef2011-07-24 00:14:56 +000038static ScriptInterpreter::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = NULL;
39static ScriptInterpreter::SWIGPythonCalculateNumChildren g_swig_calc_children = NULL;
40static ScriptInterpreter::SWIGPythonGetChildAtIndex g_swig_get_child_index = NULL;
41static ScriptInterpreter::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = NULL;
42static ScriptInterpreter::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = NULL;
Enrico Granata979e20d2011-07-29 19:53:35 +000043static ScriptInterpreter::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = NULL;
Enrico Granatac2a28252011-08-16 16:49:25 +000044static ScriptInterpreter::SWIGPythonCallCommand g_swig_call_command = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +000045
46static int
47_check_and_flush (FILE *stream)
48{
49 int prev_fail = ferror (stream);
50 return fflush (stream) || prev_fail ? EOF : 0;
51}
52
Caroline Tice202f6b82011-01-17 21:55:19 +000053static Predicate<lldb::tid_t> &
54PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +000055{
Caroline Tice202f6b82011-01-17 21:55:19 +000056 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
57 return g_interpreter_is_running;
58}
59
60static bool
61CurrentThreadHasPythonLock ()
62{
63 TimeValue timeout;
64
65 timeout = TimeValue::Now(); // Don't wait any time.
66
67 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
68}
69
70static bool
71GetPythonLock (uint32_t seconds_to_wait)
72{
73
74 TimeValue timeout;
75
76 if (seconds_to_wait != UINT32_MAX)
77 {
78 timeout = TimeValue::Now();
79 timeout.OffsetWithSeconds (seconds_to_wait);
80 }
81
82 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
83 Host::GetCurrentThreadID(), &timeout, NULL);
84}
85
86static void
87ReleasePythonLock ()
88{
89 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +000090}
91
Greg Clayton63094e02010-06-23 01:19:29 +000092ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +000093 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +000094 m_embedded_python_pty (),
95 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +000096 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +000097 m_new_sysout (NULL),
98 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +000099 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000100 m_session_is_active (false),
101 m_pty_slave_is_open (false),
102 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000103{
104
Greg Clayton7c330d62011-01-27 01:01:10 +0000105 static int g_initialized = false;
106
107 if (!g_initialized)
108 {
109 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000110 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000111 }
112
Caroline Tice202f6b82011-01-17 21:55:19 +0000113 bool safe_to_run = false;
114 bool need_to_release_lock = true;
115 int interval = 5; // Number of seconds to try getting the Python lock before timing out.
116
117 // We don't dare exit this function without finishing setting up the script interpreter, so we must wait until
118 // we can get the Python lock.
119
120 if (CurrentThreadHasPythonLock())
121 {
122 safe_to_run = true;
123 need_to_release_lock = false;
124 }
125
126 while (!safe_to_run)
127 {
128 safe_to_run = GetPythonLock (interval);
129 if (!safe_to_run)
130 {
131 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
132 fprintf (tmp_fh,
133 "Python interpreter is locked on another thread; "
134 "please release interpreter in order to continue.\n");
135 interval = interval * 2;
136 }
137 }
138
Caroline Tice0aa2e552011-01-14 00:29:16 +0000139 m_dictionary_name.append("_dict");
140 StreamString run_string;
141 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
142 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000143
Caroline Tice0aa2e552011-01-14 00:29:16 +0000144 run_string.Clear();
145 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
146 PyRun_SimpleString (run_string.GetData());
147
148 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
149 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
150 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
151 // call to Debugger::Terminate is made, the ref-count has the correct value.
152 //
153 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
154 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000155
Caroline Tice0aa2e552011-01-14 00:29:16 +0000156 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000157
Caroline Tice0aa2e552011-01-14 00:29:16 +0000158 run_string.Clear();
159 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
160 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000161
Caroline Tice0aa2e552011-01-14 00:29:16 +0000162 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000163
Caroline Tice0aa2e552011-01-14 00:29:16 +0000164 if (new_count > old_count)
165 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000166
Caroline Tice0aa2e552011-01-14 00:29:16 +0000167 run_string.Clear();
168 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
169 PyRun_SimpleString (run_string.GetData());
170
171 run_string.Clear();
172 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
173 interpreter.GetDebugger().GetID());
174 PyRun_SimpleString (run_string.GetData());
175
Enrico Granata074e3b62011-08-17 19:07:52 +0000176 run_string.Clear();
177 run_string.Printf ("run_one_line (%s, 'from osxcpp import *')", m_dictionary_name.c_str(),
178 interpreter.GetDebugger().GetID());
179 PyRun_SimpleString (run_string.GetData());
180
Caroline Tice0aa2e552011-01-14 00:29:16 +0000181 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000182 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000183 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000184 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000185
186 if (need_to_release_lock)
187 ReleasePythonLock();
Chris Lattner24943d22010-06-08 16:52:24 +0000188}
189
190ScriptInterpreterPython::~ScriptInterpreterPython ()
191{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000192 Debugger &debugger = GetCommandInterpreter().GetDebugger();
193
194 if (m_embedded_thread_input_reader_sp.get() != NULL)
195 {
196 m_embedded_thread_input_reader_sp->SetIsDone (true);
197 m_embedded_python_pty.CloseSlaveFileDescriptor();
198 m_pty_slave_is_open = false;
199 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
200 m_embedded_thread_input_reader_sp.reset();
201 debugger.PopInputReader (reader_sp);
202 }
203
204 if (m_new_sysout)
205 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000206 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
207 if (!CurrentThreadHasPythonLock ())
208 {
209 while (!GetPythonLock (1))
210 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
211 Py_DECREF (m_new_sysout);
212 ReleasePythonLock ();
213 }
214 else
215 Py_DECREF (m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000216 }
Chris Lattner24943d22010-06-08 16:52:24 +0000217}
218
Caroline Tice0aa2e552011-01-14 00:29:16 +0000219void
220ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
221{
222 if (fh == NULL)
223 return;
224
225 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000226
Caroline Tice202f6b82011-01-17 21:55:19 +0000227 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
228 if (!CurrentThreadHasPythonLock ())
229 {
230 while (!GetPythonLock (1))
231 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
232 EnterSession ();
233 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
234 LeaveSession ();
235 ReleasePythonLock ();
236 }
237 else
238 {
239 EnterSession ();
240 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
241 LeaveSession ();
242 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000243}
244
245void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000246ScriptInterpreterPython::SaveTerminalState (int fd)
247{
248 // Python mucks with the terminal state of STDIN. If we can possibly avoid
249 // this by setting the file handles up correctly prior to entering the
250 // interpreter we should. For now we save and restore the terminal state
251 // on the input file handle.
252 m_terminal_state.Save (fd, false);
253}
254
255void
256ScriptInterpreterPython::RestoreTerminalState ()
257{
258 // Python mucks with the terminal state of STDIN. If we can possibly avoid
259 // this by setting the file handles up correctly prior to entering the
260 // interpreter we should. For now we save and restore the terminal state
261 // on the input file handle.
262 m_terminal_state.Restore();
263}
264
265
266
267void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000268ScriptInterpreterPython::LeaveSession ()
269{
270 m_session_is_active = false;
271}
272
273void
274ScriptInterpreterPython::EnterSession ()
275{
276 // If we have already entered the session, without having officially 'left' it, then there is no need to
277 // 'enter' it again.
278
279 if (m_session_is_active)
280 return;
281
282 m_session_is_active = true;
283
Caroline Tice202f6b82011-01-17 21:55:19 +0000284 StreamString run_string;
285
286 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
287 GetCommandInterpreter().GetDebugger().GetID());
288 PyRun_SimpleString (run_string.GetData());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000289 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +0000290
Caroline Tice0aa2e552011-01-14 00:29:16 +0000291
Caroline Tice6af65cb2011-05-03 21:21:50 +0000292 run_string.Printf ("run_one_line (%s, 'lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%d)')",
293 m_dictionary_name.c_str(),
294 GetCommandInterpreter().GetDebugger().GetID());
295 PyRun_SimpleString (run_string.GetData());
296 run_string.Clear();
297
298
299 ExecutionContext exe_ctx = m_interpreter.GetDebugger().GetSelectedExecutionContext();
300
301 if (exe_ctx.target)
302 run_string.Printf ("run_one_line (%s, 'lldb.target = lldb.debugger.GetSelectedTarget()')",
303 m_dictionary_name.c_str());
304 else
305 run_string.Printf ("run_one_line (%s, 'lldb.target = None')", m_dictionary_name.c_str());
306 PyRun_SimpleString (run_string.GetData());
307 run_string.Clear();
308
309 if (exe_ctx.process)
310 run_string.Printf ("run_one_line (%s, 'lldb.process = lldb.target.GetProcess()')", m_dictionary_name.c_str());
311 else
312 run_string.Printf ("run_one_line (%s, 'lldb.process = None')", m_dictionary_name.c_str());
313 PyRun_SimpleString (run_string.GetData());
314 run_string.Clear();
315
316 if (exe_ctx.thread)
317 run_string.Printf ("run_one_line (%s, 'lldb.thread = lldb.process.GetSelectedThread ()')",
318 m_dictionary_name.c_str());
319 else
320 run_string.Printf ("run_one_line (%s, 'lldb.thread = None')", m_dictionary_name.c_str());
321 PyRun_SimpleString (run_string.GetData());
322 run_string.Clear();
323
324 if (exe_ctx.frame)
325 run_string.Printf ("run_one_line (%s, 'lldb.frame = lldb.thread.GetSelectedFrame ()')",
326 m_dictionary_name.c_str());
327 else
328 run_string.Printf ("run_one_line (%s, 'lldb.frame = None')", m_dictionary_name.c_str());
329 PyRun_SimpleString (run_string.GetData());
330 run_string.Clear();
331
Caroline Tice0aa2e552011-01-14 00:29:16 +0000332 PyObject *sysmod = PyImport_AddModule ("sys");
333 PyObject *sysdict = PyModule_GetDict (sysmod);
334
335 if ((m_new_sysout != NULL)
336 && (sysmod != NULL)
337 && (sysdict != NULL))
338 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
339
340 if (PyErr_Occurred())
341 PyErr_Clear ();
342
Caroline Tice0aa2e552011-01-14 00:29:16 +0000343 if (!m_pty_slave_is_open)
344 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000345 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000346 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
347 m_pty_slave_name.c_str());
348 PyRun_SimpleString (run_string.GetData());
349 m_pty_slave_is_open = true;
350
351 run_string.Clear();
352 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
353 PyRun_SimpleString (run_string.GetData());
354 }
355}
356
357
Johnny Chen60dde642010-07-30 22:33:14 +0000358bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000359ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000360{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000361 if (!m_valid_session)
362 return false;
363
Caroline Tice0aa2e552011-01-14 00:29:16 +0000364
Caroline Tice0aa2e552011-01-14 00:29:16 +0000365
Caroline Tice4a461da2011-01-14 21:09:29 +0000366 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
367 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
368 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
369 // method to pass the command string directly down to Python.
370
371
Caroline Tice202f6b82011-01-17 21:55:19 +0000372 bool need_to_release_lock = true;
373
374 if (CurrentThreadHasPythonLock())
375 need_to_release_lock = false;
376 else if (!GetPythonLock (1))
377 {
378 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
379 "Python interpreter is currently locked by another thread; unable to process command.\n");
380 return false;
381 }
382
383 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000384 bool success = false;
385
Greg Clayton63094e02010-06-23 01:19:29 +0000386 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000387 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000388 // Find the correct script interpreter dictionary in the main module.
389 PyObject *main_mod = PyImport_AddModule ("__main__");
390 PyObject *script_interpreter_dict = NULL;
391 if (main_mod != NULL)
392 {
393 PyObject *main_dict = PyModule_GetDict (main_mod);
394 if ((main_dict != NULL)
395 && PyDict_Check (main_dict))
396 {
397 // Go through the main dictionary looking for the correct python script interpreter dictionary
398 PyObject *key, *value;
399 Py_ssize_t pos = 0;
400
401 while (PyDict_Next (main_dict, &pos, &key, &value))
402 {
403 // We have stolen references to the key and value objects in the dictionary; we need to increment
404 // them now so that Python's garbage collector doesn't collect them out from under us.
405 Py_INCREF (key);
406 Py_INCREF (value);
407 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
408 {
409 script_interpreter_dict = value;
410 break;
411 }
412 }
413 }
414
415 if (script_interpreter_dict != NULL)
416 {
417 PyObject *pfunc = NULL;
418 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
419 if (pmod != NULL)
420 {
421 PyObject *pmod_dict = PyModule_GetDict (pmod);
422 if ((pmod_dict != NULL)
423 && PyDict_Check (pmod_dict))
424 {
425 PyObject *key, *value;
426 Py_ssize_t pos = 0;
427
428 while (PyDict_Next (pmod_dict, &pos, &key, &value))
429 {
430 Py_INCREF (key);
431 Py_INCREF (value);
432 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
433 {
434 pfunc = value;
435 break;
436 }
437 }
438
439 PyObject *string_arg = PyString_FromString (command);
440 if (pfunc && string_arg && PyCallable_Check (pfunc))
441 {
442 PyObject *pargs = PyTuple_New (2);
443 if (pargs != NULL)
444 {
445 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
446 PyTuple_SetItem (pargs, 1, string_arg);
447 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
448 Py_DECREF (pargs);
449 if (pvalue != NULL)
450 {
451 Py_DECREF (pvalue);
452 success = true;
453 }
454 else if (PyErr_Occurred ())
455 {
456 PyErr_Print();
457 PyErr_Clear();
458 }
459 }
460 }
461 }
462 }
463 Py_INCREF (script_interpreter_dict);
464 }
465 }
Greg Clayton63094e02010-06-23 01:19:29 +0000466
Caroline Tice0aa2e552011-01-14 00:29:16 +0000467 LeaveSession ();
468
Caroline Tice202f6b82011-01-17 21:55:19 +0000469 if (need_to_release_lock)
470 ReleasePythonLock();
471
Caroline Tice4a461da2011-01-14 21:09:29 +0000472 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000473 return true;
474
475 // The one-liner failed. Append the error message.
476 if (result)
477 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
478 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000479 }
Johnny Chen60dde642010-07-30 22:33:14 +0000480
Caroline Tice0aa2e552011-01-14 00:29:16 +0000481 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000482
483 if (need_to_release_lock)
484 ReleasePythonLock ();
485
Johnny Chen60dde642010-07-30 22:33:14 +0000486 if (result)
487 result->AppendError ("empty command passed to python\n");
488 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000489}
490
491
492
493size_t
494ScriptInterpreterPython::InputReaderCallback
495(
496 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000497 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000498 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000499 const char *bytes,
500 size_t bytes_len
501)
502{
Caroline Tice2ade6112010-11-10 19:18:14 +0000503 lldb::thread_t embedded_interpreter_thread;
504 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
505
Chris Lattner24943d22010-06-08 16:52:24 +0000506 if (baton == NULL)
507 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000508
509 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
510
511 if (script_interpreter->m_script_lang != eScriptLanguagePython)
512 return 0;
513
Caroline Tice892fadd2011-06-16 16:27:19 +0000514 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
515 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
516
Chris Lattner24943d22010-06-08 16:52:24 +0000517 switch (notification)
518 {
519 case eInputReaderActivate:
520 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000521 if (!batch_mode)
522 {
523 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
524 out_stream->Flush();
525 }
Greg Clayton58928562011-02-09 01:08:52 +0000526
Chris Lattner24943d22010-06-08 16:52:24 +0000527 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000528 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
529 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000530 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000531
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000532 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000533
Caroline Tice202f6b82011-01-17 21:55:19 +0000534 if (!CurrentThreadHasPythonLock())
535 {
536 while (!GetPythonLock(1))
537 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000538 out_stream->Printf ("Python interpreter locked on another thread; waiting to acquire lock...\n");
539 out_stream->Flush();
Caroline Tice202f6b82011-01-17 21:55:19 +0000540 }
541 script_interpreter->EnterSession ();
542 ReleasePythonLock();
543 }
544 else
545 script_interpreter->EnterSession ();
546
Caroline Tice2ade6112010-11-10 19:18:14 +0000547 char error_str[1024];
548 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
549 sizeof(error_str)))
550 {
551 if (log)
552 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
553 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
554 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
555 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
556 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000557 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000558 {
559 if (log)
560 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
561 Error detach_error;
562 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
563 }
564 else
565 {
566 if (log)
567 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
568 reader.SetIsDone (true);
569 }
570 }
571 else
572 {
573 if (log)
574 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
575 reader.SetIsDone (true);
576 }
Chris Lattner24943d22010-06-08 16:52:24 +0000577 }
578 break;
579
580 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000581 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000582 break;
583
584 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000585 if (!CurrentThreadHasPythonLock())
586 {
587 while (!GetPythonLock(1))
588 {
589 // Wait until lock is acquired.
590 }
591 script_interpreter->EnterSession ();
592 ReleasePythonLock();
593 }
594 else
595 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000596 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000597
Caroline Tice4a348082011-05-02 20:41:46 +0000598 case eInputReaderAsynchronousOutputWritten:
599 break;
600
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000601 case eInputReaderInterrupt:
602 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
603 break;
604
605 case eInputReaderEndOfFile:
606 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
607 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000608
609 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000610 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000611 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000612 if (log)
613 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
614 bytes_len);
615 if (bytes && bytes_len)
616 {
617 if ((int) bytes[0] == 4)
618 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
619 else
620 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
621 }
622 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000623 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000624 else
625 {
626 if (log)
627 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
628 bytes,
629 bytes_len);
630 reader.SetIsDone (true);
631 }
632
Chris Lattner24943d22010-06-08 16:52:24 +0000633 break;
634
635 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000636 script_interpreter->LeaveSession ();
637
Chris Lattner24943d22010-06-08 16:52:24 +0000638 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000639 if (log)
640 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000641
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000642 script_interpreter->RestoreTerminalState ();
643
Caroline Tice2ade6112010-11-10 19:18:14 +0000644 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000645 break;
646 }
647
648 return bytes_len;
649}
650
651
652void
Greg Clayton238c0a12010-09-18 01:14:36 +0000653ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000654{
655 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
656
Caroline Tice0aa2e552011-01-14 00:29:16 +0000657 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000658
659 // At the moment, the only time the debugger does not have an input file handle is when this is called
660 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
661 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
662 // do it.
663
Greg Clayton58928562011-02-09 01:08:52 +0000664 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000665 return;
666
Greg Clayton63094e02010-06-23 01:19:29 +0000667 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000668 if (reader_sp)
669 {
670 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
671 this, // baton
672 eInputReaderGranularityLine, // token size, to pass to callback function
673 NULL, // end token
674 NULL, // prompt
675 true)); // echo input
676
677 if (error.Success())
678 {
Greg Clayton63094e02010-06-23 01:19:29 +0000679 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000680 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000681 }
682 }
683}
684
685bool
686ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
687 ScriptInterpreter::ReturnType return_type,
688 void *ret_value)
689{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000690
Caroline Tice202f6b82011-01-17 21:55:19 +0000691 bool need_to_release_lock = true;
692
693 if (CurrentThreadHasPythonLock())
694 need_to_release_lock = false;
695 else if (!GetPythonLock (1))
696 {
697 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
698 "Python interpreter is currently locked by another thread; unable to process command.\n");
699 return false;
700 }
701
702 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000703
Chris Lattner24943d22010-06-08 16:52:24 +0000704 PyObject *py_return = NULL;
705 PyObject *mainmod = PyImport_AddModule ("__main__");
706 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000707 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000708 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000709 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000710 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000711 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000712
713 if (PyDict_Check (globals))
714 {
715 PyObject *key, *value;
716 Py_ssize_t pos = 0;
717
718 int i = 0;
719 while (PyDict_Next (globals, &pos, &key, &value))
720 {
721 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
722 // so that Python's garbage collector doesn't collect them out from under us.
723 Py_INCREF (key);
724 Py_INCREF (value);
725 char *c_str = PyString_AsString (key);
726 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
727 locals = value;
728 ++i;
729 }
730 }
Chris Lattner24943d22010-06-08 16:52:24 +0000731
Caroline Tice0aa2e552011-01-14 00:29:16 +0000732 if (locals == NULL)
733 {
734 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
735 should_decrement_locals = true;
736 }
737
738 if (locals == NULL)
739 {
740 locals = globals;
741 should_decrement_locals = false;
742 }
743
744 py_error = PyErr_Occurred();
745 if (py_error != NULL)
746 PyErr_Clear();
747
Chris Lattner24943d22010-06-08 16:52:24 +0000748 if (in_string != NULL)
749 {
750 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
751 if (py_return == NULL)
752 {
753 py_error = PyErr_Occurred ();
754 if (py_error != NULL)
755 PyErr_Clear ();
756
757 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
758 }
759
Caroline Tice0aa2e552011-01-14 00:29:16 +0000760 if (locals != NULL
761 && should_decrement_locals)
762 Py_DECREF (locals);
763
Chris Lattner24943d22010-06-08 16:52:24 +0000764 if (py_return != NULL)
765 {
766 switch (return_type)
767 {
768 case eCharPtr: // "char *"
769 {
770 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000771 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000772 break;
773 }
Enrico Granatac2a28252011-08-16 16:49:25 +0000774 case eCharStrOrNone: // char* or NULL if py_return == Py_None
775 {
776 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000777 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000778 break;
779 }
Chris Lattner24943d22010-06-08 16:52:24 +0000780 case eBool:
781 {
782 const char format[2] = "b";
783 success = PyArg_Parse (py_return, format, (bool *) ret_value);
784 break;
785 }
786 case eShortInt:
787 {
788 const char format[2] = "h";
789 success = PyArg_Parse (py_return, format, (short *) ret_value);
790 break;
791 }
792 case eShortIntUnsigned:
793 {
794 const char format[2] = "H";
795 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
796 break;
797 }
798 case eInt:
799 {
800 const char format[2] = "i";
801 success = PyArg_Parse (py_return, format, (int *) ret_value);
802 break;
803 }
804 case eIntUnsigned:
805 {
806 const char format[2] = "I";
807 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
808 break;
809 }
810 case eLongInt:
811 {
812 const char format[2] = "l";
813 success = PyArg_Parse (py_return, format, (long *) ret_value);
814 break;
815 }
816 case eLongIntUnsigned:
817 {
818 const char format[2] = "k";
819 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
820 break;
821 }
822 case eLongLong:
823 {
824 const char format[2] = "L";
825 success = PyArg_Parse (py_return, format, (long long *) ret_value);
826 break;
827 }
828 case eLongLongUnsigned:
829 {
830 const char format[2] = "K";
831 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
832 break;
833 }
834 case eFloat:
835 {
836 const char format[2] = "f";
837 success = PyArg_Parse (py_return, format, (float *) ret_value);
838 break;
839 }
840 case eDouble:
841 {
842 const char format[2] = "d";
843 success = PyArg_Parse (py_return, format, (double *) ret_value);
844 break;
845 }
846 case eChar:
847 {
848 const char format[2] = "c";
849 success = PyArg_Parse (py_return, format, (char *) ret_value);
850 break;
851 }
852 default:
853 {}
854 }
855 Py_DECREF (py_return);
856 if (success)
857 ret_success = true;
858 else
859 ret_success = false;
860 }
861 }
862
863 py_error = PyErr_Occurred();
864 if (py_error != NULL)
865 {
866 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
867 PyErr_Print ();
868 PyErr_Clear();
869 ret_success = false;
870 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000871
872 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000873
Caroline Tice202f6b82011-01-17 21:55:19 +0000874 if (need_to_release_lock)
875 ReleasePythonLock();
876
Chris Lattner24943d22010-06-08 16:52:24 +0000877 return ret_success;
878}
879
880bool
881ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
882{
Caroline Tice202f6b82011-01-17 21:55:19 +0000883 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
884 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000885
Caroline Tice202f6b82011-01-17 21:55:19 +0000886 if (CurrentThreadHasPythonLock())
887 need_to_release_lock = false;
888 else
889 {
890 while (!GetPythonLock (1))
891 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
892 }
893
894 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000895
Chris Lattner24943d22010-06-08 16:52:24 +0000896 bool success = false;
897 PyObject *py_return = NULL;
898 PyObject *mainmod = PyImport_AddModule ("__main__");
899 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000900 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000901 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000902 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000903
Caroline Tice0aa2e552011-01-14 00:29:16 +0000904 if (PyDict_Check (globals))
905 {
906 PyObject *key, *value;
907 Py_ssize_t pos = 0;
908
909 while (PyDict_Next (globals, &pos, &key, &value))
910 {
911 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
912 // so that Python's garbage collector doesn't collect them out from under us.
913 Py_INCREF (key);
914 Py_INCREF (value);
915 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
916 locals = value;
917 }
918 }
919
920 if (locals == NULL)
921 {
922 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
923 should_decrement_locals = true;
924 }
925
926 if (locals == NULL)
927 {
928 locals = globals;
929 should_decrement_locals = false;
930 }
931
932 py_error = PyErr_Occurred();
933 if (py_error != NULL)
934 PyErr_Clear();
935
Chris Lattner24943d22010-06-08 16:52:24 +0000936 if (in_string != NULL)
937 {
938 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
939 if (compiled_node)
940 {
941 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
942 if (compiled_code)
943 {
944 py_return = PyEval_EvalCode (compiled_code, globals, locals);
945 if (py_return != NULL)
946 {
947 success = true;
948 Py_DECREF (py_return);
949 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000950 if (locals && should_decrement_locals)
951 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000952 }
953 }
954 }
955
956 py_error = PyErr_Occurred ();
957 if (py_error != NULL)
958 {
959 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
960 PyErr_Print ();
961 PyErr_Clear();
962 success = false;
963 }
964
Caroline Tice0aa2e552011-01-14 00:29:16 +0000965 LeaveSession ();
966
Caroline Tice202f6b82011-01-17 21:55:19 +0000967 if (need_to_release_lock)
968 ReleasePythonLock();
969
Chris Lattner24943d22010-06-08 16:52:24 +0000970 return success;
971}
972
973static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
974
975size_t
976ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
977(
978 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000979 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000980 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000981 const char *bytes,
982 size_t bytes_len
983)
984{
Caroline Tice892fadd2011-06-16 16:27:19 +0000985 static StringList commands_in_progress;
986
987 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
988 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
989
Chris Lattner24943d22010-06-08 16:52:24 +0000990 switch (notification)
991 {
992 case eInputReaderActivate:
993 {
994 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +0000995 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +0000996 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000997 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000998 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +0000999 out_stream->Printf ("%s", reader.GetPrompt());
1000 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001001 }
1002 }
1003 break;
1004
1005 case eInputReaderDeactivate:
1006 break;
1007
1008 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001009 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001010 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001011 out_stream->Printf ("%s", reader.GetPrompt());
1012 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001013 }
Chris Lattner24943d22010-06-08 16:52:24 +00001014 break;
1015
Caroline Tice4a348082011-05-02 20:41:46 +00001016 case eInputReaderAsynchronousOutputWritten:
1017 break;
1018
Chris Lattner24943d22010-06-08 16:52:24 +00001019 case eInputReaderGotToken:
1020 {
1021 std::string temp_string (bytes, bytes_len);
1022 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001023 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001024 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001025 out_stream->Printf ("%s", reader.GetPrompt());
1026 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001027 }
Chris Lattner24943d22010-06-08 16:52:24 +00001028 }
1029 break;
1030
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001031 case eInputReaderEndOfFile:
1032 case eInputReaderInterrupt:
1033 // Control-c (SIGINT) & control-d both mean finish & exit.
1034 reader.SetIsDone(true);
1035
1036 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1037 if (notification == eInputReaderInterrupt)
1038 commands_in_progress.Clear();
1039
1040 // Fall through here...
1041
Chris Lattner24943d22010-06-08 16:52:24 +00001042 case eInputReaderDone:
1043 {
1044 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1045 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1046 data_ap->user_source.AppendList (commands_in_progress);
1047 if (data_ap.get())
1048 {
Greg Clayton63094e02010-06-23 01:19:29 +00001049 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001050 if (interpreter)
1051 {
1052 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1053 data_ap->script_source))
1054 {
1055 if (data_ap->script_source.GetSize() == 1)
1056 {
1057 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1058 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1059 }
1060 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001061 else if (!batch_mode)
1062 {
1063 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1064 out_stream->Flush();
1065 }
Chris Lattner24943d22010-06-08 16:52:24 +00001066 }
1067 else
1068 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001069 if (!batch_mode)
1070 {
1071 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1072 out_stream->Flush();
1073 }
Chris Lattner24943d22010-06-08 16:52:24 +00001074 }
1075 }
1076 }
1077 break;
1078
1079 }
1080
1081 return bytes_len;
1082}
1083
1084void
Greg Clayton238c0a12010-09-18 01:14:36 +00001085ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001086 CommandReturnObject &result)
1087{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001088 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1089
Greg Clayton63094e02010-06-23 01:19:29 +00001090 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001091
1092 if (reader_sp)
1093 {
1094 Error err = reader_sp->Initialize (
1095 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1096 bp_options, // baton
1097 eInputReaderGranularityLine, // token size, for feeding data to callback function
1098 "DONE", // end token
1099 "> ", // prompt
1100 true); // echo input
1101
1102 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001103 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001104 else
1105 {
1106 result.AppendError (err.AsCString());
1107 result.SetStatus (eReturnStatusFailed);
1108 }
1109 }
1110 else
1111 {
1112 result.AppendError("out of memory");
1113 result.SetStatus (eReturnStatusFailed);
1114 }
1115}
1116
Johnny Chen3e0571b2010-09-11 00:23:59 +00001117// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001118void
Greg Clayton238c0a12010-09-18 01:14:36 +00001119ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001120 const char *oneliner)
1121{
1122 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1123
1124 // It's necessary to set both user_source and script_source to the oneliner.
1125 // The former is used to generate callback description (as in breakpoint command list)
1126 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001127
Johnny Chend1c2dca2010-09-10 18:21:10 +00001128 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001129
Caroline Tice5136f942010-09-27 21:35:15 +00001130 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1131 {
1132 if (data_ap->script_source.GetSize() == 1)
1133 {
1134 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1135 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1136 }
1137 }
1138
Johnny Chend1c2dca2010-09-10 18:21:10 +00001139 return;
1140}
1141
Chris Lattner24943d22010-06-08 16:52:24 +00001142bool
1143ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1144{
1145 // Convert StringList to one long, newline delimited, const char *.
1146 std::string function_def_string;
1147
1148 int num_lines = function_def.GetSize();
1149
1150 for (int i = 0; i < num_lines; ++i)
1151 {
1152 function_def_string.append (function_def.GetStringAtIndex(i));
1153 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1154 function_def_string.append ("\n");
1155
1156 }
1157
1158 return ExecuteMultipleLines (function_def_string.c_str());
1159}
1160
Enrico Granataf7a9b142011-07-15 02:26:42 +00001161// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1162// use this code to generate their functions
1163bool
1164ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1165{
1166 int num_lines = input.GetSize ();
1167 if (num_lines == 0)
1168 return false;
1169 StreamString sstr;
1170 StringList auto_generated_function;
1171 auto_generated_function.AppendString (signature.c_str());
1172 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1173 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1174 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1175 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1176 // global dictionary.
1177
1178 // Wrap everything up inside the function, increasing the indentation.
1179
1180 for (int i = 0; i < num_lines; ++i)
1181 {
1182 sstr.Clear ();
1183 sstr.Printf (" %s", input.GetStringAtIndex (i));
1184 auto_generated_function.AppendString (sstr.GetData());
1185 }
1186 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1187 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1188 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1189 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1190
1191 // Verify that the results are valid Python.
1192
1193 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1194 return false;
1195
1196 return true;
1197
1198}
1199
1200// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1201// given to generated functions, of course)
1202bool
1203ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output)
1204{
1205 static int num_created_functions = 0;
1206 user_input.RemoveBlankLines ();
1207 int num_lines = user_input.GetSize ();
1208 StreamString sstr;
1209
1210 // Check to see if we have any data; if not, just return.
1211 if (user_input.GetSize() == 0)
1212 return false;
1213
1214 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1215 // ValueObject as parameter to the function.
1216
1217 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1218 ++num_created_functions;
1219 std::string auto_generated_function_name = sstr.GetData();
1220
1221 sstr.Clear();
1222 StringList auto_generated_function;
1223
1224 // Create the function name & definition string.
1225
1226 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1227 auto_generated_function.AppendString (sstr.GetData());
1228
1229 // Pre-pend code for setting up the session dictionary.
1230
1231 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1232 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1233 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1234 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1235 // global dictionary.
1236
1237 // Wrap everything up inside the function, increasing the indentation.
1238
1239 for (int i = 0; i < num_lines; ++i)
1240 {
1241 sstr.Clear ();
1242 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1243 auto_generated_function.AppendString (sstr.GetData());
1244 }
1245
1246 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1247 // got written to the values in the global dictionary, not the session dictionary).
1248
1249 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1250 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1251 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1252 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1253
1254 // Verify that the results are valid Python.
1255
1256 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1257 return false;
1258
1259 // Store the name of the auto-generated function to be called.
1260
1261 output.AppendString (auto_generated_function_name.c_str());
1262 return true;
1263}
1264
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001265bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001266ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, StringList &output)
1267{
1268 static int num_created_functions = 0;
1269 user_input.RemoveBlankLines ();
1270 int num_lines = user_input.GetSize ();
1271 StreamString sstr;
1272
1273 // Check to see if we have any data; if not, just return.
1274 if (user_input.GetSize() == 0)
1275 return false;
1276
1277 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1278 // ValueObject as parameter to the function.
1279
1280 sstr.Printf ("lldb_autogen_python_cmd_alias_func_%d", num_created_functions);
1281 ++num_created_functions;
1282 std::string auto_generated_function_name = sstr.GetData();
1283
1284 sstr.Clear();
1285 StringList auto_generated_function;
1286
1287 // Create the function name & definition string.
1288
1289 sstr.Printf ("def %s (debugger, args, dict):", auto_generated_function_name.c_str());
1290 auto_generated_function.AppendString (sstr.GetData());
1291
1292 // Pre-pend code for setting up the session dictionary.
1293
1294 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1295 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1296 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1297 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1298 // global dictionary.
1299
1300 // Wrap everything up inside the function, increasing the indentation.
1301
1302 for (int i = 0; i < num_lines; ++i)
1303 {
1304 sstr.Clear ();
1305 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1306 auto_generated_function.AppendString (sstr.GetData());
1307 }
1308
1309 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1310 // got written to the values in the global dictionary, not the session dictionary).
1311
1312 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1313 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1314 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1315 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1316
1317 // Verify that the results are valid Python.
1318
1319 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1320 return false;
1321
1322 // Store the name of the auto-generated function to be called.
1323
1324 output.AppendString (auto_generated_function_name.c_str());
1325 return true;
1326}
1327
1328
1329bool
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001330ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output)
1331{
1332 static int num_created_classes = 0;
1333 user_input.RemoveBlankLines ();
1334 int num_lines = user_input.GetSize ();
1335 StreamString sstr;
1336
1337 // Check to see if we have any data; if not, just return.
1338 if (user_input.GetSize() == 0)
1339 return false;
1340
1341 // Wrap all user input into a Python class
1342
1343 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1344 ++num_created_classes;
1345 std::string auto_generated_class_name = sstr.GetData();
1346
1347 sstr.Clear();
1348 StringList auto_generated_class;
1349
1350 // Create the function name & definition string.
1351
1352 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1353 auto_generated_class.AppendString (sstr.GetData());
1354
1355 // Wrap everything up inside the class, increasing the indentation.
1356
1357 for (int i = 0; i < num_lines; ++i)
1358 {
1359 sstr.Clear ();
1360 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1361 auto_generated_class.AppendString (sstr.GetData());
1362 }
1363
1364
1365 // Verify that the results are valid Python.
1366 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1367 // (TODO: rename that method to ExportDefinitionToInterpreter)
1368 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1369 return false;
1370
1371 // Store the name of the auto-generated class
1372
1373 output.AppendString (auto_generated_class_name.c_str());
1374 return true;
1375}
1376
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001377void*
1378ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1379 lldb::ValueObjectSP valobj)
1380{
1381 if (class_name.empty())
1382 return NULL;
1383
1384 if (!valobj.get())
1385 return NULL;
1386
Enrico Granata979e20d2011-07-29 19:53:35 +00001387 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001388
1389 if (!target)
1390 return NULL;
1391
1392 Debugger &debugger = target->GetDebugger();
1393 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1394 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1395
1396 if (!script_interpreter)
1397 return NULL;
1398
1399 void* ret_val;
1400
1401 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1402 if (CurrentThreadHasPythonLock())
1403 {
1404 python_interpreter->EnterSession ();
1405 ret_val = g_swig_synthetic_script (class_name,
1406 python_interpreter->m_dictionary_name.c_str(),
1407 valobj);
1408 python_interpreter->LeaveSession ();
1409 }
1410 else
1411 {
1412 while (!GetPythonLock (1))
1413 fprintf (tmp_fh,
1414 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1415 python_interpreter->EnterSession ();
1416 ret_val = g_swig_synthetic_script (class_name,
1417 python_interpreter->m_dictionary_name.c_str(),
1418 valobj);
1419 python_interpreter->LeaveSession ();
1420 ReleasePythonLock ();
1421 }
1422
1423 return ret_val;
1424}
1425
Enrico Granataf7a9b142011-07-15 02:26:42 +00001426bool
1427ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output)
1428{
1429 StringList input(oneliner);
1430 return GenerateTypeScriptFunction(input, output);
1431}
1432
Chris Lattner24943d22010-06-08 16:52:24 +00001433bool
1434ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1435{
1436 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001437 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001438 int num_lines = user_input.GetSize ();
1439 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001440
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001441 // Check to see if we have any data; if not, just return.
1442 if (user_input.GetSize() == 0)
1443 return false;
1444
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001445 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1446 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001447
Caroline Ticeb447e842010-09-21 19:25:28 +00001448
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001449 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1450 ++num_created_functions;
1451 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001452
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001453 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001454 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001455
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001456 // Create the function name & definition string.
1457
Caroline Tice0aa2e552011-01-14 00:29:16 +00001458 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001459 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001460
1461 // Pre-pend code for setting up the session dictionary.
1462
1463 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1464 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1465 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1466 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1467 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001468
1469 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001470
1471 for (int i = 0; i < num_lines; ++i)
1472 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001473 sstr.Clear ();
1474 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1475 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001476 }
Chris Lattner24943d22010-06-08 16:52:24 +00001477
Caroline Tice0aa2e552011-01-14 00:29:16 +00001478 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1479 // got written to the values in the global dictionary, not the session dictionary).
1480
1481 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1482 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1483 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1484 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1485
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001486 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001487
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001488 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001489 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001490 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001491 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001492
1493 // Store the name of the auto-generated function to be called.
1494
1495 callback_data.AppendString (auto_generated_function_name.c_str());
1496 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001497}
1498
Enrico Granataf7a9b142011-07-15 02:26:42 +00001499std::string
1500ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1501 lldb::ValueObjectSP valobj)
1502{
1503
1504 if (!python_function_name || !(*python_function_name))
1505 return "<no function>";
1506
1507 if (!valobj.get())
1508 return "<no object>";
1509
Enrico Granata979e20d2011-07-29 19:53:35 +00001510 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001511
1512 if (!target)
1513 return "<no target>";
1514
1515 Debugger &debugger = target->GetDebugger();
1516 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1517 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1518
1519 if (!script_interpreter)
1520 return "<no python>";
1521
1522 std::string ret_val;
1523
1524 if (python_function_name
1525 && *python_function_name)
1526 {
1527 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1528 if (CurrentThreadHasPythonLock())
1529 {
1530 python_interpreter->EnterSession ();
1531 ret_val = g_swig_typescript_callback (python_function_name,
1532 python_interpreter->m_dictionary_name.c_str(),
1533 valobj);
1534 python_interpreter->LeaveSession ();
1535 }
1536 else
1537 {
1538 while (!GetPythonLock (1))
1539 fprintf (tmp_fh,
1540 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1541 python_interpreter->EnterSession ();
1542 ret_val = g_swig_typescript_callback (python_function_name,
1543 python_interpreter->m_dictionary_name.c_str(),
1544 valobj);
1545 python_interpreter->LeaveSession ();
1546 ReleasePythonLock ();
1547 }
1548 }
1549 else
1550 return "<no function name>";
1551
1552 return ret_val;
1553
1554}
1555
Greg Clayton5144f382010-10-07 17:14:24 +00001556bool
1557ScriptInterpreterPython::BreakpointCallbackFunction
1558(
1559 void *baton,
1560 StoppointCallbackContext *context,
1561 user_id_t break_id,
1562 user_id_t break_loc_id
1563)
1564{
1565 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1566 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001567
1568 if (!context)
1569 return true;
1570
1571 Target *target = context->exe_ctx.target;
1572
1573 if (!target)
1574 return true;
1575
1576 Debugger &debugger = target->GetDebugger();
1577 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1578 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1579
1580 if (!script_interpreter)
1581 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001582
1583 if (python_function_name != NULL
1584 && python_function_name[0] != '\0')
1585 {
1586 Thread *thread = context->exe_ctx.thread;
Greg Claytone86cbb92011-03-22 01:14:58 +00001587 const StackFrameSP stop_frame_sp (thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame));
Greg Clayton5144f382010-10-07 17:14:24 +00001588 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001589 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001590 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001591 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1592
1593 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001594 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001595 bool ret_val = true;
1596 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1597 if (CurrentThreadHasPythonLock())
1598 {
1599 python_interpreter->EnterSession ();
1600 ret_val = g_swig_breakpoint_callback (python_function_name,
1601 python_interpreter->m_dictionary_name.c_str(),
1602 stop_frame_sp,
1603 bp_loc_sp);
1604 python_interpreter->LeaveSession ();
1605 }
1606 else
1607 {
1608 while (!GetPythonLock (1))
1609 fprintf (tmp_fh,
1610 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1611 python_interpreter->EnterSession ();
1612 ret_val = g_swig_breakpoint_callback (python_function_name,
1613 python_interpreter->m_dictionary_name.c_str(),
1614 stop_frame_sp,
1615 bp_loc_sp);
1616 python_interpreter->LeaveSession ();
1617 ReleasePythonLock ();
1618 }
1619 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001620 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001621 }
Greg Clayton5144f382010-10-07 17:14:24 +00001622 }
1623 // We currently always true so we stop in case anything goes wrong when
1624 // trying to call the script function
1625 return true;
1626}
Caroline Tice2ade6112010-11-10 19:18:14 +00001627
1628lldb::thread_result_t
1629ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1630{
1631 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1632
1633 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1634
1635 if (log)
1636 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1637
1638 char error_str[1024];
1639 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001640 bool need_to_release_lock = true;
1641 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001642
Caroline Tice202f6b82011-01-17 21:55:19 +00001643 if (CurrentThreadHasPythonLock())
1644 {
1645 safe_to_run = true;
1646 need_to_release_lock = false;
1647 }
1648 else
1649 {
1650 int interval = 1;
1651 safe_to_run = GetPythonLock (interval);
1652 while (!safe_to_run)
1653 {
1654 interval = interval * 2;
1655 safe_to_run = GetPythonLock (interval);
1656 }
1657 }
1658
1659 if (pty_slave_name != NULL && safe_to_run)
1660 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001661 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001662
Caroline Tice202f6b82011-01-17 21:55:19 +00001663 script_interpreter->EnterSession ();
1664
Caroline Tice0aa2e552011-01-14 00:29:16 +00001665 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1666 PyRun_SimpleString (run_string.GetData());
1667 run_string.Clear ();
1668
1669 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1670 PyRun_SimpleString (run_string.GetData());
1671 run_string.Clear ();
1672
1673 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1674 PyRun_SimpleString (run_string.GetData());
1675 run_string.Clear ();
1676
1677 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1678 pty_slave_name);
1679 PyRun_SimpleString (run_string.GetData());
1680 run_string.Clear ();
1681
Johnny Chen8054ba32011-03-11 00:28:50 +00001682 // The following call drops into the embedded interpreter loop and stays there until the
1683 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001684
Caroline Ticece207c12011-03-11 00:21:55 +00001685 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001686 // 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 +00001687 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1688
1689 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1690 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1691 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1692 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1693 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1694 // hang (it's happened before).
1695
Caroline Tice9d352ce2011-03-07 23:24:28 +00001696 Py_BEGIN_ALLOW_THREADS
1697 PyGILState_STATE gstate = PyGILState_Ensure();
1698
Caroline Tice0aa2e552011-01-14 00:29:16 +00001699 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1700 PyRun_SimpleString (run_string.GetData());
1701 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001702
Caroline Tice9d352ce2011-03-07 23:24:28 +00001703 PyGILState_Release (gstate);
1704 Py_END_ALLOW_THREADS
1705
Caroline Tice0aa2e552011-01-14 00:29:16 +00001706 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1707 PyRun_SimpleString (run_string.GetData());
1708 run_string.Clear();
1709
1710 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1711 PyRun_SimpleString (run_string.GetData());
1712 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001713
1714 script_interpreter->LeaveSession ();
1715
Caroline Tice2ade6112010-11-10 19:18:14 +00001716 }
1717
Caroline Tice202f6b82011-01-17 21:55:19 +00001718 if (!safe_to_run)
1719 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1720 "Python interpreter locked on another thread; unable to acquire lock.\n");
1721
1722 if (need_to_release_lock)
1723 ReleasePythonLock ();
1724
Caroline Tice2ade6112010-11-10 19:18:14 +00001725 if (script_interpreter->m_embedded_thread_input_reader_sp)
1726 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1727
1728 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001729
1730 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001731
1732 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1733 if (log)
1734 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1735
1736
Johnny Chen8054ba32011-03-11 00:28:50 +00001737 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001738 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001739 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1740 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1741 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001742
Caroline Tice2ade6112010-11-10 19:18:14 +00001743 return NULL;
1744}
1745
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001746uint32_t
1747ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1748{
1749 if (!implementor)
1750 return 0;
1751
1752 if (!g_swig_calc_children)
1753 return 0;
1754
1755 ScriptInterpreterPython *python_interpreter = this;
1756
1757 uint32_t ret_val = 0;
1758
1759 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1760 if (CurrentThreadHasPythonLock())
1761 {
1762 python_interpreter->EnterSession ();
1763 ret_val = g_swig_calc_children (implementor);
1764 python_interpreter->LeaveSession ();
1765 }
1766 else
1767 {
1768 while (!GetPythonLock (1))
1769 fprintf (tmp_fh,
1770 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1771 python_interpreter->EnterSession ();
1772 ret_val = g_swig_calc_children (implementor);
1773 python_interpreter->LeaveSession ();
1774 ReleasePythonLock ();
1775 }
1776
1777 return ret_val;
1778}
1779
1780void*
1781ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1782{
1783 if (!implementor)
1784 return 0;
1785
1786 if (!g_swig_get_child_index)
1787 return 0;
1788
1789 ScriptInterpreterPython *python_interpreter = this;
1790
1791 void* ret_val = NULL;
1792
1793 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1794 if (CurrentThreadHasPythonLock())
1795 {
1796 python_interpreter->EnterSession ();
1797 ret_val = g_swig_get_child_index (implementor,idx);
1798 python_interpreter->LeaveSession ();
1799 }
1800 else
1801 {
1802 while (!GetPythonLock (1))
1803 fprintf (tmp_fh,
1804 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1805 python_interpreter->EnterSession ();
1806 ret_val = g_swig_get_child_index (implementor,idx);
1807 python_interpreter->LeaveSession ();
1808 ReleasePythonLock ();
1809 }
1810
1811 return ret_val;
1812}
1813
1814int
1815ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1816{
1817 if (!implementor)
1818 return UINT32_MAX;
1819
1820 if (!g_swig_get_index_child)
1821 return UINT32_MAX;
1822
1823 ScriptInterpreterPython *python_interpreter = this;
1824
1825 int ret_val = UINT32_MAX;
1826
1827 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1828 if (CurrentThreadHasPythonLock())
1829 {
1830 python_interpreter->EnterSession ();
1831 ret_val = g_swig_get_index_child (implementor, child_name);
1832 python_interpreter->LeaveSession ();
1833 }
1834 else
1835 {
1836 while (!GetPythonLock (1))
1837 fprintf (tmp_fh,
1838 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1839 python_interpreter->EnterSession ();
1840 ret_val = g_swig_get_index_child (implementor, child_name);
1841 python_interpreter->LeaveSession ();
1842 ReleasePythonLock ();
1843 }
1844
1845 return ret_val;
1846}
1847
Enrico Granata979e20d2011-07-29 19:53:35 +00001848void
1849ScriptInterpreterPython::UpdateSynthProviderInstance (void* implementor)
1850{
1851 if (!implementor)
1852 return;
1853
1854 if (!g_swig_update_provider)
1855 return;
1856
1857 ScriptInterpreterPython *python_interpreter = this;
1858
1859 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1860 if (CurrentThreadHasPythonLock())
1861 {
1862 python_interpreter->EnterSession ();
1863 g_swig_update_provider (implementor);
1864 python_interpreter->LeaveSession ();
1865 }
1866 else
1867 {
1868 while (!GetPythonLock (1))
1869 fprintf (tmp_fh,
1870 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1871 python_interpreter->EnterSession ();
1872 g_swig_update_provider (implementor);
1873 python_interpreter->LeaveSession ();
1874 ReleasePythonLock ();
1875 }
1876
1877 return;
1878}
1879
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001880lldb::SBValue*
1881ScriptInterpreterPython::CastPyObjectToSBValue (void* data)
1882{
1883 if (!data)
1884 return NULL;
1885
1886 if (!g_swig_cast_to_sbvalue)
1887 return NULL;
1888
1889 ScriptInterpreterPython *python_interpreter = this;
1890
1891 lldb::SBValue* ret_val = NULL;
1892
1893 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1894 if (CurrentThreadHasPythonLock())
1895 {
1896 python_interpreter->EnterSession ();
1897 ret_val = g_swig_cast_to_sbvalue (data);
1898 python_interpreter->LeaveSession ();
1899 }
1900 else
1901 {
1902 while (!GetPythonLock (1))
1903 fprintf (tmp_fh,
1904 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1905 python_interpreter->EnterSession ();
1906 ret_val = g_swig_cast_to_sbvalue (data);
1907 python_interpreter->LeaveSession ();
1908 ReleasePythonLock ();
1909 }
1910
1911 return ret_val;
1912}
1913
Enrico Granatac2a28252011-08-16 16:49:25 +00001914bool
1915ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1916 const char* args,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001917 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001918 Error& error)
1919{
1920 if (!impl_function)
1921 {
1922 error.SetErrorString("no function to execute");
1923 return false;
1924 }
1925
1926 if (!g_swig_call_command)
1927 {
1928 error.SetErrorString("no helper function to run scripted commands");
1929 return false;
1930 }
1931
1932 ScriptInterpreterPython *python_interpreter = this;
1933
1934 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
1935
1936 bool ret_val;
1937
1938 std::string err_msg;
1939
1940 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1941 if (CurrentThreadHasPythonLock())
1942 {
1943 python_interpreter->EnterSession ();
1944 ret_val = g_swig_call_command (impl_function,
1945 python_interpreter->m_dictionary_name.c_str(),
1946 debugger_sp,
1947 args,
1948 err_msg,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001949 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001950 python_interpreter->LeaveSession ();
1951 }
1952 else
1953 {
1954 while (!GetPythonLock (1))
1955 fprintf (tmp_fh,
1956 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1957 python_interpreter->EnterSession ();
1958 ret_val = g_swig_call_command (impl_function,
1959 python_interpreter->m_dictionary_name.c_str(),
1960 debugger_sp,
1961 args,
1962 err_msg,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001963 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001964 python_interpreter->LeaveSession ();
1965 ReleasePythonLock ();
1966 }
1967
1968 if (!ret_val)
1969 error.SetErrorString(err_msg.c_str());
1970 else
1971 error.Clear();
1972
1973 return ret_val;
1974
1975
1976 return true;
1977
1978}
1979
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001980// in Python, a special attribute __doc__ contains the docstring
1981// for an object (function, method, class, ...) if any is defined
1982// Otherwise, the attribute's value is None
1983std::string
1984ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1985{
1986 std::string command(item);
1987 command += ".__doc__";
1988
1989 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1990
1991 if (ExecuteOneLineWithReturn (command.c_str(),
1992 ScriptInterpreter::eCharStrOrNone,
1993 &result_ptr) && result_ptr)
1994 {
1995 return std::string(result_ptr);
1996 }
1997 else
1998 return std::string("");
1999}
Caroline Tice2ade6112010-11-10 19:18:14 +00002000
Caroline Tice0aa2e552011-01-14 00:29:16 +00002001void
Greg Claytone86cbb92011-03-22 01:14:58 +00002002ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00002003 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002004 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
2005 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
2006 SWIGPythonCalculateNumChildren python_swig_calc_children,
2007 SWIGPythonGetChildAtIndex python_swig_get_child_index,
2008 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
Enrico Granata979e20d2011-07-29 19:53:35 +00002009 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue,
Enrico Granatac2a28252011-08-16 16:49:25 +00002010 SWIGPythonUpdateSynthProviderInstance python_swig_update_provider,
2011 SWIGPythonCallCommand python_swig_call_command)
Greg Claytone86cbb92011-03-22 01:14:58 +00002012{
2013 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00002014 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
2015 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002016 g_swig_synthetic_script = python_swig_synthetic_script;
2017 g_swig_calc_children = python_swig_calc_children;
2018 g_swig_get_child_index = python_swig_get_child_index;
2019 g_swig_get_index_child = python_swig_get_index_child;
2020 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Enrico Granata979e20d2011-07-29 19:53:35 +00002021 g_swig_update_provider = python_swig_update_provider;
Enrico Granatac2a28252011-08-16 16:49:25 +00002022 g_swig_call_command = python_swig_call_command;
Greg Claytone86cbb92011-03-22 01:14:58 +00002023}
2024
2025void
2026ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00002027{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002028 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
2029
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002030 // Python will muck with STDIN terminal state, so save off any current TTY
2031 // settings so we can restore them.
2032 TerminalState stdin_tty_state;
2033 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002034
2035 // Find the module that owns this code and use that path we get to
2036 // set the PYTHONPATH appropriately.
2037
2038 FileSpec file_spec;
2039 char python_dir_path[PATH_MAX];
2040 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
2041 {
2042 std::string python_path;
2043 const char *curr_python_path = ::getenv ("PYTHONPATH");
2044 if (curr_python_path)
2045 {
2046 // We have a current value for PYTHONPATH, so lets append to it
2047 python_path.append (curr_python_path);
2048 }
2049
2050 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2051 {
2052 if (!python_path.empty())
2053 python_path.append (1, ':');
2054 python_path.append (python_dir_path);
2055 }
2056
2057 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
2058 {
2059 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2060 {
2061 if (!python_path.empty())
2062 python_path.append (1, ':');
2063 python_path.append (python_dir_path);
2064 }
2065 }
2066 const char *pathon_path_env_cstr = python_path.c_str();
2067 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
2068 }
2069
Caroline Tice9d352ce2011-03-07 23:24:28 +00002070 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00002071 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002072
Greg Claytone86cbb92011-03-22 01:14:58 +00002073 // Initialize SWIG after setting up python
2074 assert (g_swig_init_callback != NULL);
2075 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002076
2077 // Update the path python uses to search for modules to include the current directory.
2078
Caroline Ticed4d92832011-06-13 21:33:00 +00002079 PyRun_SimpleString ("import sys");
2080 PyRun_SimpleString ("sys.path.append ('.')");
Caroline Tice0aa2e552011-01-14 00:29:16 +00002081
Caroline Ticed4d92832011-06-13 21:33:00 +00002082 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00002083
Caroline Ticed4d92832011-06-13 21:33:00 +00002084 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
2085 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
2086 PyRun_SimpleString ("import sys");
2087 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00002088
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002089 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002090}
2091
Greg Claytone86cbb92011-03-22 01:14:58 +00002092//void
2093//ScriptInterpreterPython::Terminate ()
2094//{
2095// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
2096// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
2097// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
2098// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
2099// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
2100// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
2101// // within Py_Finalize, which results in a seg fault.
2102// //
2103// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
2104// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
2105// // process exits).
2106// //
2107//// Py_Finalize ();
2108//}