blob: e7c68e74da9cf98c20865bf5aa31fa971d0ff247 [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;
Chris Lattner24943d22010-06-08 16:52:24 +000044
45static int
46_check_and_flush (FILE *stream)
47{
48 int prev_fail = ferror (stream);
49 return fflush (stream) || prev_fail ? EOF : 0;
50}
51
Caroline Tice202f6b82011-01-17 21:55:19 +000052static Predicate<lldb::tid_t> &
53PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +000054{
Caroline Tice202f6b82011-01-17 21:55:19 +000055 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
56 return g_interpreter_is_running;
57}
58
59static bool
60CurrentThreadHasPythonLock ()
61{
62 TimeValue timeout;
63
64 timeout = TimeValue::Now(); // Don't wait any time.
65
66 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
67}
68
69static bool
70GetPythonLock (uint32_t seconds_to_wait)
71{
72
73 TimeValue timeout;
74
75 if (seconds_to_wait != UINT32_MAX)
76 {
77 timeout = TimeValue::Now();
78 timeout.OffsetWithSeconds (seconds_to_wait);
79 }
80
81 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
82 Host::GetCurrentThreadID(), &timeout, NULL);
83}
84
85static void
86ReleasePythonLock ()
87{
88 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +000089}
90
Greg Clayton63094e02010-06-23 01:19:29 +000091ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +000092 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +000093 m_embedded_python_pty (),
94 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +000095 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +000096 m_new_sysout (NULL),
97 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +000098 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +000099 m_session_is_active (false),
100 m_pty_slave_is_open (false),
101 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000102{
103
Greg Clayton7c330d62011-01-27 01:01:10 +0000104 static int g_initialized = false;
105
106 if (!g_initialized)
107 {
108 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000109 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000110 }
111
Caroline Tice202f6b82011-01-17 21:55:19 +0000112 bool safe_to_run = false;
113 bool need_to_release_lock = true;
114 int interval = 5; // Number of seconds to try getting the Python lock before timing out.
115
116 // We don't dare exit this function without finishing setting up the script interpreter, so we must wait until
117 // we can get the Python lock.
118
119 if (CurrentThreadHasPythonLock())
120 {
121 safe_to_run = true;
122 need_to_release_lock = false;
123 }
124
125 while (!safe_to_run)
126 {
127 safe_to_run = GetPythonLock (interval);
128 if (!safe_to_run)
129 {
130 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
131 fprintf (tmp_fh,
132 "Python interpreter is locked on another thread; "
133 "please release interpreter in order to continue.\n");
134 interval = interval * 2;
135 }
136 }
137
Caroline Tice0aa2e552011-01-14 00:29:16 +0000138 m_dictionary_name.append("_dict");
139 StreamString run_string;
140 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
141 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000142
Caroline Tice0aa2e552011-01-14 00:29:16 +0000143 run_string.Clear();
144 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
145 PyRun_SimpleString (run_string.GetData());
146
147 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
148 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
149 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
150 // call to Debugger::Terminate is made, the ref-count has the correct value.
151 //
152 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
153 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000154
Caroline Tice0aa2e552011-01-14 00:29:16 +0000155 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000156
Caroline Tice0aa2e552011-01-14 00:29:16 +0000157 run_string.Clear();
158 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
159 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000160
Caroline Tice0aa2e552011-01-14 00:29:16 +0000161 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000162
Caroline Tice0aa2e552011-01-14 00:29:16 +0000163 if (new_count > old_count)
164 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000165
Caroline Tice0aa2e552011-01-14 00:29:16 +0000166 run_string.Clear();
167 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
168 PyRun_SimpleString (run_string.GetData());
169
170 run_string.Clear();
171 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
172 interpreter.GetDebugger().GetID());
173 PyRun_SimpleString (run_string.GetData());
174
175 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000176 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000177 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000178 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000179
180 if (need_to_release_lock)
181 ReleasePythonLock();
Chris Lattner24943d22010-06-08 16:52:24 +0000182}
183
184ScriptInterpreterPython::~ScriptInterpreterPython ()
185{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000186 Debugger &debugger = GetCommandInterpreter().GetDebugger();
187
188 if (m_embedded_thread_input_reader_sp.get() != NULL)
189 {
190 m_embedded_thread_input_reader_sp->SetIsDone (true);
191 m_embedded_python_pty.CloseSlaveFileDescriptor();
192 m_pty_slave_is_open = false;
193 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
194 m_embedded_thread_input_reader_sp.reset();
195 debugger.PopInputReader (reader_sp);
196 }
197
198 if (m_new_sysout)
199 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000200 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
201 if (!CurrentThreadHasPythonLock ())
202 {
203 while (!GetPythonLock (1))
204 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
205 Py_DECREF (m_new_sysout);
206 ReleasePythonLock ();
207 }
208 else
209 Py_DECREF (m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000210 }
Chris Lattner24943d22010-06-08 16:52:24 +0000211}
212
Caroline Tice0aa2e552011-01-14 00:29:16 +0000213void
214ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
215{
216 if (fh == NULL)
217 return;
218
219 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000220
Caroline Tice202f6b82011-01-17 21:55:19 +0000221 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
222 if (!CurrentThreadHasPythonLock ())
223 {
224 while (!GetPythonLock (1))
225 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
226 EnterSession ();
227 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
228 LeaveSession ();
229 ReleasePythonLock ();
230 }
231 else
232 {
233 EnterSession ();
234 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
235 LeaveSession ();
236 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000237}
238
239void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000240ScriptInterpreterPython::SaveTerminalState (int fd)
241{
242 // Python mucks with the terminal state of STDIN. If we can possibly avoid
243 // this by setting the file handles up correctly prior to entering the
244 // interpreter we should. For now we save and restore the terminal state
245 // on the input file handle.
246 m_terminal_state.Save (fd, false);
247}
248
249void
250ScriptInterpreterPython::RestoreTerminalState ()
251{
252 // Python mucks with the terminal state of STDIN. If we can possibly avoid
253 // this by setting the file handles up correctly prior to entering the
254 // interpreter we should. For now we save and restore the terminal state
255 // on the input file handle.
256 m_terminal_state.Restore();
257}
258
259
260
261void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000262ScriptInterpreterPython::LeaveSession ()
263{
264 m_session_is_active = false;
265}
266
267void
268ScriptInterpreterPython::EnterSession ()
269{
270 // If we have already entered the session, without having officially 'left' it, then there is no need to
271 // 'enter' it again.
272
273 if (m_session_is_active)
274 return;
275
276 m_session_is_active = true;
277
Caroline Tice202f6b82011-01-17 21:55:19 +0000278 StreamString run_string;
279
280 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
281 GetCommandInterpreter().GetDebugger().GetID());
282 PyRun_SimpleString (run_string.GetData());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000283 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +0000284
Caroline Tice0aa2e552011-01-14 00:29:16 +0000285
Caroline Tice6af65cb2011-05-03 21:21:50 +0000286 run_string.Printf ("run_one_line (%s, 'lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%d)')",
287 m_dictionary_name.c_str(),
288 GetCommandInterpreter().GetDebugger().GetID());
289 PyRun_SimpleString (run_string.GetData());
290 run_string.Clear();
291
292
293 ExecutionContext exe_ctx = m_interpreter.GetDebugger().GetSelectedExecutionContext();
294
295 if (exe_ctx.target)
296 run_string.Printf ("run_one_line (%s, 'lldb.target = lldb.debugger.GetSelectedTarget()')",
297 m_dictionary_name.c_str());
298 else
299 run_string.Printf ("run_one_line (%s, 'lldb.target = None')", m_dictionary_name.c_str());
300 PyRun_SimpleString (run_string.GetData());
301 run_string.Clear();
302
303 if (exe_ctx.process)
304 run_string.Printf ("run_one_line (%s, 'lldb.process = lldb.target.GetProcess()')", m_dictionary_name.c_str());
305 else
306 run_string.Printf ("run_one_line (%s, 'lldb.process = None')", m_dictionary_name.c_str());
307 PyRun_SimpleString (run_string.GetData());
308 run_string.Clear();
309
310 if (exe_ctx.thread)
311 run_string.Printf ("run_one_line (%s, 'lldb.thread = lldb.process.GetSelectedThread ()')",
312 m_dictionary_name.c_str());
313 else
314 run_string.Printf ("run_one_line (%s, 'lldb.thread = None')", m_dictionary_name.c_str());
315 PyRun_SimpleString (run_string.GetData());
316 run_string.Clear();
317
318 if (exe_ctx.frame)
319 run_string.Printf ("run_one_line (%s, 'lldb.frame = lldb.thread.GetSelectedFrame ()')",
320 m_dictionary_name.c_str());
321 else
322 run_string.Printf ("run_one_line (%s, 'lldb.frame = None')", m_dictionary_name.c_str());
323 PyRun_SimpleString (run_string.GetData());
324 run_string.Clear();
325
Caroline Tice0aa2e552011-01-14 00:29:16 +0000326 PyObject *sysmod = PyImport_AddModule ("sys");
327 PyObject *sysdict = PyModule_GetDict (sysmod);
328
329 if ((m_new_sysout != NULL)
330 && (sysmod != NULL)
331 && (sysdict != NULL))
332 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
333
334 if (PyErr_Occurred())
335 PyErr_Clear ();
336
Caroline Tice0aa2e552011-01-14 00:29:16 +0000337 if (!m_pty_slave_is_open)
338 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000339 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000340 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
341 m_pty_slave_name.c_str());
342 PyRun_SimpleString (run_string.GetData());
343 m_pty_slave_is_open = true;
344
345 run_string.Clear();
346 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
347 PyRun_SimpleString (run_string.GetData());
348 }
349}
350
351
Johnny Chen60dde642010-07-30 22:33:14 +0000352bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000353ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000354{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000355 if (!m_valid_session)
356 return false;
357
Caroline Tice0aa2e552011-01-14 00:29:16 +0000358
Caroline Tice0aa2e552011-01-14 00:29:16 +0000359
Caroline Tice4a461da2011-01-14 21:09:29 +0000360 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
361 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
362 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
363 // method to pass the command string directly down to Python.
364
365
Caroline Tice202f6b82011-01-17 21:55:19 +0000366 bool need_to_release_lock = true;
367
368 if (CurrentThreadHasPythonLock())
369 need_to_release_lock = false;
370 else if (!GetPythonLock (1))
371 {
372 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
373 "Python interpreter is currently locked by another thread; unable to process command.\n");
374 return false;
375 }
376
377 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000378 bool success = false;
379
Greg Clayton63094e02010-06-23 01:19:29 +0000380 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000381 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000382 // Find the correct script interpreter dictionary in the main module.
383 PyObject *main_mod = PyImport_AddModule ("__main__");
384 PyObject *script_interpreter_dict = NULL;
385 if (main_mod != NULL)
386 {
387 PyObject *main_dict = PyModule_GetDict (main_mod);
388 if ((main_dict != NULL)
389 && PyDict_Check (main_dict))
390 {
391 // Go through the main dictionary looking for the correct python script interpreter dictionary
392 PyObject *key, *value;
393 Py_ssize_t pos = 0;
394
395 while (PyDict_Next (main_dict, &pos, &key, &value))
396 {
397 // We have stolen references to the key and value objects in the dictionary; we need to increment
398 // them now so that Python's garbage collector doesn't collect them out from under us.
399 Py_INCREF (key);
400 Py_INCREF (value);
401 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
402 {
403 script_interpreter_dict = value;
404 break;
405 }
406 }
407 }
408
409 if (script_interpreter_dict != NULL)
410 {
411 PyObject *pfunc = NULL;
412 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
413 if (pmod != NULL)
414 {
415 PyObject *pmod_dict = PyModule_GetDict (pmod);
416 if ((pmod_dict != NULL)
417 && PyDict_Check (pmod_dict))
418 {
419 PyObject *key, *value;
420 Py_ssize_t pos = 0;
421
422 while (PyDict_Next (pmod_dict, &pos, &key, &value))
423 {
424 Py_INCREF (key);
425 Py_INCREF (value);
426 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
427 {
428 pfunc = value;
429 break;
430 }
431 }
432
433 PyObject *string_arg = PyString_FromString (command);
434 if (pfunc && string_arg && PyCallable_Check (pfunc))
435 {
436 PyObject *pargs = PyTuple_New (2);
437 if (pargs != NULL)
438 {
439 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
440 PyTuple_SetItem (pargs, 1, string_arg);
441 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
442 Py_DECREF (pargs);
443 if (pvalue != NULL)
444 {
445 Py_DECREF (pvalue);
446 success = true;
447 }
448 else if (PyErr_Occurred ())
449 {
450 PyErr_Print();
451 PyErr_Clear();
452 }
453 }
454 }
455 }
456 }
457 Py_INCREF (script_interpreter_dict);
458 }
459 }
Greg Clayton63094e02010-06-23 01:19:29 +0000460
Caroline Tice0aa2e552011-01-14 00:29:16 +0000461 LeaveSession ();
462
Caroline Tice202f6b82011-01-17 21:55:19 +0000463 if (need_to_release_lock)
464 ReleasePythonLock();
465
Caroline Tice4a461da2011-01-14 21:09:29 +0000466 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000467 return true;
468
469 // The one-liner failed. Append the error message.
470 if (result)
471 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
472 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000473 }
Johnny Chen60dde642010-07-30 22:33:14 +0000474
Caroline Tice0aa2e552011-01-14 00:29:16 +0000475 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000476
477 if (need_to_release_lock)
478 ReleasePythonLock ();
479
Johnny Chen60dde642010-07-30 22:33:14 +0000480 if (result)
481 result->AppendError ("empty command passed to python\n");
482 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000483}
484
485
486
487size_t
488ScriptInterpreterPython::InputReaderCallback
489(
490 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000491 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000492 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000493 const char *bytes,
494 size_t bytes_len
495)
496{
Caroline Tice2ade6112010-11-10 19:18:14 +0000497 lldb::thread_t embedded_interpreter_thread;
498 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
499
Chris Lattner24943d22010-06-08 16:52:24 +0000500 if (baton == NULL)
501 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000502
503 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
504
505 if (script_interpreter->m_script_lang != eScriptLanguagePython)
506 return 0;
507
Caroline Tice892fadd2011-06-16 16:27:19 +0000508 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
509 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
510
Chris Lattner24943d22010-06-08 16:52:24 +0000511 switch (notification)
512 {
513 case eInputReaderActivate:
514 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000515 if (!batch_mode)
516 {
517 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
518 out_stream->Flush();
519 }
Greg Clayton58928562011-02-09 01:08:52 +0000520
Chris Lattner24943d22010-06-08 16:52:24 +0000521 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000522 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
523 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000524 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000525
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000526 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000527
Caroline Tice202f6b82011-01-17 21:55:19 +0000528 if (!CurrentThreadHasPythonLock())
529 {
530 while (!GetPythonLock(1))
531 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000532 out_stream->Printf ("Python interpreter locked on another thread; waiting to acquire lock...\n");
533 out_stream->Flush();
Caroline Tice202f6b82011-01-17 21:55:19 +0000534 }
535 script_interpreter->EnterSession ();
536 ReleasePythonLock();
537 }
538 else
539 script_interpreter->EnterSession ();
540
Caroline Tice2ade6112010-11-10 19:18:14 +0000541 char error_str[1024];
542 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
543 sizeof(error_str)))
544 {
545 if (log)
546 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
547 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
548 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
549 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
550 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000551 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000552 {
553 if (log)
554 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
555 Error detach_error;
556 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
557 }
558 else
559 {
560 if (log)
561 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
562 reader.SetIsDone (true);
563 }
564 }
565 else
566 {
567 if (log)
568 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
569 reader.SetIsDone (true);
570 }
Chris Lattner24943d22010-06-08 16:52:24 +0000571 }
572 break;
573
574 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000575 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000576 break;
577
578 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000579 if (!CurrentThreadHasPythonLock())
580 {
581 while (!GetPythonLock(1))
582 {
583 // Wait until lock is acquired.
584 }
585 script_interpreter->EnterSession ();
586 ReleasePythonLock();
587 }
588 else
589 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000590 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000591
Caroline Tice4a348082011-05-02 20:41:46 +0000592 case eInputReaderAsynchronousOutputWritten:
593 break;
594
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000595 case eInputReaderInterrupt:
596 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
597 break;
598
599 case eInputReaderEndOfFile:
600 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
601 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000602
603 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000604 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000605 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000606 if (log)
607 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
608 bytes_len);
609 if (bytes && bytes_len)
610 {
611 if ((int) bytes[0] == 4)
612 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
613 else
614 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
615 }
616 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000617 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000618 else
619 {
620 if (log)
621 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
622 bytes,
623 bytes_len);
624 reader.SetIsDone (true);
625 }
626
Chris Lattner24943d22010-06-08 16:52:24 +0000627 break;
628
629 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000630 script_interpreter->LeaveSession ();
631
Chris Lattner24943d22010-06-08 16:52:24 +0000632 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000633 if (log)
634 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000635
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000636 script_interpreter->RestoreTerminalState ();
637
Caroline Tice2ade6112010-11-10 19:18:14 +0000638 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000639 break;
640 }
641
642 return bytes_len;
643}
644
645
646void
Greg Clayton238c0a12010-09-18 01:14:36 +0000647ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000648{
649 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
650
Caroline Tice0aa2e552011-01-14 00:29:16 +0000651 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000652
653 // At the moment, the only time the debugger does not have an input file handle is when this is called
654 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
655 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
656 // do it.
657
Greg Clayton58928562011-02-09 01:08:52 +0000658 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000659 return;
660
Greg Clayton63094e02010-06-23 01:19:29 +0000661 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000662 if (reader_sp)
663 {
664 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
665 this, // baton
666 eInputReaderGranularityLine, // token size, to pass to callback function
667 NULL, // end token
668 NULL, // prompt
669 true)); // echo input
670
671 if (error.Success())
672 {
Greg Clayton63094e02010-06-23 01:19:29 +0000673 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000674 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000675 }
676 }
677}
678
679bool
680ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
681 ScriptInterpreter::ReturnType return_type,
682 void *ret_value)
683{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000684
Caroline Tice202f6b82011-01-17 21:55:19 +0000685 bool need_to_release_lock = true;
686
687 if (CurrentThreadHasPythonLock())
688 need_to_release_lock = false;
689 else if (!GetPythonLock (1))
690 {
691 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
692 "Python interpreter is currently locked by another thread; unable to process command.\n");
693 return false;
694 }
695
696 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000697
Chris Lattner24943d22010-06-08 16:52:24 +0000698 PyObject *py_return = NULL;
699 PyObject *mainmod = PyImport_AddModule ("__main__");
700 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000701 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000702 PyObject *py_error = NULL;
703 bool ret_success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000704 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000705 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000706
707 if (PyDict_Check (globals))
708 {
709 PyObject *key, *value;
710 Py_ssize_t pos = 0;
711
712 int i = 0;
713 while (PyDict_Next (globals, &pos, &key, &value))
714 {
715 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
716 // so that Python's garbage collector doesn't collect them out from under us.
717 Py_INCREF (key);
718 Py_INCREF (value);
719 char *c_str = PyString_AsString (key);
720 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
721 locals = value;
722 ++i;
723 }
724 }
Chris Lattner24943d22010-06-08 16:52:24 +0000725
Caroline Tice0aa2e552011-01-14 00:29:16 +0000726 if (locals == NULL)
727 {
728 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
729 should_decrement_locals = true;
730 }
731
732 if (locals == NULL)
733 {
734 locals = globals;
735 should_decrement_locals = false;
736 }
737
738 py_error = PyErr_Occurred();
739 if (py_error != NULL)
740 PyErr_Clear();
741
Chris Lattner24943d22010-06-08 16:52:24 +0000742 if (in_string != NULL)
743 {
744 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
745 if (py_return == NULL)
746 {
747 py_error = PyErr_Occurred ();
748 if (py_error != NULL)
749 PyErr_Clear ();
750
751 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
752 }
753
Caroline Tice0aa2e552011-01-14 00:29:16 +0000754 if (locals != NULL
755 && should_decrement_locals)
756 Py_DECREF (locals);
757
Chris Lattner24943d22010-06-08 16:52:24 +0000758 if (py_return != NULL)
759 {
760 switch (return_type)
761 {
762 case eCharPtr: // "char *"
763 {
764 const char format[3] = "s#";
765 success = PyArg_Parse (py_return, format, (char **) &ret_value);
766 break;
767 }
768 case eBool:
769 {
770 const char format[2] = "b";
771 success = PyArg_Parse (py_return, format, (bool *) ret_value);
772 break;
773 }
774 case eShortInt:
775 {
776 const char format[2] = "h";
777 success = PyArg_Parse (py_return, format, (short *) ret_value);
778 break;
779 }
780 case eShortIntUnsigned:
781 {
782 const char format[2] = "H";
783 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
784 break;
785 }
786 case eInt:
787 {
788 const char format[2] = "i";
789 success = PyArg_Parse (py_return, format, (int *) ret_value);
790 break;
791 }
792 case eIntUnsigned:
793 {
794 const char format[2] = "I";
795 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
796 break;
797 }
798 case eLongInt:
799 {
800 const char format[2] = "l";
801 success = PyArg_Parse (py_return, format, (long *) ret_value);
802 break;
803 }
804 case eLongIntUnsigned:
805 {
806 const char format[2] = "k";
807 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
808 break;
809 }
810 case eLongLong:
811 {
812 const char format[2] = "L";
813 success = PyArg_Parse (py_return, format, (long long *) ret_value);
814 break;
815 }
816 case eLongLongUnsigned:
817 {
818 const char format[2] = "K";
819 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
820 break;
821 }
822 case eFloat:
823 {
824 const char format[2] = "f";
825 success = PyArg_Parse (py_return, format, (float *) ret_value);
826 break;
827 }
828 case eDouble:
829 {
830 const char format[2] = "d";
831 success = PyArg_Parse (py_return, format, (double *) ret_value);
832 break;
833 }
834 case eChar:
835 {
836 const char format[2] = "c";
837 success = PyArg_Parse (py_return, format, (char *) ret_value);
838 break;
839 }
840 default:
841 {}
842 }
843 Py_DECREF (py_return);
844 if (success)
845 ret_success = true;
846 else
847 ret_success = false;
848 }
849 }
850
851 py_error = PyErr_Occurred();
852 if (py_error != NULL)
853 {
854 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
855 PyErr_Print ();
856 PyErr_Clear();
857 ret_success = false;
858 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000859
860 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000861
Caroline Tice202f6b82011-01-17 21:55:19 +0000862 if (need_to_release_lock)
863 ReleasePythonLock();
864
Chris Lattner24943d22010-06-08 16:52:24 +0000865 return ret_success;
866}
867
868bool
869ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
870{
Caroline Tice202f6b82011-01-17 21:55:19 +0000871 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
872 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000873
Caroline Tice202f6b82011-01-17 21:55:19 +0000874 if (CurrentThreadHasPythonLock())
875 need_to_release_lock = false;
876 else
877 {
878 while (!GetPythonLock (1))
879 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
880 }
881
882 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000883
Chris Lattner24943d22010-06-08 16:52:24 +0000884 bool success = false;
885 PyObject *py_return = NULL;
886 PyObject *mainmod = PyImport_AddModule ("__main__");
887 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000888 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000889 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000890 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000891
Caroline Tice0aa2e552011-01-14 00:29:16 +0000892 if (PyDict_Check (globals))
893 {
894 PyObject *key, *value;
895 Py_ssize_t pos = 0;
896
897 while (PyDict_Next (globals, &pos, &key, &value))
898 {
899 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
900 // so that Python's garbage collector doesn't collect them out from under us.
901 Py_INCREF (key);
902 Py_INCREF (value);
903 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
904 locals = value;
905 }
906 }
907
908 if (locals == NULL)
909 {
910 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
911 should_decrement_locals = true;
912 }
913
914 if (locals == NULL)
915 {
916 locals = globals;
917 should_decrement_locals = false;
918 }
919
920 py_error = PyErr_Occurred();
921 if (py_error != NULL)
922 PyErr_Clear();
923
Chris Lattner24943d22010-06-08 16:52:24 +0000924 if (in_string != NULL)
925 {
926 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
927 if (compiled_node)
928 {
929 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
930 if (compiled_code)
931 {
932 py_return = PyEval_EvalCode (compiled_code, globals, locals);
933 if (py_return != NULL)
934 {
935 success = true;
936 Py_DECREF (py_return);
937 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000938 if (locals && should_decrement_locals)
939 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000940 }
941 }
942 }
943
944 py_error = PyErr_Occurred ();
945 if (py_error != NULL)
946 {
947 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
948 PyErr_Print ();
949 PyErr_Clear();
950 success = false;
951 }
952
Caroline Tice0aa2e552011-01-14 00:29:16 +0000953 LeaveSession ();
954
Caroline Tice202f6b82011-01-17 21:55:19 +0000955 if (need_to_release_lock)
956 ReleasePythonLock();
957
Chris Lattner24943d22010-06-08 16:52:24 +0000958 return success;
959}
960
961static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
962
963size_t
964ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
965(
966 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000967 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000968 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000969 const char *bytes,
970 size_t bytes_len
971)
972{
Caroline Tice892fadd2011-06-16 16:27:19 +0000973 static StringList commands_in_progress;
974
975 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
976 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
977
Chris Lattner24943d22010-06-08 16:52:24 +0000978 switch (notification)
979 {
980 case eInputReaderActivate:
981 {
982 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +0000983 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +0000984 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000985 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000986 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +0000987 out_stream->Printf ("%s", reader.GetPrompt());
988 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +0000989 }
990 }
991 break;
992
993 case eInputReaderDeactivate:
994 break;
995
996 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +0000997 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000998 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000999 out_stream->Printf ("%s", reader.GetPrompt());
1000 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001001 }
Chris Lattner24943d22010-06-08 16:52:24 +00001002 break;
1003
Caroline Tice4a348082011-05-02 20:41:46 +00001004 case eInputReaderAsynchronousOutputWritten:
1005 break;
1006
Chris Lattner24943d22010-06-08 16:52:24 +00001007 case eInputReaderGotToken:
1008 {
1009 std::string temp_string (bytes, bytes_len);
1010 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001011 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001012 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001013 out_stream->Printf ("%s", reader.GetPrompt());
1014 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001015 }
Chris Lattner24943d22010-06-08 16:52:24 +00001016 }
1017 break;
1018
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001019 case eInputReaderEndOfFile:
1020 case eInputReaderInterrupt:
1021 // Control-c (SIGINT) & control-d both mean finish & exit.
1022 reader.SetIsDone(true);
1023
1024 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1025 if (notification == eInputReaderInterrupt)
1026 commands_in_progress.Clear();
1027
1028 // Fall through here...
1029
Chris Lattner24943d22010-06-08 16:52:24 +00001030 case eInputReaderDone:
1031 {
1032 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1033 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1034 data_ap->user_source.AppendList (commands_in_progress);
1035 if (data_ap.get())
1036 {
Greg Clayton63094e02010-06-23 01:19:29 +00001037 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001038 if (interpreter)
1039 {
1040 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1041 data_ap->script_source))
1042 {
1043 if (data_ap->script_source.GetSize() == 1)
1044 {
1045 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1046 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1047 }
1048 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001049 else if (!batch_mode)
1050 {
1051 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1052 out_stream->Flush();
1053 }
Chris Lattner24943d22010-06-08 16:52:24 +00001054 }
1055 else
1056 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001057 if (!batch_mode)
1058 {
1059 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1060 out_stream->Flush();
1061 }
Chris Lattner24943d22010-06-08 16:52:24 +00001062 }
1063 }
1064 }
1065 break;
1066
1067 }
1068
1069 return bytes_len;
1070}
1071
1072void
Greg Clayton238c0a12010-09-18 01:14:36 +00001073ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001074 CommandReturnObject &result)
1075{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001076 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1077
Greg Clayton63094e02010-06-23 01:19:29 +00001078 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001079
1080 if (reader_sp)
1081 {
1082 Error err = reader_sp->Initialize (
1083 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1084 bp_options, // baton
1085 eInputReaderGranularityLine, // token size, for feeding data to callback function
1086 "DONE", // end token
1087 "> ", // prompt
1088 true); // echo input
1089
1090 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001091 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001092 else
1093 {
1094 result.AppendError (err.AsCString());
1095 result.SetStatus (eReturnStatusFailed);
1096 }
1097 }
1098 else
1099 {
1100 result.AppendError("out of memory");
1101 result.SetStatus (eReturnStatusFailed);
1102 }
1103}
1104
Johnny Chen3e0571b2010-09-11 00:23:59 +00001105// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001106void
Greg Clayton238c0a12010-09-18 01:14:36 +00001107ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001108 const char *oneliner)
1109{
1110 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1111
1112 // It's necessary to set both user_source and script_source to the oneliner.
1113 // The former is used to generate callback description (as in breakpoint command list)
1114 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001115
Johnny Chend1c2dca2010-09-10 18:21:10 +00001116 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001117
Caroline Tice5136f942010-09-27 21:35:15 +00001118 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1119 {
1120 if (data_ap->script_source.GetSize() == 1)
1121 {
1122 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1123 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1124 }
1125 }
1126
Johnny Chend1c2dca2010-09-10 18:21:10 +00001127 return;
1128}
1129
Chris Lattner24943d22010-06-08 16:52:24 +00001130bool
1131ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1132{
1133 // Convert StringList to one long, newline delimited, const char *.
1134 std::string function_def_string;
1135
1136 int num_lines = function_def.GetSize();
1137
1138 for (int i = 0; i < num_lines; ++i)
1139 {
1140 function_def_string.append (function_def.GetStringAtIndex(i));
1141 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1142 function_def_string.append ("\n");
1143
1144 }
1145
1146 return ExecuteMultipleLines (function_def_string.c_str());
1147}
1148
Enrico Granataf7a9b142011-07-15 02:26:42 +00001149// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1150// use this code to generate their functions
1151bool
1152ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1153{
1154 int num_lines = input.GetSize ();
1155 if (num_lines == 0)
1156 return false;
1157 StreamString sstr;
1158 StringList auto_generated_function;
1159 auto_generated_function.AppendString (signature.c_str());
1160 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1161 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1162 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1163 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1164 // global dictionary.
1165
1166 // Wrap everything up inside the function, increasing the indentation.
1167
1168 for (int i = 0; i < num_lines; ++i)
1169 {
1170 sstr.Clear ();
1171 sstr.Printf (" %s", input.GetStringAtIndex (i));
1172 auto_generated_function.AppendString (sstr.GetData());
1173 }
1174 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1175 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1176 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1177 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1178
1179 // Verify that the results are valid Python.
1180
1181 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1182 return false;
1183
1184 return true;
1185
1186}
1187
1188// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1189// given to generated functions, of course)
1190bool
1191ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output)
1192{
1193 static int num_created_functions = 0;
1194 user_input.RemoveBlankLines ();
1195 int num_lines = user_input.GetSize ();
1196 StreamString sstr;
1197
1198 // Check to see if we have any data; if not, just return.
1199 if (user_input.GetSize() == 0)
1200 return false;
1201
1202 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1203 // ValueObject as parameter to the function.
1204
1205 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1206 ++num_created_functions;
1207 std::string auto_generated_function_name = sstr.GetData();
1208
1209 sstr.Clear();
1210 StringList auto_generated_function;
1211
1212 // Create the function name & definition string.
1213
1214 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1215 auto_generated_function.AppendString (sstr.GetData());
1216
1217 // Pre-pend code for setting up the session dictionary.
1218
1219 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1220 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1221 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1222 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1223 // global dictionary.
1224
1225 // Wrap everything up inside the function, increasing the indentation.
1226
1227 for (int i = 0; i < num_lines; ++i)
1228 {
1229 sstr.Clear ();
1230 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1231 auto_generated_function.AppendString (sstr.GetData());
1232 }
1233
1234 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1235 // got written to the values in the global dictionary, not the session dictionary).
1236
1237 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1238 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1239 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1240 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1241
1242 // Verify that the results are valid Python.
1243
1244 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1245 return false;
1246
1247 // Store the name of the auto-generated function to be called.
1248
1249 output.AppendString (auto_generated_function_name.c_str());
1250 return true;
1251}
1252
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001253bool
1254ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output)
1255{
1256 static int num_created_classes = 0;
1257 user_input.RemoveBlankLines ();
1258 int num_lines = user_input.GetSize ();
1259 StreamString sstr;
1260
1261 // Check to see if we have any data; if not, just return.
1262 if (user_input.GetSize() == 0)
1263 return false;
1264
1265 // Wrap all user input into a Python class
1266
1267 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1268 ++num_created_classes;
1269 std::string auto_generated_class_name = sstr.GetData();
1270
1271 sstr.Clear();
1272 StringList auto_generated_class;
1273
1274 // Create the function name & definition string.
1275
1276 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1277 auto_generated_class.AppendString (sstr.GetData());
1278
1279 // Wrap everything up inside the class, increasing the indentation.
1280
1281 for (int i = 0; i < num_lines; ++i)
1282 {
1283 sstr.Clear ();
1284 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1285 auto_generated_class.AppendString (sstr.GetData());
1286 }
1287
1288
1289 // Verify that the results are valid Python.
1290 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1291 // (TODO: rename that method to ExportDefinitionToInterpreter)
1292 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1293 return false;
1294
1295 // Store the name of the auto-generated class
1296
1297 output.AppendString (auto_generated_class_name.c_str());
1298 return true;
1299}
1300
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001301void*
1302ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1303 lldb::ValueObjectSP valobj)
1304{
1305 if (class_name.empty())
1306 return NULL;
1307
1308 if (!valobj.get())
1309 return NULL;
1310
Enrico Granata979e20d2011-07-29 19:53:35 +00001311 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001312
1313 if (!target)
1314 return NULL;
1315
1316 Debugger &debugger = target->GetDebugger();
1317 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1318 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1319
1320 if (!script_interpreter)
1321 return NULL;
1322
1323 void* ret_val;
1324
1325 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1326 if (CurrentThreadHasPythonLock())
1327 {
1328 python_interpreter->EnterSession ();
1329 ret_val = g_swig_synthetic_script (class_name,
1330 python_interpreter->m_dictionary_name.c_str(),
1331 valobj);
1332 python_interpreter->LeaveSession ();
1333 }
1334 else
1335 {
1336 while (!GetPythonLock (1))
1337 fprintf (tmp_fh,
1338 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1339 python_interpreter->EnterSession ();
1340 ret_val = g_swig_synthetic_script (class_name,
1341 python_interpreter->m_dictionary_name.c_str(),
1342 valobj);
1343 python_interpreter->LeaveSession ();
1344 ReleasePythonLock ();
1345 }
1346
1347 return ret_val;
1348}
1349
Enrico Granataf7a9b142011-07-15 02:26:42 +00001350bool
1351ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output)
1352{
1353 StringList input(oneliner);
1354 return GenerateTypeScriptFunction(input, output);
1355}
1356
Chris Lattner24943d22010-06-08 16:52:24 +00001357bool
1358ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1359{
1360 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001361 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001362 int num_lines = user_input.GetSize ();
1363 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001364
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001365 // Check to see if we have any data; if not, just return.
1366 if (user_input.GetSize() == 0)
1367 return false;
1368
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001369 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1370 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001371
Caroline Ticeb447e842010-09-21 19:25:28 +00001372
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001373 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1374 ++num_created_functions;
1375 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001376
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001377 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001378 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001379
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001380 // Create the function name & definition string.
1381
Caroline Tice0aa2e552011-01-14 00:29:16 +00001382 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001383 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001384
1385 // Pre-pend code for setting up the session dictionary.
1386
1387 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1388 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1389 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1390 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1391 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001392
1393 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001394
1395 for (int i = 0; i < num_lines; ++i)
1396 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001397 sstr.Clear ();
1398 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1399 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001400 }
Chris Lattner24943d22010-06-08 16:52:24 +00001401
Caroline Tice0aa2e552011-01-14 00:29:16 +00001402 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1403 // got written to the values in the global dictionary, not the session dictionary).
1404
1405 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1406 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1407 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1408 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1409
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001410 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001411
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001412 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001413 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001414 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001415 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001416
1417 // Store the name of the auto-generated function to be called.
1418
1419 callback_data.AppendString (auto_generated_function_name.c_str());
1420 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001421}
1422
Enrico Granataf7a9b142011-07-15 02:26:42 +00001423std::string
1424ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1425 lldb::ValueObjectSP valobj)
1426{
1427
1428 if (!python_function_name || !(*python_function_name))
1429 return "<no function>";
1430
1431 if (!valobj.get())
1432 return "<no object>";
1433
Enrico Granata979e20d2011-07-29 19:53:35 +00001434 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001435
1436 if (!target)
1437 return "<no target>";
1438
1439 Debugger &debugger = target->GetDebugger();
1440 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1441 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1442
1443 if (!script_interpreter)
1444 return "<no python>";
1445
1446 std::string ret_val;
1447
1448 if (python_function_name
1449 && *python_function_name)
1450 {
1451 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1452 if (CurrentThreadHasPythonLock())
1453 {
1454 python_interpreter->EnterSession ();
1455 ret_val = g_swig_typescript_callback (python_function_name,
1456 python_interpreter->m_dictionary_name.c_str(),
1457 valobj);
1458 python_interpreter->LeaveSession ();
1459 }
1460 else
1461 {
1462 while (!GetPythonLock (1))
1463 fprintf (tmp_fh,
1464 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1465 python_interpreter->EnterSession ();
1466 ret_val = g_swig_typescript_callback (python_function_name,
1467 python_interpreter->m_dictionary_name.c_str(),
1468 valobj);
1469 python_interpreter->LeaveSession ();
1470 ReleasePythonLock ();
1471 }
1472 }
1473 else
1474 return "<no function name>";
1475
1476 return ret_val;
1477
1478}
1479
Greg Clayton5144f382010-10-07 17:14:24 +00001480bool
1481ScriptInterpreterPython::BreakpointCallbackFunction
1482(
1483 void *baton,
1484 StoppointCallbackContext *context,
1485 user_id_t break_id,
1486 user_id_t break_loc_id
1487)
1488{
1489 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1490 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001491
1492 if (!context)
1493 return true;
1494
1495 Target *target = context->exe_ctx.target;
1496
1497 if (!target)
1498 return true;
1499
1500 Debugger &debugger = target->GetDebugger();
1501 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1502 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1503
1504 if (!script_interpreter)
1505 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001506
1507 if (python_function_name != NULL
1508 && python_function_name[0] != '\0')
1509 {
1510 Thread *thread = context->exe_ctx.thread;
Greg Claytone86cbb92011-03-22 01:14:58 +00001511 const StackFrameSP stop_frame_sp (thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame));
Greg Clayton5144f382010-10-07 17:14:24 +00001512 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001513 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001514 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001515 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1516
1517 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001518 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001519 bool ret_val = true;
1520 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1521 if (CurrentThreadHasPythonLock())
1522 {
1523 python_interpreter->EnterSession ();
1524 ret_val = g_swig_breakpoint_callback (python_function_name,
1525 python_interpreter->m_dictionary_name.c_str(),
1526 stop_frame_sp,
1527 bp_loc_sp);
1528 python_interpreter->LeaveSession ();
1529 }
1530 else
1531 {
1532 while (!GetPythonLock (1))
1533 fprintf (tmp_fh,
1534 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1535 python_interpreter->EnterSession ();
1536 ret_val = g_swig_breakpoint_callback (python_function_name,
1537 python_interpreter->m_dictionary_name.c_str(),
1538 stop_frame_sp,
1539 bp_loc_sp);
1540 python_interpreter->LeaveSession ();
1541 ReleasePythonLock ();
1542 }
1543 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001544 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001545 }
Greg Clayton5144f382010-10-07 17:14:24 +00001546 }
1547 // We currently always true so we stop in case anything goes wrong when
1548 // trying to call the script function
1549 return true;
1550}
Caroline Tice2ade6112010-11-10 19:18:14 +00001551
1552lldb::thread_result_t
1553ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1554{
1555 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1556
1557 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1558
1559 if (log)
1560 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1561
1562 char error_str[1024];
1563 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001564 bool need_to_release_lock = true;
1565 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001566
Caroline Tice202f6b82011-01-17 21:55:19 +00001567 if (CurrentThreadHasPythonLock())
1568 {
1569 safe_to_run = true;
1570 need_to_release_lock = false;
1571 }
1572 else
1573 {
1574 int interval = 1;
1575 safe_to_run = GetPythonLock (interval);
1576 while (!safe_to_run)
1577 {
1578 interval = interval * 2;
1579 safe_to_run = GetPythonLock (interval);
1580 }
1581 }
1582
1583 if (pty_slave_name != NULL && safe_to_run)
1584 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001585 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001586
Caroline Tice202f6b82011-01-17 21:55:19 +00001587 script_interpreter->EnterSession ();
1588
Caroline Tice0aa2e552011-01-14 00:29:16 +00001589 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1590 PyRun_SimpleString (run_string.GetData());
1591 run_string.Clear ();
1592
1593 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1594 PyRun_SimpleString (run_string.GetData());
1595 run_string.Clear ();
1596
1597 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1598 PyRun_SimpleString (run_string.GetData());
1599 run_string.Clear ();
1600
1601 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1602 pty_slave_name);
1603 PyRun_SimpleString (run_string.GetData());
1604 run_string.Clear ();
1605
Johnny Chen8054ba32011-03-11 00:28:50 +00001606 // The following call drops into the embedded interpreter loop and stays there until the
1607 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001608
Caroline Ticece207c12011-03-11 00:21:55 +00001609 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001610 // 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 +00001611 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1612
1613 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1614 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1615 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1616 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1617 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1618 // hang (it's happened before).
1619
Caroline Tice9d352ce2011-03-07 23:24:28 +00001620 Py_BEGIN_ALLOW_THREADS
1621 PyGILState_STATE gstate = PyGILState_Ensure();
1622
Caroline Tice0aa2e552011-01-14 00:29:16 +00001623 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1624 PyRun_SimpleString (run_string.GetData());
1625 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001626
Caroline Tice9d352ce2011-03-07 23:24:28 +00001627 PyGILState_Release (gstate);
1628 Py_END_ALLOW_THREADS
1629
Caroline Tice0aa2e552011-01-14 00:29:16 +00001630 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1631 PyRun_SimpleString (run_string.GetData());
1632 run_string.Clear();
1633
1634 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1635 PyRun_SimpleString (run_string.GetData());
1636 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001637
1638 script_interpreter->LeaveSession ();
1639
Caroline Tice2ade6112010-11-10 19:18:14 +00001640 }
1641
Caroline Tice202f6b82011-01-17 21:55:19 +00001642 if (!safe_to_run)
1643 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1644 "Python interpreter locked on another thread; unable to acquire lock.\n");
1645
1646 if (need_to_release_lock)
1647 ReleasePythonLock ();
1648
Caroline Tice2ade6112010-11-10 19:18:14 +00001649 if (script_interpreter->m_embedded_thread_input_reader_sp)
1650 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1651
1652 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001653
1654 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001655
1656 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1657 if (log)
1658 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1659
1660
Johnny Chen8054ba32011-03-11 00:28:50 +00001661 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001662 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001663 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1664 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1665 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001666
Caroline Tice2ade6112010-11-10 19:18:14 +00001667 return NULL;
1668}
1669
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001670uint32_t
1671ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1672{
1673 if (!implementor)
1674 return 0;
1675
1676 if (!g_swig_calc_children)
1677 return 0;
1678
1679 ScriptInterpreterPython *python_interpreter = this;
1680
1681 uint32_t ret_val = 0;
1682
1683 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1684 if (CurrentThreadHasPythonLock())
1685 {
1686 python_interpreter->EnterSession ();
1687 ret_val = g_swig_calc_children (implementor);
1688 python_interpreter->LeaveSession ();
1689 }
1690 else
1691 {
1692 while (!GetPythonLock (1))
1693 fprintf (tmp_fh,
1694 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1695 python_interpreter->EnterSession ();
1696 ret_val = g_swig_calc_children (implementor);
1697 python_interpreter->LeaveSession ();
1698 ReleasePythonLock ();
1699 }
1700
1701 return ret_val;
1702}
1703
1704void*
1705ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1706{
1707 if (!implementor)
1708 return 0;
1709
1710 if (!g_swig_get_child_index)
1711 return 0;
1712
1713 ScriptInterpreterPython *python_interpreter = this;
1714
1715 void* ret_val = NULL;
1716
1717 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1718 if (CurrentThreadHasPythonLock())
1719 {
1720 python_interpreter->EnterSession ();
1721 ret_val = g_swig_get_child_index (implementor,idx);
1722 python_interpreter->LeaveSession ();
1723 }
1724 else
1725 {
1726 while (!GetPythonLock (1))
1727 fprintf (tmp_fh,
1728 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1729 python_interpreter->EnterSession ();
1730 ret_val = g_swig_get_child_index (implementor,idx);
1731 python_interpreter->LeaveSession ();
1732 ReleasePythonLock ();
1733 }
1734
1735 return ret_val;
1736}
1737
1738int
1739ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1740{
1741 if (!implementor)
1742 return UINT32_MAX;
1743
1744 if (!g_swig_get_index_child)
1745 return UINT32_MAX;
1746
1747 ScriptInterpreterPython *python_interpreter = this;
1748
1749 int ret_val = UINT32_MAX;
1750
1751 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1752 if (CurrentThreadHasPythonLock())
1753 {
1754 python_interpreter->EnterSession ();
1755 ret_val = g_swig_get_index_child (implementor, child_name);
1756 python_interpreter->LeaveSession ();
1757 }
1758 else
1759 {
1760 while (!GetPythonLock (1))
1761 fprintf (tmp_fh,
1762 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1763 python_interpreter->EnterSession ();
1764 ret_val = g_swig_get_index_child (implementor, child_name);
1765 python_interpreter->LeaveSession ();
1766 ReleasePythonLock ();
1767 }
1768
1769 return ret_val;
1770}
1771
Enrico Granata979e20d2011-07-29 19:53:35 +00001772void
1773ScriptInterpreterPython::UpdateSynthProviderInstance (void* implementor)
1774{
1775 if (!implementor)
1776 return;
1777
1778 if (!g_swig_update_provider)
1779 return;
1780
1781 ScriptInterpreterPython *python_interpreter = this;
1782
1783 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1784 if (CurrentThreadHasPythonLock())
1785 {
1786 python_interpreter->EnterSession ();
1787 g_swig_update_provider (implementor);
1788 python_interpreter->LeaveSession ();
1789 }
1790 else
1791 {
1792 while (!GetPythonLock (1))
1793 fprintf (tmp_fh,
1794 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1795 python_interpreter->EnterSession ();
1796 g_swig_update_provider (implementor);
1797 python_interpreter->LeaveSession ();
1798 ReleasePythonLock ();
1799 }
1800
1801 return;
1802}
1803
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001804lldb::SBValue*
1805ScriptInterpreterPython::CastPyObjectToSBValue (void* data)
1806{
1807 if (!data)
1808 return NULL;
1809
1810 if (!g_swig_cast_to_sbvalue)
1811 return NULL;
1812
1813 ScriptInterpreterPython *python_interpreter = this;
1814
1815 lldb::SBValue* ret_val = NULL;
1816
1817 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1818 if (CurrentThreadHasPythonLock())
1819 {
1820 python_interpreter->EnterSession ();
1821 ret_val = g_swig_cast_to_sbvalue (data);
1822 python_interpreter->LeaveSession ();
1823 }
1824 else
1825 {
1826 while (!GetPythonLock (1))
1827 fprintf (tmp_fh,
1828 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1829 python_interpreter->EnterSession ();
1830 ret_val = g_swig_cast_to_sbvalue (data);
1831 python_interpreter->LeaveSession ();
1832 ReleasePythonLock ();
1833 }
1834
1835 return ret_val;
1836}
1837
Caroline Tice2ade6112010-11-10 19:18:14 +00001838
Caroline Tice0aa2e552011-01-14 00:29:16 +00001839void
Greg Claytone86cbb92011-03-22 01:14:58 +00001840ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00001841 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001842 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
1843 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
1844 SWIGPythonCalculateNumChildren python_swig_calc_children,
1845 SWIGPythonGetChildAtIndex python_swig_get_child_index,
1846 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
Enrico Granata979e20d2011-07-29 19:53:35 +00001847 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue,
1848 SWIGPythonUpdateSynthProviderInstance python_swig_update_provider)
Greg Claytone86cbb92011-03-22 01:14:58 +00001849{
1850 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001851 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1852 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001853 g_swig_synthetic_script = python_swig_synthetic_script;
1854 g_swig_calc_children = python_swig_calc_children;
1855 g_swig_get_child_index = python_swig_get_child_index;
1856 g_swig_get_index_child = python_swig_get_index_child;
1857 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Enrico Granata979e20d2011-07-29 19:53:35 +00001858 g_swig_update_provider = python_swig_update_provider;
Greg Claytone86cbb92011-03-22 01:14:58 +00001859}
1860
1861void
1862ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001863{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001864 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1865
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001866 // Python will muck with STDIN terminal state, so save off any current TTY
1867 // settings so we can restore them.
1868 TerminalState stdin_tty_state;
1869 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001870
1871 // Find the module that owns this code and use that path we get to
1872 // set the PYTHONPATH appropriately.
1873
1874 FileSpec file_spec;
1875 char python_dir_path[PATH_MAX];
1876 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1877 {
1878 std::string python_path;
1879 const char *curr_python_path = ::getenv ("PYTHONPATH");
1880 if (curr_python_path)
1881 {
1882 // We have a current value for PYTHONPATH, so lets append to it
1883 python_path.append (curr_python_path);
1884 }
1885
1886 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1887 {
1888 if (!python_path.empty())
1889 python_path.append (1, ':');
1890 python_path.append (python_dir_path);
1891 }
1892
1893 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1894 {
1895 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1896 {
1897 if (!python_path.empty())
1898 python_path.append (1, ':');
1899 python_path.append (python_dir_path);
1900 }
1901 }
1902 const char *pathon_path_env_cstr = python_path.c_str();
1903 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
1904 }
1905
Caroline Tice9d352ce2011-03-07 23:24:28 +00001906 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001907 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001908
Greg Claytone86cbb92011-03-22 01:14:58 +00001909 // Initialize SWIG after setting up python
1910 assert (g_swig_init_callback != NULL);
1911 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001912
1913 // Update the path python uses to search for modules to include the current directory.
1914
Caroline Ticed4d92832011-06-13 21:33:00 +00001915 PyRun_SimpleString ("import sys");
1916 PyRun_SimpleString ("sys.path.append ('.')");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001917
Caroline Ticed4d92832011-06-13 21:33:00 +00001918 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001919
Caroline Ticed4d92832011-06-13 21:33:00 +00001920 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1921 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
1922 PyRun_SimpleString ("import sys");
1923 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001924
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001925 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001926}
1927
Greg Claytone86cbb92011-03-22 01:14:58 +00001928//void
1929//ScriptInterpreterPython::Terminate ()
1930//{
1931// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1932// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1933// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1934// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1935// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1936// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1937// // within Py_Finalize, which results in a seg fault.
1938// //
1939// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1940// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1941// // process exits).
1942// //
1943//// Py_Finalize ();
1944//}