blob: e0a88cbc338f1a79e9bdf11bdbf13d48539e4310 [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
176 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000177 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000178 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000179 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000180
181 if (need_to_release_lock)
182 ReleasePythonLock();
Chris Lattner24943d22010-06-08 16:52:24 +0000183}
184
185ScriptInterpreterPython::~ScriptInterpreterPython ()
186{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000187 Debugger &debugger = GetCommandInterpreter().GetDebugger();
188
189 if (m_embedded_thread_input_reader_sp.get() != NULL)
190 {
191 m_embedded_thread_input_reader_sp->SetIsDone (true);
192 m_embedded_python_pty.CloseSlaveFileDescriptor();
193 m_pty_slave_is_open = false;
194 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
195 m_embedded_thread_input_reader_sp.reset();
196 debugger.PopInputReader (reader_sp);
197 }
198
199 if (m_new_sysout)
200 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000201 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
202 if (!CurrentThreadHasPythonLock ())
203 {
204 while (!GetPythonLock (1))
205 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
206 Py_DECREF (m_new_sysout);
207 ReleasePythonLock ();
208 }
209 else
210 Py_DECREF (m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000211 }
Chris Lattner24943d22010-06-08 16:52:24 +0000212}
213
Caroline Tice0aa2e552011-01-14 00:29:16 +0000214void
215ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
216{
217 if (fh == NULL)
218 return;
219
220 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000221
Caroline Tice202f6b82011-01-17 21:55:19 +0000222 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
223 if (!CurrentThreadHasPythonLock ())
224 {
225 while (!GetPythonLock (1))
226 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
227 EnterSession ();
228 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
229 LeaveSession ();
230 ReleasePythonLock ();
231 }
232 else
233 {
234 EnterSession ();
235 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
236 LeaveSession ();
237 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000238}
239
240void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000241ScriptInterpreterPython::SaveTerminalState (int fd)
242{
243 // Python mucks with the terminal state of STDIN. If we can possibly avoid
244 // this by setting the file handles up correctly prior to entering the
245 // interpreter we should. For now we save and restore the terminal state
246 // on the input file handle.
247 m_terminal_state.Save (fd, false);
248}
249
250void
251ScriptInterpreterPython::RestoreTerminalState ()
252{
253 // Python mucks with the terminal state of STDIN. If we can possibly avoid
254 // this by setting the file handles up correctly prior to entering the
255 // interpreter we should. For now we save and restore the terminal state
256 // on the input file handle.
257 m_terminal_state.Restore();
258}
259
260
261
262void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000263ScriptInterpreterPython::LeaveSession ()
264{
265 m_session_is_active = false;
266}
267
268void
269ScriptInterpreterPython::EnterSession ()
270{
271 // If we have already entered the session, without having officially 'left' it, then there is no need to
272 // 'enter' it again.
273
274 if (m_session_is_active)
275 return;
276
277 m_session_is_active = true;
278
Caroline Tice202f6b82011-01-17 21:55:19 +0000279 StreamString run_string;
280
281 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
282 GetCommandInterpreter().GetDebugger().GetID());
283 PyRun_SimpleString (run_string.GetData());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000284 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +0000285
Caroline Tice0aa2e552011-01-14 00:29:16 +0000286
Caroline Tice6af65cb2011-05-03 21:21:50 +0000287 run_string.Printf ("run_one_line (%s, 'lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%d)')",
288 m_dictionary_name.c_str(),
289 GetCommandInterpreter().GetDebugger().GetID());
290 PyRun_SimpleString (run_string.GetData());
291 run_string.Clear();
292
293
294 ExecutionContext exe_ctx = m_interpreter.GetDebugger().GetSelectedExecutionContext();
295
296 if (exe_ctx.target)
297 run_string.Printf ("run_one_line (%s, 'lldb.target = lldb.debugger.GetSelectedTarget()')",
298 m_dictionary_name.c_str());
299 else
300 run_string.Printf ("run_one_line (%s, 'lldb.target = None')", m_dictionary_name.c_str());
301 PyRun_SimpleString (run_string.GetData());
302 run_string.Clear();
303
304 if (exe_ctx.process)
305 run_string.Printf ("run_one_line (%s, 'lldb.process = lldb.target.GetProcess()')", m_dictionary_name.c_str());
306 else
307 run_string.Printf ("run_one_line (%s, 'lldb.process = None')", m_dictionary_name.c_str());
308 PyRun_SimpleString (run_string.GetData());
309 run_string.Clear();
310
311 if (exe_ctx.thread)
312 run_string.Printf ("run_one_line (%s, 'lldb.thread = lldb.process.GetSelectedThread ()')",
313 m_dictionary_name.c_str());
314 else
315 run_string.Printf ("run_one_line (%s, 'lldb.thread = None')", m_dictionary_name.c_str());
316 PyRun_SimpleString (run_string.GetData());
317 run_string.Clear();
318
319 if (exe_ctx.frame)
320 run_string.Printf ("run_one_line (%s, 'lldb.frame = lldb.thread.GetSelectedFrame ()')",
321 m_dictionary_name.c_str());
322 else
323 run_string.Printf ("run_one_line (%s, 'lldb.frame = None')", m_dictionary_name.c_str());
324 PyRun_SimpleString (run_string.GetData());
325 run_string.Clear();
326
Caroline Tice0aa2e552011-01-14 00:29:16 +0000327 PyObject *sysmod = PyImport_AddModule ("sys");
328 PyObject *sysdict = PyModule_GetDict (sysmod);
329
330 if ((m_new_sysout != NULL)
331 && (sysmod != NULL)
332 && (sysdict != NULL))
333 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
334
335 if (PyErr_Occurred())
336 PyErr_Clear ();
337
Caroline Tice0aa2e552011-01-14 00:29:16 +0000338 if (!m_pty_slave_is_open)
339 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000340 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000341 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
342 m_pty_slave_name.c_str());
343 PyRun_SimpleString (run_string.GetData());
344 m_pty_slave_is_open = true;
345
346 run_string.Clear();
347 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
348 PyRun_SimpleString (run_string.GetData());
349 }
350}
351
352
Johnny Chen60dde642010-07-30 22:33:14 +0000353bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000354ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000355{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000356 if (!m_valid_session)
357 return false;
358
Caroline Tice0aa2e552011-01-14 00:29:16 +0000359
Caroline Tice0aa2e552011-01-14 00:29:16 +0000360
Caroline Tice4a461da2011-01-14 21:09:29 +0000361 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
362 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
363 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
364 // method to pass the command string directly down to Python.
365
366
Caroline Tice202f6b82011-01-17 21:55:19 +0000367 bool need_to_release_lock = true;
368
369 if (CurrentThreadHasPythonLock())
370 need_to_release_lock = false;
371 else if (!GetPythonLock (1))
372 {
373 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
374 "Python interpreter is currently locked by another thread; unable to process command.\n");
375 return false;
376 }
377
378 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000379 bool success = false;
380
Greg Clayton63094e02010-06-23 01:19:29 +0000381 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000382 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000383 // Find the correct script interpreter dictionary in the main module.
384 PyObject *main_mod = PyImport_AddModule ("__main__");
385 PyObject *script_interpreter_dict = NULL;
386 if (main_mod != NULL)
387 {
388 PyObject *main_dict = PyModule_GetDict (main_mod);
389 if ((main_dict != NULL)
390 && PyDict_Check (main_dict))
391 {
392 // Go through the main dictionary looking for the correct python script interpreter dictionary
393 PyObject *key, *value;
394 Py_ssize_t pos = 0;
395
396 while (PyDict_Next (main_dict, &pos, &key, &value))
397 {
398 // We have stolen references to the key and value objects in the dictionary; we need to increment
399 // them now so that Python's garbage collector doesn't collect them out from under us.
400 Py_INCREF (key);
401 Py_INCREF (value);
402 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
403 {
404 script_interpreter_dict = value;
405 break;
406 }
407 }
408 }
409
410 if (script_interpreter_dict != NULL)
411 {
412 PyObject *pfunc = NULL;
413 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
414 if (pmod != NULL)
415 {
416 PyObject *pmod_dict = PyModule_GetDict (pmod);
417 if ((pmod_dict != NULL)
418 && PyDict_Check (pmod_dict))
419 {
420 PyObject *key, *value;
421 Py_ssize_t pos = 0;
422
423 while (PyDict_Next (pmod_dict, &pos, &key, &value))
424 {
425 Py_INCREF (key);
426 Py_INCREF (value);
427 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
428 {
429 pfunc = value;
430 break;
431 }
432 }
433
434 PyObject *string_arg = PyString_FromString (command);
435 if (pfunc && string_arg && PyCallable_Check (pfunc))
436 {
437 PyObject *pargs = PyTuple_New (2);
438 if (pargs != NULL)
439 {
440 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
441 PyTuple_SetItem (pargs, 1, string_arg);
442 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
443 Py_DECREF (pargs);
444 if (pvalue != NULL)
445 {
446 Py_DECREF (pvalue);
447 success = true;
448 }
449 else if (PyErr_Occurred ())
450 {
451 PyErr_Print();
452 PyErr_Clear();
453 }
454 }
455 }
456 }
457 }
458 Py_INCREF (script_interpreter_dict);
459 }
460 }
Greg Clayton63094e02010-06-23 01:19:29 +0000461
Caroline Tice0aa2e552011-01-14 00:29:16 +0000462 LeaveSession ();
463
Caroline Tice202f6b82011-01-17 21:55:19 +0000464 if (need_to_release_lock)
465 ReleasePythonLock();
466
Caroline Tice4a461da2011-01-14 21:09:29 +0000467 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000468 return true;
469
470 // The one-liner failed. Append the error message.
471 if (result)
472 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
473 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000474 }
Johnny Chen60dde642010-07-30 22:33:14 +0000475
Caroline Tice0aa2e552011-01-14 00:29:16 +0000476 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000477
478 if (need_to_release_lock)
479 ReleasePythonLock ();
480
Johnny Chen60dde642010-07-30 22:33:14 +0000481 if (result)
482 result->AppendError ("empty command passed to python\n");
483 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000484}
485
486
487
488size_t
489ScriptInterpreterPython::InputReaderCallback
490(
491 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000492 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000493 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000494 const char *bytes,
495 size_t bytes_len
496)
497{
Caroline Tice2ade6112010-11-10 19:18:14 +0000498 lldb::thread_t embedded_interpreter_thread;
499 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
500
Chris Lattner24943d22010-06-08 16:52:24 +0000501 if (baton == NULL)
502 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000503
504 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
505
506 if (script_interpreter->m_script_lang != eScriptLanguagePython)
507 return 0;
508
Caroline Tice892fadd2011-06-16 16:27:19 +0000509 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
510 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
511
Chris Lattner24943d22010-06-08 16:52:24 +0000512 switch (notification)
513 {
514 case eInputReaderActivate:
515 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000516 if (!batch_mode)
517 {
518 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
519 out_stream->Flush();
520 }
Greg Clayton58928562011-02-09 01:08:52 +0000521
Chris Lattner24943d22010-06-08 16:52:24 +0000522 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000523 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
524 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000525 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000526
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000527 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000528
Caroline Tice202f6b82011-01-17 21:55:19 +0000529 if (!CurrentThreadHasPythonLock())
530 {
531 while (!GetPythonLock(1))
532 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000533 out_stream->Printf ("Python interpreter locked on another thread; waiting to acquire lock...\n");
534 out_stream->Flush();
Caroline Tice202f6b82011-01-17 21:55:19 +0000535 }
536 script_interpreter->EnterSession ();
537 ReleasePythonLock();
538 }
539 else
540 script_interpreter->EnterSession ();
541
Caroline Tice2ade6112010-11-10 19:18:14 +0000542 char error_str[1024];
543 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
544 sizeof(error_str)))
545 {
546 if (log)
547 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
548 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
549 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
550 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
551 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000552 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000553 {
554 if (log)
555 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
556 Error detach_error;
557 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
558 }
559 else
560 {
561 if (log)
562 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
563 reader.SetIsDone (true);
564 }
565 }
566 else
567 {
568 if (log)
569 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
570 reader.SetIsDone (true);
571 }
Chris Lattner24943d22010-06-08 16:52:24 +0000572 }
573 break;
574
575 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000576 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000577 break;
578
579 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000580 if (!CurrentThreadHasPythonLock())
581 {
582 while (!GetPythonLock(1))
583 {
584 // Wait until lock is acquired.
585 }
586 script_interpreter->EnterSession ();
587 ReleasePythonLock();
588 }
589 else
590 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000591 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000592
Caroline Tice4a348082011-05-02 20:41:46 +0000593 case eInputReaderAsynchronousOutputWritten:
594 break;
595
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000596 case eInputReaderInterrupt:
597 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
598 break;
599
600 case eInputReaderEndOfFile:
601 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
602 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000603
604 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000605 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000606 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000607 if (log)
608 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
609 bytes_len);
610 if (bytes && bytes_len)
611 {
612 if ((int) bytes[0] == 4)
613 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
614 else
615 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
616 }
617 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000618 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000619 else
620 {
621 if (log)
622 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
623 bytes,
624 bytes_len);
625 reader.SetIsDone (true);
626 }
627
Chris Lattner24943d22010-06-08 16:52:24 +0000628 break;
629
630 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000631 script_interpreter->LeaveSession ();
632
Chris Lattner24943d22010-06-08 16:52:24 +0000633 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000634 if (log)
635 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000636
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000637 script_interpreter->RestoreTerminalState ();
638
Caroline Tice2ade6112010-11-10 19:18:14 +0000639 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000640 break;
641 }
642
643 return bytes_len;
644}
645
646
647void
Greg Clayton238c0a12010-09-18 01:14:36 +0000648ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000649{
650 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
651
Caroline Tice0aa2e552011-01-14 00:29:16 +0000652 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000653
654 // At the moment, the only time the debugger does not have an input file handle is when this is called
655 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
656 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
657 // do it.
658
Greg Clayton58928562011-02-09 01:08:52 +0000659 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000660 return;
661
Greg Clayton63094e02010-06-23 01:19:29 +0000662 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000663 if (reader_sp)
664 {
665 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
666 this, // baton
667 eInputReaderGranularityLine, // token size, to pass to callback function
668 NULL, // end token
669 NULL, // prompt
670 true)); // echo input
671
672 if (error.Success())
673 {
Greg Clayton63094e02010-06-23 01:19:29 +0000674 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000675 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000676 }
677 }
678}
679
680bool
681ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
682 ScriptInterpreter::ReturnType return_type,
683 void *ret_value)
684{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000685
Caroline Tice202f6b82011-01-17 21:55:19 +0000686 bool need_to_release_lock = true;
687
688 if (CurrentThreadHasPythonLock())
689 need_to_release_lock = false;
690 else if (!GetPythonLock (1))
691 {
692 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
693 "Python interpreter is currently locked by another thread; unable to process command.\n");
694 return false;
695 }
696
697 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000698
Chris Lattner24943d22010-06-08 16:52:24 +0000699 PyObject *py_return = NULL;
700 PyObject *mainmod = PyImport_AddModule ("__main__");
701 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000702 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000703 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000704 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000705 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000706 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000707
708 if (PyDict_Check (globals))
709 {
710 PyObject *key, *value;
711 Py_ssize_t pos = 0;
712
713 int i = 0;
714 while (PyDict_Next (globals, &pos, &key, &value))
715 {
716 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
717 // so that Python's garbage collector doesn't collect them out from under us.
718 Py_INCREF (key);
719 Py_INCREF (value);
720 char *c_str = PyString_AsString (key);
721 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
722 locals = value;
723 ++i;
724 }
725 }
Chris Lattner24943d22010-06-08 16:52:24 +0000726
Caroline Tice0aa2e552011-01-14 00:29:16 +0000727 if (locals == NULL)
728 {
729 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
730 should_decrement_locals = true;
731 }
732
733 if (locals == NULL)
734 {
735 locals = globals;
736 should_decrement_locals = false;
737 }
738
739 py_error = PyErr_Occurred();
740 if (py_error != NULL)
741 PyErr_Clear();
742
Chris Lattner24943d22010-06-08 16:52:24 +0000743 if (in_string != NULL)
744 {
745 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
746 if (py_return == NULL)
747 {
748 py_error = PyErr_Occurred ();
749 if (py_error != NULL)
750 PyErr_Clear ();
751
752 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
753 }
754
Caroline Tice0aa2e552011-01-14 00:29:16 +0000755 if (locals != NULL
756 && should_decrement_locals)
757 Py_DECREF (locals);
758
Chris Lattner24943d22010-06-08 16:52:24 +0000759 if (py_return != NULL)
760 {
761 switch (return_type)
762 {
763 case eCharPtr: // "char *"
764 {
765 const char format[3] = "s#";
766 success = PyArg_Parse (py_return, format, (char **) &ret_value);
767 break;
768 }
Enrico Granatac2a28252011-08-16 16:49:25 +0000769 case eCharStrOrNone: // char* or NULL if py_return == Py_None
770 {
771 const char format[3] = "z";
772 success = PyArg_Parse (py_return, format, (char **) &ret_value);
773 break;
774 }
Chris Lattner24943d22010-06-08 16:52:24 +0000775 case eBool:
776 {
777 const char format[2] = "b";
778 success = PyArg_Parse (py_return, format, (bool *) ret_value);
779 break;
780 }
781 case eShortInt:
782 {
783 const char format[2] = "h";
784 success = PyArg_Parse (py_return, format, (short *) ret_value);
785 break;
786 }
787 case eShortIntUnsigned:
788 {
789 const char format[2] = "H";
790 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
791 break;
792 }
793 case eInt:
794 {
795 const char format[2] = "i";
796 success = PyArg_Parse (py_return, format, (int *) ret_value);
797 break;
798 }
799 case eIntUnsigned:
800 {
801 const char format[2] = "I";
802 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
803 break;
804 }
805 case eLongInt:
806 {
807 const char format[2] = "l";
808 success = PyArg_Parse (py_return, format, (long *) ret_value);
809 break;
810 }
811 case eLongIntUnsigned:
812 {
813 const char format[2] = "k";
814 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
815 break;
816 }
817 case eLongLong:
818 {
819 const char format[2] = "L";
820 success = PyArg_Parse (py_return, format, (long long *) ret_value);
821 break;
822 }
823 case eLongLongUnsigned:
824 {
825 const char format[2] = "K";
826 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
827 break;
828 }
829 case eFloat:
830 {
831 const char format[2] = "f";
832 success = PyArg_Parse (py_return, format, (float *) ret_value);
833 break;
834 }
835 case eDouble:
836 {
837 const char format[2] = "d";
838 success = PyArg_Parse (py_return, format, (double *) ret_value);
839 break;
840 }
841 case eChar:
842 {
843 const char format[2] = "c";
844 success = PyArg_Parse (py_return, format, (char *) ret_value);
845 break;
846 }
847 default:
848 {}
849 }
850 Py_DECREF (py_return);
851 if (success)
852 ret_success = true;
853 else
854 ret_success = false;
855 }
856 }
857
858 py_error = PyErr_Occurred();
859 if (py_error != NULL)
860 {
861 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
862 PyErr_Print ();
863 PyErr_Clear();
864 ret_success = false;
865 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000866
867 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000868
Caroline Tice202f6b82011-01-17 21:55:19 +0000869 if (need_to_release_lock)
870 ReleasePythonLock();
871
Chris Lattner24943d22010-06-08 16:52:24 +0000872 return ret_success;
873}
874
875bool
876ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
877{
Caroline Tice202f6b82011-01-17 21:55:19 +0000878 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
879 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000880
Caroline Tice202f6b82011-01-17 21:55:19 +0000881 if (CurrentThreadHasPythonLock())
882 need_to_release_lock = false;
883 else
884 {
885 while (!GetPythonLock (1))
886 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
887 }
888
889 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000890
Chris Lattner24943d22010-06-08 16:52:24 +0000891 bool success = false;
892 PyObject *py_return = NULL;
893 PyObject *mainmod = PyImport_AddModule ("__main__");
894 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000895 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000896 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000897 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000898
Caroline Tice0aa2e552011-01-14 00:29:16 +0000899 if (PyDict_Check (globals))
900 {
901 PyObject *key, *value;
902 Py_ssize_t pos = 0;
903
904 while (PyDict_Next (globals, &pos, &key, &value))
905 {
906 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
907 // so that Python's garbage collector doesn't collect them out from under us.
908 Py_INCREF (key);
909 Py_INCREF (value);
910 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
911 locals = value;
912 }
913 }
914
915 if (locals == NULL)
916 {
917 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
918 should_decrement_locals = true;
919 }
920
921 if (locals == NULL)
922 {
923 locals = globals;
924 should_decrement_locals = false;
925 }
926
927 py_error = PyErr_Occurred();
928 if (py_error != NULL)
929 PyErr_Clear();
930
Chris Lattner24943d22010-06-08 16:52:24 +0000931 if (in_string != NULL)
932 {
933 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
934 if (compiled_node)
935 {
936 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
937 if (compiled_code)
938 {
939 py_return = PyEval_EvalCode (compiled_code, globals, locals);
940 if (py_return != NULL)
941 {
942 success = true;
943 Py_DECREF (py_return);
944 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000945 if (locals && should_decrement_locals)
946 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000947 }
948 }
949 }
950
951 py_error = PyErr_Occurred ();
952 if (py_error != NULL)
953 {
954 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
955 PyErr_Print ();
956 PyErr_Clear();
957 success = false;
958 }
959
Caroline Tice0aa2e552011-01-14 00:29:16 +0000960 LeaveSession ();
961
Caroline Tice202f6b82011-01-17 21:55:19 +0000962 if (need_to_release_lock)
963 ReleasePythonLock();
964
Chris Lattner24943d22010-06-08 16:52:24 +0000965 return success;
966}
967
968static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
969
970size_t
971ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
972(
973 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000974 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000975 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000976 const char *bytes,
977 size_t bytes_len
978)
979{
Caroline Tice892fadd2011-06-16 16:27:19 +0000980 static StringList commands_in_progress;
981
982 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
983 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
984
Chris Lattner24943d22010-06-08 16:52:24 +0000985 switch (notification)
986 {
987 case eInputReaderActivate:
988 {
989 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +0000990 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +0000991 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000992 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000993 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +0000994 out_stream->Printf ("%s", reader.GetPrompt());
995 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +0000996 }
997 }
998 break;
999
1000 case eInputReaderDeactivate:
1001 break;
1002
1003 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001004 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001005 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001006 out_stream->Printf ("%s", reader.GetPrompt());
1007 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001008 }
Chris Lattner24943d22010-06-08 16:52:24 +00001009 break;
1010
Caroline Tice4a348082011-05-02 20:41:46 +00001011 case eInputReaderAsynchronousOutputWritten:
1012 break;
1013
Chris Lattner24943d22010-06-08 16:52:24 +00001014 case eInputReaderGotToken:
1015 {
1016 std::string temp_string (bytes, bytes_len);
1017 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001018 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001019 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001020 out_stream->Printf ("%s", reader.GetPrompt());
1021 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001022 }
Chris Lattner24943d22010-06-08 16:52:24 +00001023 }
1024 break;
1025
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001026 case eInputReaderEndOfFile:
1027 case eInputReaderInterrupt:
1028 // Control-c (SIGINT) & control-d both mean finish & exit.
1029 reader.SetIsDone(true);
1030
1031 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1032 if (notification == eInputReaderInterrupt)
1033 commands_in_progress.Clear();
1034
1035 // Fall through here...
1036
Chris Lattner24943d22010-06-08 16:52:24 +00001037 case eInputReaderDone:
1038 {
1039 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1040 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1041 data_ap->user_source.AppendList (commands_in_progress);
1042 if (data_ap.get())
1043 {
Greg Clayton63094e02010-06-23 01:19:29 +00001044 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001045 if (interpreter)
1046 {
1047 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1048 data_ap->script_source))
1049 {
1050 if (data_ap->script_source.GetSize() == 1)
1051 {
1052 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1053 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1054 }
1055 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001056 else if (!batch_mode)
1057 {
1058 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1059 out_stream->Flush();
1060 }
Chris Lattner24943d22010-06-08 16:52:24 +00001061 }
1062 else
1063 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001064 if (!batch_mode)
1065 {
1066 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1067 out_stream->Flush();
1068 }
Chris Lattner24943d22010-06-08 16:52:24 +00001069 }
1070 }
1071 }
1072 break;
1073
1074 }
1075
1076 return bytes_len;
1077}
1078
1079void
Greg Clayton238c0a12010-09-18 01:14:36 +00001080ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001081 CommandReturnObject &result)
1082{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001083 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1084
Greg Clayton63094e02010-06-23 01:19:29 +00001085 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001086
1087 if (reader_sp)
1088 {
1089 Error err = reader_sp->Initialize (
1090 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1091 bp_options, // baton
1092 eInputReaderGranularityLine, // token size, for feeding data to callback function
1093 "DONE", // end token
1094 "> ", // prompt
1095 true); // echo input
1096
1097 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001098 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001099 else
1100 {
1101 result.AppendError (err.AsCString());
1102 result.SetStatus (eReturnStatusFailed);
1103 }
1104 }
1105 else
1106 {
1107 result.AppendError("out of memory");
1108 result.SetStatus (eReturnStatusFailed);
1109 }
1110}
1111
Johnny Chen3e0571b2010-09-11 00:23:59 +00001112// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001113void
Greg Clayton238c0a12010-09-18 01:14:36 +00001114ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001115 const char *oneliner)
1116{
1117 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1118
1119 // It's necessary to set both user_source and script_source to the oneliner.
1120 // The former is used to generate callback description (as in breakpoint command list)
1121 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001122
Johnny Chend1c2dca2010-09-10 18:21:10 +00001123 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001124
Caroline Tice5136f942010-09-27 21:35:15 +00001125 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1126 {
1127 if (data_ap->script_source.GetSize() == 1)
1128 {
1129 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1130 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1131 }
1132 }
1133
Johnny Chend1c2dca2010-09-10 18:21:10 +00001134 return;
1135}
1136
Chris Lattner24943d22010-06-08 16:52:24 +00001137bool
1138ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1139{
1140 // Convert StringList to one long, newline delimited, const char *.
1141 std::string function_def_string;
1142
1143 int num_lines = function_def.GetSize();
1144
1145 for (int i = 0; i < num_lines; ++i)
1146 {
1147 function_def_string.append (function_def.GetStringAtIndex(i));
1148 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1149 function_def_string.append ("\n");
1150
1151 }
1152
1153 return ExecuteMultipleLines (function_def_string.c_str());
1154}
1155
Enrico Granataf7a9b142011-07-15 02:26:42 +00001156// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1157// use this code to generate their functions
1158bool
1159ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1160{
1161 int num_lines = input.GetSize ();
1162 if (num_lines == 0)
1163 return false;
1164 StreamString sstr;
1165 StringList auto_generated_function;
1166 auto_generated_function.AppendString (signature.c_str());
1167 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1168 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1169 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1170 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1171 // global dictionary.
1172
1173 // Wrap everything up inside the function, increasing the indentation.
1174
1175 for (int i = 0; i < num_lines; ++i)
1176 {
1177 sstr.Clear ();
1178 sstr.Printf (" %s", input.GetStringAtIndex (i));
1179 auto_generated_function.AppendString (sstr.GetData());
1180 }
1181 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1182 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1183 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1184 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1185
1186 // Verify that the results are valid Python.
1187
1188 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1189 return false;
1190
1191 return true;
1192
1193}
1194
1195// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1196// given to generated functions, of course)
1197bool
1198ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output)
1199{
1200 static int num_created_functions = 0;
1201 user_input.RemoveBlankLines ();
1202 int num_lines = user_input.GetSize ();
1203 StreamString sstr;
1204
1205 // Check to see if we have any data; if not, just return.
1206 if (user_input.GetSize() == 0)
1207 return false;
1208
1209 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1210 // ValueObject as parameter to the function.
1211
1212 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1213 ++num_created_functions;
1214 std::string auto_generated_function_name = sstr.GetData();
1215
1216 sstr.Clear();
1217 StringList auto_generated_function;
1218
1219 // Create the function name & definition string.
1220
1221 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1222 auto_generated_function.AppendString (sstr.GetData());
1223
1224 // Pre-pend code for setting up the session dictionary.
1225
1226 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1227 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1228 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1229 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1230 // global dictionary.
1231
1232 // Wrap everything up inside the function, increasing the indentation.
1233
1234 for (int i = 0; i < num_lines; ++i)
1235 {
1236 sstr.Clear ();
1237 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1238 auto_generated_function.AppendString (sstr.GetData());
1239 }
1240
1241 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1242 // got written to the values in the global dictionary, not the session dictionary).
1243
1244 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1245 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1246 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1247 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1248
1249 // Verify that the results are valid Python.
1250
1251 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1252 return false;
1253
1254 // Store the name of the auto-generated function to be called.
1255
1256 output.AppendString (auto_generated_function_name.c_str());
1257 return true;
1258}
1259
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001260bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001261ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, StringList &output)
1262{
1263 static int num_created_functions = 0;
1264 user_input.RemoveBlankLines ();
1265 int num_lines = user_input.GetSize ();
1266 StreamString sstr;
1267
1268 // Check to see if we have any data; if not, just return.
1269 if (user_input.GetSize() == 0)
1270 return false;
1271
1272 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1273 // ValueObject as parameter to the function.
1274
1275 sstr.Printf ("lldb_autogen_python_cmd_alias_func_%d", num_created_functions);
1276 ++num_created_functions;
1277 std::string auto_generated_function_name = sstr.GetData();
1278
1279 sstr.Clear();
1280 StringList auto_generated_function;
1281
1282 // Create the function name & definition string.
1283
1284 sstr.Printf ("def %s (debugger, args, dict):", auto_generated_function_name.c_str());
1285 auto_generated_function.AppendString (sstr.GetData());
1286
1287 // Pre-pend code for setting up the session dictionary.
1288
1289 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1290 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1291 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1292 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1293 // global dictionary.
1294
1295 // Wrap everything up inside the function, increasing the indentation.
1296
1297 for (int i = 0; i < num_lines; ++i)
1298 {
1299 sstr.Clear ();
1300 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1301 auto_generated_function.AppendString (sstr.GetData());
1302 }
1303
1304 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1305 // got written to the values in the global dictionary, not the session dictionary).
1306
1307 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1308 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1309 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1310 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1311
1312 // Verify that the results are valid Python.
1313
1314 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1315 return false;
1316
1317 // Store the name of the auto-generated function to be called.
1318
1319 output.AppendString (auto_generated_function_name.c_str());
1320 return true;
1321}
1322
1323
1324bool
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001325ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output)
1326{
1327 static int num_created_classes = 0;
1328 user_input.RemoveBlankLines ();
1329 int num_lines = user_input.GetSize ();
1330 StreamString sstr;
1331
1332 // Check to see if we have any data; if not, just return.
1333 if (user_input.GetSize() == 0)
1334 return false;
1335
1336 // Wrap all user input into a Python class
1337
1338 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1339 ++num_created_classes;
1340 std::string auto_generated_class_name = sstr.GetData();
1341
1342 sstr.Clear();
1343 StringList auto_generated_class;
1344
1345 // Create the function name & definition string.
1346
1347 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1348 auto_generated_class.AppendString (sstr.GetData());
1349
1350 // Wrap everything up inside the class, increasing the indentation.
1351
1352 for (int i = 0; i < num_lines; ++i)
1353 {
1354 sstr.Clear ();
1355 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1356 auto_generated_class.AppendString (sstr.GetData());
1357 }
1358
1359
1360 // Verify that the results are valid Python.
1361 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1362 // (TODO: rename that method to ExportDefinitionToInterpreter)
1363 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1364 return false;
1365
1366 // Store the name of the auto-generated class
1367
1368 output.AppendString (auto_generated_class_name.c_str());
1369 return true;
1370}
1371
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001372void*
1373ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1374 lldb::ValueObjectSP valobj)
1375{
1376 if (class_name.empty())
1377 return NULL;
1378
1379 if (!valobj.get())
1380 return NULL;
1381
Enrico Granata979e20d2011-07-29 19:53:35 +00001382 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001383
1384 if (!target)
1385 return NULL;
1386
1387 Debugger &debugger = target->GetDebugger();
1388 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1389 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1390
1391 if (!script_interpreter)
1392 return NULL;
1393
1394 void* ret_val;
1395
1396 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1397 if (CurrentThreadHasPythonLock())
1398 {
1399 python_interpreter->EnterSession ();
1400 ret_val = g_swig_synthetic_script (class_name,
1401 python_interpreter->m_dictionary_name.c_str(),
1402 valobj);
1403 python_interpreter->LeaveSession ();
1404 }
1405 else
1406 {
1407 while (!GetPythonLock (1))
1408 fprintf (tmp_fh,
1409 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1410 python_interpreter->EnterSession ();
1411 ret_val = g_swig_synthetic_script (class_name,
1412 python_interpreter->m_dictionary_name.c_str(),
1413 valobj);
1414 python_interpreter->LeaveSession ();
1415 ReleasePythonLock ();
1416 }
1417
1418 return ret_val;
1419}
1420
Enrico Granataf7a9b142011-07-15 02:26:42 +00001421bool
1422ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output)
1423{
1424 StringList input(oneliner);
1425 return GenerateTypeScriptFunction(input, output);
1426}
1427
Chris Lattner24943d22010-06-08 16:52:24 +00001428bool
1429ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1430{
1431 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001432 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001433 int num_lines = user_input.GetSize ();
1434 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001435
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001436 // Check to see if we have any data; if not, just return.
1437 if (user_input.GetSize() == 0)
1438 return false;
1439
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001440 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1441 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001442
Caroline Ticeb447e842010-09-21 19:25:28 +00001443
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001444 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1445 ++num_created_functions;
1446 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001447
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001448 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001449 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001450
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001451 // Create the function name & definition string.
1452
Caroline Tice0aa2e552011-01-14 00:29:16 +00001453 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001454 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001455
1456 // Pre-pend code for setting up the session dictionary.
1457
1458 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1459 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1460 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1461 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1462 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001463
1464 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001465
1466 for (int i = 0; i < num_lines; ++i)
1467 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001468 sstr.Clear ();
1469 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1470 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001471 }
Chris Lattner24943d22010-06-08 16:52:24 +00001472
Caroline Tice0aa2e552011-01-14 00:29:16 +00001473 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1474 // got written to the values in the global dictionary, not the session dictionary).
1475
1476 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1477 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1478 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1479 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1480
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001481 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001482
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001483 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001484 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001485 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001486 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001487
1488 // Store the name of the auto-generated function to be called.
1489
1490 callback_data.AppendString (auto_generated_function_name.c_str());
1491 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001492}
1493
Enrico Granataf7a9b142011-07-15 02:26:42 +00001494std::string
1495ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1496 lldb::ValueObjectSP valobj)
1497{
1498
1499 if (!python_function_name || !(*python_function_name))
1500 return "<no function>";
1501
1502 if (!valobj.get())
1503 return "<no object>";
1504
Enrico Granata979e20d2011-07-29 19:53:35 +00001505 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001506
1507 if (!target)
1508 return "<no target>";
1509
1510 Debugger &debugger = target->GetDebugger();
1511 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1512 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1513
1514 if (!script_interpreter)
1515 return "<no python>";
1516
1517 std::string ret_val;
1518
1519 if (python_function_name
1520 && *python_function_name)
1521 {
1522 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1523 if (CurrentThreadHasPythonLock())
1524 {
1525 python_interpreter->EnterSession ();
1526 ret_val = g_swig_typescript_callback (python_function_name,
1527 python_interpreter->m_dictionary_name.c_str(),
1528 valobj);
1529 python_interpreter->LeaveSession ();
1530 }
1531 else
1532 {
1533 while (!GetPythonLock (1))
1534 fprintf (tmp_fh,
1535 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1536 python_interpreter->EnterSession ();
1537 ret_val = g_swig_typescript_callback (python_function_name,
1538 python_interpreter->m_dictionary_name.c_str(),
1539 valobj);
1540 python_interpreter->LeaveSession ();
1541 ReleasePythonLock ();
1542 }
1543 }
1544 else
1545 return "<no function name>";
1546
1547 return ret_val;
1548
1549}
1550
Greg Clayton5144f382010-10-07 17:14:24 +00001551bool
1552ScriptInterpreterPython::BreakpointCallbackFunction
1553(
1554 void *baton,
1555 StoppointCallbackContext *context,
1556 user_id_t break_id,
1557 user_id_t break_loc_id
1558)
1559{
1560 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1561 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001562
1563 if (!context)
1564 return true;
1565
1566 Target *target = context->exe_ctx.target;
1567
1568 if (!target)
1569 return true;
1570
1571 Debugger &debugger = target->GetDebugger();
1572 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1573 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1574
1575 if (!script_interpreter)
1576 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001577
1578 if (python_function_name != NULL
1579 && python_function_name[0] != '\0')
1580 {
1581 Thread *thread = context->exe_ctx.thread;
Greg Claytone86cbb92011-03-22 01:14:58 +00001582 const StackFrameSP stop_frame_sp (thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame));
Greg Clayton5144f382010-10-07 17:14:24 +00001583 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001584 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001585 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001586 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1587
1588 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001589 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001590 bool ret_val = true;
1591 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1592 if (CurrentThreadHasPythonLock())
1593 {
1594 python_interpreter->EnterSession ();
1595 ret_val = g_swig_breakpoint_callback (python_function_name,
1596 python_interpreter->m_dictionary_name.c_str(),
1597 stop_frame_sp,
1598 bp_loc_sp);
1599 python_interpreter->LeaveSession ();
1600 }
1601 else
1602 {
1603 while (!GetPythonLock (1))
1604 fprintf (tmp_fh,
1605 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1606 python_interpreter->EnterSession ();
1607 ret_val = g_swig_breakpoint_callback (python_function_name,
1608 python_interpreter->m_dictionary_name.c_str(),
1609 stop_frame_sp,
1610 bp_loc_sp);
1611 python_interpreter->LeaveSession ();
1612 ReleasePythonLock ();
1613 }
1614 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001615 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001616 }
Greg Clayton5144f382010-10-07 17:14:24 +00001617 }
1618 // We currently always true so we stop in case anything goes wrong when
1619 // trying to call the script function
1620 return true;
1621}
Caroline Tice2ade6112010-11-10 19:18:14 +00001622
1623lldb::thread_result_t
1624ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1625{
1626 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1627
1628 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1629
1630 if (log)
1631 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1632
1633 char error_str[1024];
1634 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001635 bool need_to_release_lock = true;
1636 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001637
Caroline Tice202f6b82011-01-17 21:55:19 +00001638 if (CurrentThreadHasPythonLock())
1639 {
1640 safe_to_run = true;
1641 need_to_release_lock = false;
1642 }
1643 else
1644 {
1645 int interval = 1;
1646 safe_to_run = GetPythonLock (interval);
1647 while (!safe_to_run)
1648 {
1649 interval = interval * 2;
1650 safe_to_run = GetPythonLock (interval);
1651 }
1652 }
1653
1654 if (pty_slave_name != NULL && safe_to_run)
1655 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001656 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001657
Caroline Tice202f6b82011-01-17 21:55:19 +00001658 script_interpreter->EnterSession ();
1659
Caroline Tice0aa2e552011-01-14 00:29:16 +00001660 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1661 PyRun_SimpleString (run_string.GetData());
1662 run_string.Clear ();
1663
1664 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1665 PyRun_SimpleString (run_string.GetData());
1666 run_string.Clear ();
1667
1668 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1669 PyRun_SimpleString (run_string.GetData());
1670 run_string.Clear ();
1671
1672 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1673 pty_slave_name);
1674 PyRun_SimpleString (run_string.GetData());
1675 run_string.Clear ();
1676
Johnny Chen8054ba32011-03-11 00:28:50 +00001677 // The following call drops into the embedded interpreter loop and stays there until the
1678 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001679
Caroline Ticece207c12011-03-11 00:21:55 +00001680 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001681 // 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 +00001682 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1683
1684 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1685 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1686 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1687 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1688 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1689 // hang (it's happened before).
1690
Caroline Tice9d352ce2011-03-07 23:24:28 +00001691 Py_BEGIN_ALLOW_THREADS
1692 PyGILState_STATE gstate = PyGILState_Ensure();
1693
Caroline Tice0aa2e552011-01-14 00:29:16 +00001694 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1695 PyRun_SimpleString (run_string.GetData());
1696 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001697
Caroline Tice9d352ce2011-03-07 23:24:28 +00001698 PyGILState_Release (gstate);
1699 Py_END_ALLOW_THREADS
1700
Caroline Tice0aa2e552011-01-14 00:29:16 +00001701 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1702 PyRun_SimpleString (run_string.GetData());
1703 run_string.Clear();
1704
1705 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1706 PyRun_SimpleString (run_string.GetData());
1707 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001708
1709 script_interpreter->LeaveSession ();
1710
Caroline Tice2ade6112010-11-10 19:18:14 +00001711 }
1712
Caroline Tice202f6b82011-01-17 21:55:19 +00001713 if (!safe_to_run)
1714 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1715 "Python interpreter locked on another thread; unable to acquire lock.\n");
1716
1717 if (need_to_release_lock)
1718 ReleasePythonLock ();
1719
Caroline Tice2ade6112010-11-10 19:18:14 +00001720 if (script_interpreter->m_embedded_thread_input_reader_sp)
1721 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1722
1723 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001724
1725 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001726
1727 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1728 if (log)
1729 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1730
1731
Johnny Chen8054ba32011-03-11 00:28:50 +00001732 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001733 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001734 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1735 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1736 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001737
Caroline Tice2ade6112010-11-10 19:18:14 +00001738 return NULL;
1739}
1740
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001741uint32_t
1742ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1743{
1744 if (!implementor)
1745 return 0;
1746
1747 if (!g_swig_calc_children)
1748 return 0;
1749
1750 ScriptInterpreterPython *python_interpreter = this;
1751
1752 uint32_t ret_val = 0;
1753
1754 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1755 if (CurrentThreadHasPythonLock())
1756 {
1757 python_interpreter->EnterSession ();
1758 ret_val = g_swig_calc_children (implementor);
1759 python_interpreter->LeaveSession ();
1760 }
1761 else
1762 {
1763 while (!GetPythonLock (1))
1764 fprintf (tmp_fh,
1765 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1766 python_interpreter->EnterSession ();
1767 ret_val = g_swig_calc_children (implementor);
1768 python_interpreter->LeaveSession ();
1769 ReleasePythonLock ();
1770 }
1771
1772 return ret_val;
1773}
1774
1775void*
1776ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1777{
1778 if (!implementor)
1779 return 0;
1780
1781 if (!g_swig_get_child_index)
1782 return 0;
1783
1784 ScriptInterpreterPython *python_interpreter = this;
1785
1786 void* ret_val = NULL;
1787
1788 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1789 if (CurrentThreadHasPythonLock())
1790 {
1791 python_interpreter->EnterSession ();
1792 ret_val = g_swig_get_child_index (implementor,idx);
1793 python_interpreter->LeaveSession ();
1794 }
1795 else
1796 {
1797 while (!GetPythonLock (1))
1798 fprintf (tmp_fh,
1799 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1800 python_interpreter->EnterSession ();
1801 ret_val = g_swig_get_child_index (implementor,idx);
1802 python_interpreter->LeaveSession ();
1803 ReleasePythonLock ();
1804 }
1805
1806 return ret_val;
1807}
1808
1809int
1810ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1811{
1812 if (!implementor)
1813 return UINT32_MAX;
1814
1815 if (!g_swig_get_index_child)
1816 return UINT32_MAX;
1817
1818 ScriptInterpreterPython *python_interpreter = this;
1819
1820 int ret_val = UINT32_MAX;
1821
1822 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1823 if (CurrentThreadHasPythonLock())
1824 {
1825 python_interpreter->EnterSession ();
1826 ret_val = g_swig_get_index_child (implementor, child_name);
1827 python_interpreter->LeaveSession ();
1828 }
1829 else
1830 {
1831 while (!GetPythonLock (1))
1832 fprintf (tmp_fh,
1833 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1834 python_interpreter->EnterSession ();
1835 ret_val = g_swig_get_index_child (implementor, child_name);
1836 python_interpreter->LeaveSession ();
1837 ReleasePythonLock ();
1838 }
1839
1840 return ret_val;
1841}
1842
Enrico Granata979e20d2011-07-29 19:53:35 +00001843void
1844ScriptInterpreterPython::UpdateSynthProviderInstance (void* implementor)
1845{
1846 if (!implementor)
1847 return;
1848
1849 if (!g_swig_update_provider)
1850 return;
1851
1852 ScriptInterpreterPython *python_interpreter = this;
1853
1854 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1855 if (CurrentThreadHasPythonLock())
1856 {
1857 python_interpreter->EnterSession ();
1858 g_swig_update_provider (implementor);
1859 python_interpreter->LeaveSession ();
1860 }
1861 else
1862 {
1863 while (!GetPythonLock (1))
1864 fprintf (tmp_fh,
1865 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1866 python_interpreter->EnterSession ();
1867 g_swig_update_provider (implementor);
1868 python_interpreter->LeaveSession ();
1869 ReleasePythonLock ();
1870 }
1871
1872 return;
1873}
1874
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001875lldb::SBValue*
1876ScriptInterpreterPython::CastPyObjectToSBValue (void* data)
1877{
1878 if (!data)
1879 return NULL;
1880
1881 if (!g_swig_cast_to_sbvalue)
1882 return NULL;
1883
1884 ScriptInterpreterPython *python_interpreter = this;
1885
1886 lldb::SBValue* ret_val = NULL;
1887
1888 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1889 if (CurrentThreadHasPythonLock())
1890 {
1891 python_interpreter->EnterSession ();
1892 ret_val = g_swig_cast_to_sbvalue (data);
1893 python_interpreter->LeaveSession ();
1894 }
1895 else
1896 {
1897 while (!GetPythonLock (1))
1898 fprintf (tmp_fh,
1899 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1900 python_interpreter->EnterSession ();
1901 ret_val = g_swig_cast_to_sbvalue (data);
1902 python_interpreter->LeaveSession ();
1903 ReleasePythonLock ();
1904 }
1905
1906 return ret_val;
1907}
1908
Enrico Granatac2a28252011-08-16 16:49:25 +00001909bool
1910ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1911 const char* args,
1912 lldb::SBStream& stream,
1913 Error& error)
1914{
1915 if (!impl_function)
1916 {
1917 error.SetErrorString("no function to execute");
1918 return false;
1919 }
1920
1921 if (!g_swig_call_command)
1922 {
1923 error.SetErrorString("no helper function to run scripted commands");
1924 return false;
1925 }
1926
1927 ScriptInterpreterPython *python_interpreter = this;
1928
1929 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
1930
1931 bool ret_val;
1932
1933 std::string err_msg;
1934
1935 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1936 if (CurrentThreadHasPythonLock())
1937 {
1938 python_interpreter->EnterSession ();
1939 ret_val = g_swig_call_command (impl_function,
1940 python_interpreter->m_dictionary_name.c_str(),
1941 debugger_sp,
1942 args,
1943 err_msg,
1944 stream);
1945 python_interpreter->LeaveSession ();
1946 }
1947 else
1948 {
1949 while (!GetPythonLock (1))
1950 fprintf (tmp_fh,
1951 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1952 python_interpreter->EnterSession ();
1953 ret_val = g_swig_call_command (impl_function,
1954 python_interpreter->m_dictionary_name.c_str(),
1955 debugger_sp,
1956 args,
1957 err_msg,
1958 stream);
1959 python_interpreter->LeaveSession ();
1960 ReleasePythonLock ();
1961 }
1962
1963 if (!ret_val)
1964 error.SetErrorString(err_msg.c_str());
1965 else
1966 error.Clear();
1967
1968 return ret_val;
1969
1970
1971 return true;
1972
1973}
1974
Caroline Tice2ade6112010-11-10 19:18:14 +00001975
Caroline Tice0aa2e552011-01-14 00:29:16 +00001976void
Greg Claytone86cbb92011-03-22 01:14:58 +00001977ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00001978 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001979 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
1980 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
1981 SWIGPythonCalculateNumChildren python_swig_calc_children,
1982 SWIGPythonGetChildAtIndex python_swig_get_child_index,
1983 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
Enrico Granata979e20d2011-07-29 19:53:35 +00001984 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue,
Enrico Granatac2a28252011-08-16 16:49:25 +00001985 SWIGPythonUpdateSynthProviderInstance python_swig_update_provider,
1986 SWIGPythonCallCommand python_swig_call_command)
Greg Claytone86cbb92011-03-22 01:14:58 +00001987{
1988 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001989 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1990 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001991 g_swig_synthetic_script = python_swig_synthetic_script;
1992 g_swig_calc_children = python_swig_calc_children;
1993 g_swig_get_child_index = python_swig_get_child_index;
1994 g_swig_get_index_child = python_swig_get_index_child;
1995 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Enrico Granata979e20d2011-07-29 19:53:35 +00001996 g_swig_update_provider = python_swig_update_provider;
Enrico Granatac2a28252011-08-16 16:49:25 +00001997 g_swig_call_command = python_swig_call_command;
Greg Claytone86cbb92011-03-22 01:14:58 +00001998}
1999
2000void
2001ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00002002{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002003 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
2004
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002005 // Python will muck with STDIN terminal state, so save off any current TTY
2006 // settings so we can restore them.
2007 TerminalState stdin_tty_state;
2008 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002009
2010 // Find the module that owns this code and use that path we get to
2011 // set the PYTHONPATH appropriately.
2012
2013 FileSpec file_spec;
2014 char python_dir_path[PATH_MAX];
2015 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
2016 {
2017 std::string python_path;
2018 const char *curr_python_path = ::getenv ("PYTHONPATH");
2019 if (curr_python_path)
2020 {
2021 // We have a current value for PYTHONPATH, so lets append to it
2022 python_path.append (curr_python_path);
2023 }
2024
2025 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2026 {
2027 if (!python_path.empty())
2028 python_path.append (1, ':');
2029 python_path.append (python_dir_path);
2030 }
2031
2032 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
2033 {
2034 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2035 {
2036 if (!python_path.empty())
2037 python_path.append (1, ':');
2038 python_path.append (python_dir_path);
2039 }
2040 }
2041 const char *pathon_path_env_cstr = python_path.c_str();
2042 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
2043 }
2044
Caroline Tice9d352ce2011-03-07 23:24:28 +00002045 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00002046 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002047
Greg Claytone86cbb92011-03-22 01:14:58 +00002048 // Initialize SWIG after setting up python
2049 assert (g_swig_init_callback != NULL);
2050 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002051
2052 // Update the path python uses to search for modules to include the current directory.
2053
Caroline Ticed4d92832011-06-13 21:33:00 +00002054 PyRun_SimpleString ("import sys");
2055 PyRun_SimpleString ("sys.path.append ('.')");
Caroline Tice0aa2e552011-01-14 00:29:16 +00002056
Caroline Ticed4d92832011-06-13 21:33:00 +00002057 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00002058
Caroline Ticed4d92832011-06-13 21:33:00 +00002059 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
2060 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
2061 PyRun_SimpleString ("import sys");
2062 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00002063
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002064 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002065}
2066
Greg Claytone86cbb92011-03-22 01:14:58 +00002067//void
2068//ScriptInterpreterPython::Terminate ()
2069//{
2070// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
2071// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
2072// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
2073// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
2074// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
2075// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
2076// // within Py_Finalize, which results in a seg fault.
2077// //
2078// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
2079// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
2080// // process exits).
2081// //
2082//// Py_Finalize ();
2083//}