blob: d2d355cac4140098590becae3785c6f2532468ed [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
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +000011// the *FIRST* header file included here.
Greg Clayton3e4238d2011-11-04 03:34:56 +000012#ifdef LLDB_DISABLE_PYTHON
13
14// Python is disabled in this build
15
16#else
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +000017
18#if defined (__APPLE__)
19#include <Python/Python.h>
20#else
21#include <Python.h>
22#endif
Chris Lattner24943d22010-06-08 16:52:24 +000023
24#include "lldb/Interpreter/ScriptInterpreterPython.h"
25
Chris Lattner24943d22010-06-08 16:52:24 +000026#include <stdlib.h>
27#include <stdio.h>
28
29#include <string>
30
Enrico Granata91544802011-09-06 19:20:51 +000031#include "lldb/API/SBValue.h"
Greg Clayton987c7eb2011-09-17 08:33:22 +000032#include "lldb/Breakpoint/BreakpointLocation.h"
Greg Clayton63094e02010-06-23 01:19:29 +000033#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner24943d22010-06-08 16:52:24 +000034#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000035#include "lldb/Core/Timer.h"
36#include "lldb/Host/Host.h"
37#include "lldb/Interpreter/CommandInterpreter.h"
38#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton5144f382010-10-07 17:14:24 +000039#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040
Chris Lattner24943d22010-06-08 16:52:24 +000041using namespace lldb;
42using namespace lldb_private;
43
Greg Claytone86cbb92011-03-22 01:14:58 +000044
45static ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL;
46static ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL;
Enrico Granataf7a9b142011-07-15 02:26:42 +000047static ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL;
Enrico Granata9ae7cef2011-07-24 00:14:56 +000048static ScriptInterpreter::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = NULL;
49static ScriptInterpreter::SWIGPythonCalculateNumChildren g_swig_calc_children = NULL;
50static ScriptInterpreter::SWIGPythonGetChildAtIndex g_swig_get_child_index = NULL;
51static ScriptInterpreter::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = NULL;
52static ScriptInterpreter::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = NULL;
Enrico Granata979e20d2011-07-29 19:53:35 +000053static ScriptInterpreter::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = NULL;
Enrico Granatac2a28252011-08-16 16:49:25 +000054static ScriptInterpreter::SWIGPythonCallCommand g_swig_call_command = NULL;
Enrico Granata59df36f2011-10-17 21:45:27 +000055static ScriptInterpreter::SWIGPythonCallModuleInit g_swig_call_module_init = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +000056
57static int
58_check_and_flush (FILE *stream)
59{
60 int prev_fail = ferror (stream);
61 return fflush (stream) || prev_fail ? EOF : 0;
62}
63
Caroline Tice202f6b82011-01-17 21:55:19 +000064static Predicate<lldb::tid_t> &
65PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +000066{
Caroline Tice202f6b82011-01-17 21:55:19 +000067 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
68 return g_interpreter_is_running;
69}
70
Enrico Granatafa1f6172011-10-24 17:22:21 +000071bool
72ScriptInterpreterPython::Locker::CurrentThreadHasPythonLock ()
Caroline Tice202f6b82011-01-17 21:55:19 +000073{
74 TimeValue timeout;
75
76 timeout = TimeValue::Now(); // Don't wait any time.
77
78 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
79}
80
Enrico Granatafa1f6172011-10-24 17:22:21 +000081bool
82ScriptInterpreterPython::Locker::TryGetPythonLock (uint32_t seconds_to_wait)
Caroline Tice202f6b82011-01-17 21:55:19 +000083{
84
85 TimeValue timeout;
86
87 if (seconds_to_wait != UINT32_MAX)
88 {
89 timeout = TimeValue::Now();
90 timeout.OffsetWithSeconds (seconds_to_wait);
91 }
92
93 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
94 Host::GetCurrentThreadID(), &timeout, NULL);
95}
96
Enrico Granatafa1f6172011-10-24 17:22:21 +000097void
98ScriptInterpreterPython::Locker::ReleasePythonLock ()
Caroline Tice202f6b82011-01-17 21:55:19 +000099{
100 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000101}
102
Enrico Granatafa1f6172011-10-24 17:22:21 +0000103ScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *py_interpreter,
104 uint16_t on_entry,
105 uint16_t on_leave,
106 FILE* wait_msg_handle) :
107 m_need_session( (on_leave & TearDownSession) == TearDownSession ),
108 m_release_lock ( false ), // decide in constructor body
109 m_python_interpreter(py_interpreter),
110 m_tmp_fh(wait_msg_handle)
Enrico Granata91544802011-09-06 19:20:51 +0000111{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000112 if (m_python_interpreter && !m_tmp_fh)
113 m_tmp_fh = (m_python_interpreter->m_dbg_stdout ? m_python_interpreter->m_dbg_stdout : stdout);
114
115 if ( (on_entry & AcquireLock) == AcquireLock )
116 {
117 if (CurrentThreadHasPythonLock())
118 {
119 if ( (on_leave & FreeLock) == FreeLock )
120 m_release_lock = true;
121 }
122 else
123 {
124 DoAcquireLock();
125 if ( (on_leave & FreeLock) == FreeLock )
126 m_release_lock = true;
127 if ( (on_leave & FreeAcquiredLock) == FreeAcquiredLock )
128 m_release_lock = true;
129 }
130 }
131 if ( (on_entry & InitSession) == InitSession )
132 DoInitSession();
133}
134
135bool
136ScriptInterpreterPython::Locker::DoAcquireLock()
137{
Enrico Granata91544802011-09-06 19:20:51 +0000138 if (!CurrentThreadHasPythonLock())
139 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000140 while (!TryGetPythonLock (1))
141 if (m_tmp_fh)
142 fprintf (m_tmp_fh,
Enrico Granata91544802011-09-06 19:20:51 +0000143 "Python interpreter locked on another thread; waiting to acquire lock...\n");
Enrico Granata91544802011-09-06 19:20:51 +0000144 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000145 return true;
146}
147
148bool
149ScriptInterpreterPython::Locker::DoInitSession()
150{
151 if (!m_python_interpreter)
152 return false;
153 m_python_interpreter->EnterSession ();
154 return true;
155}
156
157bool
158ScriptInterpreterPython::Locker::DoFreeLock()
159{
160 ReleasePythonLock ();
161 return true;
162}
163
164bool
165ScriptInterpreterPython::Locker::DoTearDownSession()
166{
167 if (!m_python_interpreter)
168 return false;
169 m_python_interpreter->LeaveSession ();
170 return true;
Enrico Granata91544802011-09-06 19:20:51 +0000171}
172
173ScriptInterpreterPython::Locker::~Locker()
174{
175 if (m_need_session)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000176 DoTearDownSession();
Enrico Granata91544802011-09-06 19:20:51 +0000177 if (m_release_lock)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000178 DoFreeLock();
Enrico Granata91544802011-09-06 19:20:51 +0000179}
180
Greg Clayton63094e02010-06-23 01:19:29 +0000181ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000182 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000183 m_embedded_python_pty (),
184 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +0000185 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000186 m_new_sysout (NULL),
187 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000188 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000189 m_session_is_active (false),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000190 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000191{
192
Greg Clayton7c330d62011-01-27 01:01:10 +0000193 static int g_initialized = false;
194
195 if (!g_initialized)
196 {
197 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000198 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000199 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000200
201 Locker locker(this,
202 ScriptInterpreterPython::Locker::AcquireLock,
203 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Greg Clayton7c330d62011-01-27 01:01:10 +0000204
Caroline Tice0aa2e552011-01-14 00:29:16 +0000205 m_dictionary_name.append("_dict");
206 StreamString run_string;
207 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
208 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000209
Caroline Tice0aa2e552011-01-14 00:29:16 +0000210 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000211
212 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
213 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
214 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
215 // call to Debugger::Terminate is made, the ref-count has the correct value.
216 //
217 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
218 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000219
Caroline Tice0aa2e552011-01-14 00:29:16 +0000220 int old_count = Debugger::TestDebuggerRefCount();
Greg Claytonb302dff2012-02-01 08:09:32 +0000221
Chris Lattner24943d22010-06-08 16:52:24 +0000222
Greg Claytonb302dff2012-02-01 08:09:32 +0000223 run_string.Printf ("run_one_line (%s, 'import copy, os, re, sys, uuid, lldb, gnu_libstdcpp, objc')", m_dictionary_name.c_str());
Caroline Tice0aa2e552011-01-14 00:29:16 +0000224 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000225
Greg Claytonb302dff2012-02-01 08:09:32 +0000226
Caroline Tice0aa2e552011-01-14 00:29:16 +0000227 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000228
Caroline Tice0aa2e552011-01-14 00:29:16 +0000229 if (new_count > old_count)
230 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000231
Caroline Tice0aa2e552011-01-14 00:29:16 +0000232 run_string.Clear();
Greg Clayton444e35b2011-10-19 18:09:39 +0000233 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000234 interpreter.GetDebugger().GetID());
235 PyRun_SimpleString (run_string.GetData());
236
237 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000238 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000239 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000240 }
Chris Lattner24943d22010-06-08 16:52:24 +0000241}
242
243ScriptInterpreterPython::~ScriptInterpreterPython ()
244{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000245 Debugger &debugger = GetCommandInterpreter().GetDebugger();
246
247 if (m_embedded_thread_input_reader_sp.get() != NULL)
248 {
249 m_embedded_thread_input_reader_sp->SetIsDone (true);
250 m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000251 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
252 m_embedded_thread_input_reader_sp.reset();
253 debugger.PopInputReader (reader_sp);
254 }
255
256 if (m_new_sysout)
257 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000258 Locker locker(this,
259 ScriptInterpreterPython::Locker::AcquireLock,
260 ScriptInterpreterPython::Locker::FreeLock);
261 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000262 }
Chris Lattner24943d22010-06-08 16:52:24 +0000263}
264
Caroline Tice0aa2e552011-01-14 00:29:16 +0000265void
266ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
267{
268 if (fh == NULL)
269 return;
270
271 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000272
Enrico Granatafa1f6172011-10-24 17:22:21 +0000273 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +0000274
275 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000276}
277
278void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000279ScriptInterpreterPython::SaveTerminalState (int fd)
280{
281 // Python mucks with the terminal state of STDIN. If we can possibly avoid
282 // this by setting the file handles up correctly prior to entering the
283 // interpreter we should. For now we save and restore the terminal state
284 // on the input file handle.
285 m_terminal_state.Save (fd, false);
286}
287
288void
289ScriptInterpreterPython::RestoreTerminalState ()
290{
291 // Python mucks with the terminal state of STDIN. If we can possibly avoid
292 // this by setting the file handles up correctly prior to entering the
293 // interpreter we should. For now we save and restore the terminal state
294 // on the input file handle.
295 m_terminal_state.Restore();
296}
297
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000298void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000299ScriptInterpreterPython::LeaveSession ()
300{
301 m_session_is_active = false;
302}
303
304void
305ScriptInterpreterPython::EnterSession ()
306{
307 // If we have already entered the session, without having officially 'left' it, then there is no need to
308 // 'enter' it again.
309
310 if (m_session_is_active)
311 return;
312
313 m_session_is_active = true;
314
Caroline Tice202f6b82011-01-17 21:55:19 +0000315 StreamString run_string;
316
Greg Clayton2fecc452012-01-28 02:11:02 +0000317 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %llu", m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
318 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)", GetCommandInterpreter().GetDebugger().GetID());
319 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
320 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
321 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
322 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
323 // Make sure STDIN is closed since when we run this as an embedded
324 // interpreter we don't want someone to call "line = sys.stdin.readline()"
325 // and lock up. We don't have multiple windows and when the interpreter is
326 // embedded we don't know we should be feeding input to the embedded
327 // interpreter or to the python sys.stdin. We also don't want to let python
328 // play with the real stdin from this process, so we need to close it...
Greg Clayton3eeaf6e2012-02-03 01:30:30 +0000329 //run_string.PutCString ("; sys.stdin.close()");
Greg Clayton2fecc452012-01-28 02:11:02 +0000330 run_string.PutCString ("')");
Caroline Tice0aa2e552011-01-14 00:29:16 +0000331
Caroline Tice6af65cb2011-05-03 21:21:50 +0000332 PyRun_SimpleString (run_string.GetData());
333 run_string.Clear();
334
Caroline Tice0aa2e552011-01-14 00:29:16 +0000335 PyObject *sysmod = PyImport_AddModule ("sys");
336 PyObject *sysdict = PyModule_GetDict (sysmod);
337
Greg Clayton2fecc452012-01-28 02:11:02 +0000338 if (m_new_sysout && sysmod && sysdict)
339 {
340 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
341 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
342 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000343
344 if (PyErr_Occurred())
345 PyErr_Clear ();
Greg Clayton2fecc452012-01-28 02:11:02 +0000346}
Caroline Tice0aa2e552011-01-14 00:29:16 +0000347
Johnny Chen60dde642010-07-30 22:33:14 +0000348bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000349ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000350{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000351 if (!m_valid_session)
352 return false;
353
Caroline Tice4a461da2011-01-14 21:09:29 +0000354 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
355 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
356 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
357 // method to pass the command string directly down to Python.
358
Enrico Granatafa1f6172011-10-24 17:22:21 +0000359 Locker locker(this,
360 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
361 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000362
363 bool success = false;
364
Greg Clayton63094e02010-06-23 01:19:29 +0000365 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000366 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000367 // Find the correct script interpreter dictionary in the main module.
368 PyObject *main_mod = PyImport_AddModule ("__main__");
369 PyObject *script_interpreter_dict = NULL;
370 if (main_mod != NULL)
371 {
372 PyObject *main_dict = PyModule_GetDict (main_mod);
373 if ((main_dict != NULL)
374 && PyDict_Check (main_dict))
375 {
376 // Go through the main dictionary looking for the correct python script interpreter dictionary
377 PyObject *key, *value;
378 Py_ssize_t pos = 0;
379
380 while (PyDict_Next (main_dict, &pos, &key, &value))
381 {
382 // We have stolen references to the key and value objects in the dictionary; we need to increment
383 // them now so that Python's garbage collector doesn't collect them out from under us.
384 Py_INCREF (key);
385 Py_INCREF (value);
386 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
387 {
388 script_interpreter_dict = value;
389 break;
390 }
391 }
392 }
393
394 if (script_interpreter_dict != NULL)
395 {
396 PyObject *pfunc = NULL;
397 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
398 if (pmod != NULL)
399 {
400 PyObject *pmod_dict = PyModule_GetDict (pmod);
401 if ((pmod_dict != NULL)
402 && PyDict_Check (pmod_dict))
403 {
404 PyObject *key, *value;
405 Py_ssize_t pos = 0;
406
407 while (PyDict_Next (pmod_dict, &pos, &key, &value))
408 {
409 Py_INCREF (key);
410 Py_INCREF (value);
411 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
412 {
413 pfunc = value;
414 break;
415 }
416 }
417
418 PyObject *string_arg = PyString_FromString (command);
419 if (pfunc && string_arg && PyCallable_Check (pfunc))
420 {
421 PyObject *pargs = PyTuple_New (2);
422 if (pargs != NULL)
423 {
424 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
425 PyTuple_SetItem (pargs, 1, string_arg);
426 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
427 Py_DECREF (pargs);
428 if (pvalue != NULL)
429 {
430 Py_DECREF (pvalue);
431 success = true;
432 }
433 else if (PyErr_Occurred ())
434 {
435 PyErr_Print();
436 PyErr_Clear();
437 }
438 }
439 }
440 }
441 }
442 Py_INCREF (script_interpreter_dict);
443 }
444 }
Greg Clayton63094e02010-06-23 01:19:29 +0000445
Caroline Tice4a461da2011-01-14 21:09:29 +0000446 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000447 return true;
448
449 // The one-liner failed. Append the error message.
450 if (result)
451 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
452 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000453 }
Johnny Chen60dde642010-07-30 22:33:14 +0000454
455 if (result)
456 result->AppendError ("empty command passed to python\n");
457 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000458}
459
Chris Lattner24943d22010-06-08 16:52:24 +0000460size_t
461ScriptInterpreterPython::InputReaderCallback
462(
463 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000464 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000465 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000466 const char *bytes,
467 size_t bytes_len
468)
469{
Caroline Tice2ade6112010-11-10 19:18:14 +0000470 lldb::thread_t embedded_interpreter_thread;
471 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
472
Chris Lattner24943d22010-06-08 16:52:24 +0000473 if (baton == NULL)
474 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000475
476 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000477
Caroline Tice0aa2e552011-01-14 00:29:16 +0000478 if (script_interpreter->m_script_lang != eScriptLanguagePython)
479 return 0;
480
Caroline Tice892fadd2011-06-16 16:27:19 +0000481 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
482 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
483
Chris Lattner24943d22010-06-08 16:52:24 +0000484 switch (notification)
485 {
486 case eInputReaderActivate:
487 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000488 if (!batch_mode)
489 {
490 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
491 out_stream->Flush();
492 }
Greg Clayton58928562011-02-09 01:08:52 +0000493
Chris Lattner24943d22010-06-08 16:52:24 +0000494 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000495 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
496 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000497 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000498
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000499 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000500
Caroline Tice202f6b82011-01-17 21:55:19 +0000501 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000502 ScriptInterpreterPython::Locker locker(script_interpreter,
503 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
504 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000505 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000506
Caroline Tice2ade6112010-11-10 19:18:14 +0000507 char error_str[1024];
508 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
509 sizeof(error_str)))
510 {
511 if (log)
512 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
513 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
514 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
515 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
516 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000517 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000518 {
519 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000520 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000521 Error detach_error;
522 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
523 }
524 else
525 {
526 if (log)
527 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
528 reader.SetIsDone (true);
529 }
530 }
531 else
532 {
533 if (log)
534 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
535 reader.SetIsDone (true);
536 }
Chris Lattner24943d22010-06-08 16:52:24 +0000537 }
538 break;
539
540 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000541 // When another input reader is pushed, don't leave the session...
542 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000543 break;
544
545 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000546 {
Greg Claytona1cec242012-01-06 00:47:38 +0000547 // Don't try and acquire the interpreter lock here because code like
548 // this:
549 //
550 // (lldb) script
551 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
552 //
553 // This will cause the process to run. The interpreter lock is taken
554 // by the input reader for the "script" command. If we try and acquire
555 // the lock here, when the process runs it might deactivate this input
556 // reader (if STDIN is hooked up to the inferior process) and
557 // reactivate it when the process stops which will deadlock.
558 //ScriptInterpreterPython::Locker locker(script_interpreter,
559 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
560 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000561 }
Chris Lattner24943d22010-06-08 16:52:24 +0000562 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000563
Caroline Tice4a348082011-05-02 20:41:46 +0000564 case eInputReaderAsynchronousOutputWritten:
565 break;
566
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000567 case eInputReaderInterrupt:
568 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
569 break;
570
571 case eInputReaderEndOfFile:
572 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
573 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000574
575 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000576 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000577 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000578 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000579 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000580 bytes_len);
581 if (bytes && bytes_len)
582 {
583 if ((int) bytes[0] == 4)
584 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
585 else
586 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
587 }
588 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000589 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000590 else
591 {
592 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000593 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000594 bytes,
595 bytes_len);
596 reader.SetIsDone (true);
597 }
598
Chris Lattner24943d22010-06-08 16:52:24 +0000599 break;
600
601 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000602 script_interpreter->LeaveSession ();
603
Chris Lattner24943d22010-06-08 16:52:24 +0000604 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000605 if (log)
606 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000607
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000608 script_interpreter->RestoreTerminalState ();
609
Caroline Tice2ade6112010-11-10 19:18:14 +0000610 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000611 break;
612 }
613
614 return bytes_len;
615}
616
617
618void
Greg Clayton238c0a12010-09-18 01:14:36 +0000619ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000620{
621 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
622
Caroline Tice0aa2e552011-01-14 00:29:16 +0000623 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000624
625 // At the moment, the only time the debugger does not have an input file handle is when this is called
626 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
627 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
628 // do it.
629
Greg Clayton58928562011-02-09 01:08:52 +0000630 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000631 return;
632
Greg Clayton63094e02010-06-23 01:19:29 +0000633 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000634 if (reader_sp)
635 {
636 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
637 this, // baton
638 eInputReaderGranularityLine, // token size, to pass to callback function
639 NULL, // end token
640 NULL, // prompt
641 true)); // echo input
642
643 if (error.Success())
644 {
Greg Clayton63094e02010-06-23 01:19:29 +0000645 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000646 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000647 }
648 }
649}
650
651bool
652ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000653 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000654 void *ret_value)
655{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000656
Enrico Granatafa1f6172011-10-24 17:22:21 +0000657 Locker locker(this,
658 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
659 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000660
Chris Lattner24943d22010-06-08 16:52:24 +0000661 PyObject *py_return = NULL;
662 PyObject *mainmod = PyImport_AddModule ("__main__");
663 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000664 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000665 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000666 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000667 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000668 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000669
670 if (PyDict_Check (globals))
671 {
672 PyObject *key, *value;
673 Py_ssize_t pos = 0;
674
675 int i = 0;
676 while (PyDict_Next (globals, &pos, &key, &value))
677 {
678 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
679 // so that Python's garbage collector doesn't collect them out from under us.
680 Py_INCREF (key);
681 Py_INCREF (value);
682 char *c_str = PyString_AsString (key);
683 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
684 locals = value;
685 ++i;
686 }
687 }
Chris Lattner24943d22010-06-08 16:52:24 +0000688
Caroline Tice0aa2e552011-01-14 00:29:16 +0000689 if (locals == NULL)
690 {
691 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
692 should_decrement_locals = true;
693 }
694
695 if (locals == NULL)
696 {
697 locals = globals;
698 should_decrement_locals = false;
699 }
700
701 py_error = PyErr_Occurred();
702 if (py_error != NULL)
703 PyErr_Clear();
704
Chris Lattner24943d22010-06-08 16:52:24 +0000705 if (in_string != NULL)
706 {
707 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
708 if (py_return == NULL)
709 {
710 py_error = PyErr_Occurred ();
711 if (py_error != NULL)
712 PyErr_Clear ();
713
714 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
715 }
716
Caroline Tice0aa2e552011-01-14 00:29:16 +0000717 if (locals != NULL
718 && should_decrement_locals)
719 Py_DECREF (locals);
720
Chris Lattner24943d22010-06-08 16:52:24 +0000721 if (py_return != NULL)
722 {
723 switch (return_type)
724 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000725 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000726 {
727 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000728 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000729 break;
730 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000731 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000732 {
733 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000734 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000735 break;
736 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000737 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000738 {
739 const char format[2] = "b";
740 success = PyArg_Parse (py_return, format, (bool *) ret_value);
741 break;
742 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000743 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000744 {
745 const char format[2] = "h";
746 success = PyArg_Parse (py_return, format, (short *) ret_value);
747 break;
748 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000749 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000750 {
751 const char format[2] = "H";
752 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
753 break;
754 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000755 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000756 {
757 const char format[2] = "i";
758 success = PyArg_Parse (py_return, format, (int *) ret_value);
759 break;
760 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000761 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000762 {
763 const char format[2] = "I";
764 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
765 break;
766 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000767 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000768 {
769 const char format[2] = "l";
770 success = PyArg_Parse (py_return, format, (long *) ret_value);
771 break;
772 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000773 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000774 {
775 const char format[2] = "k";
776 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
777 break;
778 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000779 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000780 {
781 const char format[2] = "L";
782 success = PyArg_Parse (py_return, format, (long long *) ret_value);
783 break;
784 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000785 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000786 {
787 const char format[2] = "K";
788 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
789 break;
790 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000791 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000792 {
793 const char format[2] = "f";
794 success = PyArg_Parse (py_return, format, (float *) ret_value);
795 break;
796 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000797 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000798 {
799 const char format[2] = "d";
800 success = PyArg_Parse (py_return, format, (double *) ret_value);
801 break;
802 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000803 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000804 {
805 const char format[2] = "c";
806 success = PyArg_Parse (py_return, format, (char *) ret_value);
807 break;
808 }
809 default:
810 {}
811 }
812 Py_DECREF (py_return);
813 if (success)
814 ret_success = true;
815 else
816 ret_success = false;
817 }
818 }
819
820 py_error = PyErr_Occurred();
821 if (py_error != NULL)
822 {
823 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
824 PyErr_Print ();
825 PyErr_Clear();
826 ret_success = false;
827 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000828
Chris Lattner24943d22010-06-08 16:52:24 +0000829 return ret_success;
830}
831
832bool
833ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
834{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000835
836
837 Locker locker(this,
838 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
839 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000840
Chris Lattner24943d22010-06-08 16:52:24 +0000841 bool success = false;
842 PyObject *py_return = NULL;
843 PyObject *mainmod = PyImport_AddModule ("__main__");
844 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000845 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000846 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000847 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000848
Caroline Tice0aa2e552011-01-14 00:29:16 +0000849 if (PyDict_Check (globals))
850 {
851 PyObject *key, *value;
852 Py_ssize_t pos = 0;
853
854 while (PyDict_Next (globals, &pos, &key, &value))
855 {
856 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
857 // so that Python's garbage collector doesn't collect them out from under us.
858 Py_INCREF (key);
859 Py_INCREF (value);
860 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
861 locals = value;
862 }
863 }
864
865 if (locals == NULL)
866 {
867 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
868 should_decrement_locals = true;
869 }
870
871 if (locals == NULL)
872 {
873 locals = globals;
874 should_decrement_locals = false;
875 }
876
877 py_error = PyErr_Occurred();
878 if (py_error != NULL)
879 PyErr_Clear();
880
Chris Lattner24943d22010-06-08 16:52:24 +0000881 if (in_string != NULL)
882 {
883 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
884 if (compiled_node)
885 {
886 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
887 if (compiled_code)
888 {
889 py_return = PyEval_EvalCode (compiled_code, globals, locals);
890 if (py_return != NULL)
891 {
892 success = true;
893 Py_DECREF (py_return);
894 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000895 if (locals && should_decrement_locals)
896 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000897 }
898 }
899 }
900
901 py_error = PyErr_Occurred ();
902 if (py_error != NULL)
903 {
904 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
905 PyErr_Print ();
906 PyErr_Clear();
907 success = false;
908 }
909
910 return success;
911}
912
913static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
914
915size_t
916ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
917(
918 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000919 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000920 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000921 const char *bytes,
922 size_t bytes_len
923)
924{
Caroline Tice892fadd2011-06-16 16:27:19 +0000925 static StringList commands_in_progress;
926
927 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
928 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
929
Chris Lattner24943d22010-06-08 16:52:24 +0000930 switch (notification)
931 {
932 case eInputReaderActivate:
933 {
934 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +0000935 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +0000936 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000937 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000938 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +0000939 out_stream->Printf ("%s", reader.GetPrompt());
940 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +0000941 }
942 }
943 break;
944
945 case eInputReaderDeactivate:
946 break;
947
948 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +0000949 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000950 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000951 out_stream->Printf ("%s", reader.GetPrompt());
952 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +0000953 }
Chris Lattner24943d22010-06-08 16:52:24 +0000954 break;
955
Caroline Tice4a348082011-05-02 20:41:46 +0000956 case eInputReaderAsynchronousOutputWritten:
957 break;
958
Chris Lattner24943d22010-06-08 16:52:24 +0000959 case eInputReaderGotToken:
960 {
961 std::string temp_string (bytes, bytes_len);
962 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +0000963 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000964 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000965 out_stream->Printf ("%s", reader.GetPrompt());
966 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +0000967 }
Chris Lattner24943d22010-06-08 16:52:24 +0000968 }
969 break;
970
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000971 case eInputReaderEndOfFile:
972 case eInputReaderInterrupt:
973 // Control-c (SIGINT) & control-d both mean finish & exit.
974 reader.SetIsDone(true);
975
976 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
977 if (notification == eInputReaderInterrupt)
978 commands_in_progress.Clear();
979
980 // Fall through here...
981
Chris Lattner24943d22010-06-08 16:52:24 +0000982 case eInputReaderDone:
983 {
984 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
985 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
986 data_ap->user_source.AppendList (commands_in_progress);
987 if (data_ap.get())
988 {
Greg Clayton63094e02010-06-23 01:19:29 +0000989 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +0000990 if (interpreter)
991 {
992 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
993 data_ap->script_source))
994 {
995 if (data_ap->script_source.GetSize() == 1)
996 {
997 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
998 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
999 }
1000 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001001 else if (!batch_mode)
1002 {
1003 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1004 out_stream->Flush();
1005 }
Chris Lattner24943d22010-06-08 16:52:24 +00001006 }
1007 else
1008 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001009 if (!batch_mode)
1010 {
1011 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1012 out_stream->Flush();
1013 }
Chris Lattner24943d22010-06-08 16:52:24 +00001014 }
1015 }
1016 }
1017 break;
1018
1019 }
1020
1021 return bytes_len;
1022}
1023
1024void
Greg Clayton238c0a12010-09-18 01:14:36 +00001025ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001026 CommandReturnObject &result)
1027{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001028 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1029
Greg Clayton63094e02010-06-23 01:19:29 +00001030 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001031
1032 if (reader_sp)
1033 {
1034 Error err = reader_sp->Initialize (
1035 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1036 bp_options, // baton
1037 eInputReaderGranularityLine, // token size, for feeding data to callback function
1038 "DONE", // end token
1039 "> ", // prompt
1040 true); // echo input
1041
1042 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001043 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001044 else
1045 {
1046 result.AppendError (err.AsCString());
1047 result.SetStatus (eReturnStatusFailed);
1048 }
1049 }
1050 else
1051 {
1052 result.AppendError("out of memory");
1053 result.SetStatus (eReturnStatusFailed);
1054 }
1055}
1056
Johnny Chen3e0571b2010-09-11 00:23:59 +00001057// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001058void
Greg Clayton238c0a12010-09-18 01:14:36 +00001059ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001060 const char *oneliner)
1061{
1062 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1063
1064 // It's necessary to set both user_source and script_source to the oneliner.
1065 // The former is used to generate callback description (as in breakpoint command list)
1066 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001067
Johnny Chend1c2dca2010-09-10 18:21:10 +00001068 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001069
Caroline Tice5136f942010-09-27 21:35:15 +00001070 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1071 {
1072 if (data_ap->script_source.GetSize() == 1)
1073 {
1074 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1075 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1076 }
1077 }
1078
Johnny Chend1c2dca2010-09-10 18:21:10 +00001079 return;
1080}
1081
Chris Lattner24943d22010-06-08 16:52:24 +00001082bool
1083ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1084{
1085 // Convert StringList to one long, newline delimited, const char *.
1086 std::string function_def_string;
1087
1088 int num_lines = function_def.GetSize();
1089
1090 for (int i = 0; i < num_lines; ++i)
1091 {
1092 function_def_string.append (function_def.GetStringAtIndex(i));
1093 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1094 function_def_string.append ("\n");
1095
1096 }
1097
1098 return ExecuteMultipleLines (function_def_string.c_str());
1099}
1100
Enrico Granataf7a9b142011-07-15 02:26:42 +00001101// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1102// use this code to generate their functions
1103bool
1104ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1105{
1106 int num_lines = input.GetSize ();
1107 if (num_lines == 0)
1108 return false;
1109 StreamString sstr;
1110 StringList auto_generated_function;
1111 auto_generated_function.AppendString (signature.c_str());
1112 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1113 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1114 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1115 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1116 // global dictionary.
1117
1118 // Wrap everything up inside the function, increasing the indentation.
1119
1120 for (int i = 0; i < num_lines; ++i)
1121 {
1122 sstr.Clear ();
1123 sstr.Printf (" %s", input.GetStringAtIndex (i));
1124 auto_generated_function.AppendString (sstr.GetData());
1125 }
1126 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1127 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1128 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1129 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1130
1131 // Verify that the results are valid Python.
1132
1133 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1134 return false;
1135
1136 return true;
1137
1138}
1139
1140// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1141// given to generated functions, of course)
1142bool
1143ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output)
1144{
1145 static int num_created_functions = 0;
1146 user_input.RemoveBlankLines ();
1147 int num_lines = user_input.GetSize ();
1148 StreamString sstr;
1149
1150 // Check to see if we have any data; if not, just return.
1151 if (user_input.GetSize() == 0)
1152 return false;
1153
1154 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1155 // ValueObject as parameter to the function.
1156
1157 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1158 ++num_created_functions;
1159 std::string auto_generated_function_name = sstr.GetData();
1160
1161 sstr.Clear();
1162 StringList auto_generated_function;
1163
1164 // Create the function name & definition string.
1165
1166 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1167 auto_generated_function.AppendString (sstr.GetData());
1168
1169 // Pre-pend code for setting up the session dictionary.
1170
1171 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1172 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1173 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1174 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1175 // global dictionary.
1176
1177 // Wrap everything up inside the function, increasing the indentation.
1178
1179 for (int i = 0; i < num_lines; ++i)
1180 {
1181 sstr.Clear ();
1182 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1183 auto_generated_function.AppendString (sstr.GetData());
1184 }
1185
1186 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1187 // got written to the values in the global dictionary, not the session dictionary).
1188
1189 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1190 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1191 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1192 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1193
1194 // Verify that the results are valid Python.
1195
1196 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1197 return false;
1198
1199 // Store the name of the auto-generated function to be called.
1200
1201 output.AppendString (auto_generated_function_name.c_str());
1202 return true;
1203}
1204
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001205bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001206ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, StringList &output)
1207{
1208 static int num_created_functions = 0;
1209 user_input.RemoveBlankLines ();
1210 int num_lines = user_input.GetSize ();
1211 StreamString sstr;
1212
1213 // Check to see if we have any data; if not, just return.
1214 if (user_input.GetSize() == 0)
1215 return false;
1216
1217 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
Enrico Granatafa1f6172011-10-24 17:22:21 +00001218 // required data as parameters to the function.
Enrico Granatac2a28252011-08-16 16:49:25 +00001219
1220 sstr.Printf ("lldb_autogen_python_cmd_alias_func_%d", num_created_functions);
1221 ++num_created_functions;
1222 std::string auto_generated_function_name = sstr.GetData();
1223
1224 sstr.Clear();
1225 StringList auto_generated_function;
1226
1227 // Create the function name & definition string.
1228
Enrico Granata271568f2011-09-09 01:41:30 +00001229 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001230 auto_generated_function.AppendString (sstr.GetData());
1231
1232 // Pre-pend code for setting up the session dictionary.
1233
1234 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1235 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1236 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1237 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1238 // global dictionary.
1239
1240 // Wrap everything up inside the function, increasing the indentation.
1241
1242 for (int i = 0; i < num_lines; ++i)
1243 {
1244 sstr.Clear ();
1245 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1246 auto_generated_function.AppendString (sstr.GetData());
1247 }
1248
1249 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1250 // got written to the values in the global dictionary, not the session dictionary).
1251
1252 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1253 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1254 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1255 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1256
1257 // Verify that the results are valid Python.
1258
1259 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1260 return false;
1261
1262 // Store the name of the auto-generated function to be called.
1263
1264 output.AppendString (auto_generated_function_name.c_str());
1265 return true;
1266}
1267
1268
1269bool
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001270ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output)
1271{
1272 static int num_created_classes = 0;
1273 user_input.RemoveBlankLines ();
1274 int num_lines = user_input.GetSize ();
1275 StreamString sstr;
1276
1277 // Check to see if we have any data; if not, just return.
1278 if (user_input.GetSize() == 0)
1279 return false;
1280
1281 // Wrap all user input into a Python class
1282
1283 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1284 ++num_created_classes;
1285 std::string auto_generated_class_name = sstr.GetData();
1286
1287 sstr.Clear();
1288 StringList auto_generated_class;
1289
1290 // Create the function name & definition string.
1291
1292 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1293 auto_generated_class.AppendString (sstr.GetData());
1294
1295 // Wrap everything up inside the class, 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_class.AppendString (sstr.GetData());
1302 }
1303
1304
1305 // Verify that the results are valid Python.
1306 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1307 // (TODO: rename that method to ExportDefinitionToInterpreter)
1308 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1309 return false;
1310
1311 // Store the name of the auto-generated class
1312
1313 output.AppendString (auto_generated_class_name.c_str());
1314 return true;
1315}
1316
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001317void*
1318ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1319 lldb::ValueObjectSP valobj)
1320{
1321 if (class_name.empty())
1322 return NULL;
1323
1324 if (!valobj.get())
1325 return NULL;
1326
Enrico Granata979e20d2011-07-29 19:53:35 +00001327 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001328
1329 if (!target)
1330 return NULL;
1331
1332 Debugger &debugger = target->GetDebugger();
1333 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1334 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1335
1336 if (!script_interpreter)
1337 return NULL;
1338
1339 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001340
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001341 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001342 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001343 ret_val = g_swig_synthetic_script (class_name,
1344 python_interpreter->m_dictionary_name.c_str(),
1345 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001346 }
1347
1348 return ret_val;
1349}
1350
Enrico Granataf7a9b142011-07-15 02:26:42 +00001351bool
1352ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output)
1353{
1354 StringList input(oneliner);
1355 return GenerateTypeScriptFunction(input, output);
1356}
1357
Chris Lattner24943d22010-06-08 16:52:24 +00001358bool
1359ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1360{
1361 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001362 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001363 int num_lines = user_input.GetSize ();
1364 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001365
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001366 // Check to see if we have any data; if not, just return.
1367 if (user_input.GetSize() == 0)
1368 return false;
1369
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001370 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1371 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001372
Caroline Ticeb447e842010-09-21 19:25:28 +00001373
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001374 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1375 ++num_created_functions;
1376 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001377
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001378 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001379 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001380
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001381 // Create the function name & definition string.
1382
Caroline Tice0aa2e552011-01-14 00:29:16 +00001383 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001384 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001385
1386 // Pre-pend code for setting up the session dictionary.
1387
1388 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1389 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1390 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1391 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1392 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001393
1394 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001395
1396 for (int i = 0; i < num_lines; ++i)
1397 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001398 sstr.Clear ();
1399 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1400 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001401 }
Chris Lattner24943d22010-06-08 16:52:24 +00001402
Caroline Tice0aa2e552011-01-14 00:29:16 +00001403 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1404 // got written to the values in the global dictionary, not the session dictionary).
1405
1406 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1407 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1408 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1409 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1410
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001411 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001412
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001413 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001414 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001415 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001416 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001417
1418 // Store the name of the auto-generated function to be called.
1419
1420 callback_data.AppendString (auto_generated_function_name.c_str());
1421 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001422}
1423
Enrico Granataf7a9b142011-07-15 02:26:42 +00001424std::string
1425ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1426 lldb::ValueObjectSP valobj)
1427{
1428
1429 if (!python_function_name || !(*python_function_name))
1430 return "<no function>";
1431
1432 if (!valobj.get())
1433 return "<no object>";
1434
Enrico Granata979e20d2011-07-29 19:53:35 +00001435 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001436
1437 if (!target)
1438 return "<no target>";
1439
1440 Debugger &debugger = target->GetDebugger();
1441 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1442 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1443
1444 if (!script_interpreter)
1445 return "<no python>";
1446
1447 std::string ret_val;
1448
1449 if (python_function_name
1450 && *python_function_name)
1451 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001452 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001453 Locker py_lock(python_interpreter);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001454 ret_val = g_swig_typescript_callback (python_function_name,
1455 python_interpreter->m_dictionary_name.c_str(),
1456 valobj);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001457 }
1458 }
1459 else
1460 return "<no function name>";
1461
1462 return ret_val;
1463
1464}
1465
Greg Clayton5144f382010-10-07 17:14:24 +00001466bool
1467ScriptInterpreterPython::BreakpointCallbackFunction
1468(
1469 void *baton,
1470 StoppointCallbackContext *context,
1471 user_id_t break_id,
1472 user_id_t break_loc_id
1473)
1474{
1475 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1476 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001477
1478 if (!context)
1479 return true;
1480
Greg Clayton567e7f32011-09-22 04:58:26 +00001481 Target *target = context->exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001482
1483 if (!target)
1484 return true;
1485
1486 Debugger &debugger = target->GetDebugger();
1487 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1488 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1489
1490 if (!script_interpreter)
1491 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001492
1493 if (python_function_name != NULL
1494 && python_function_name[0] != '\0')
1495 {
Greg Clayton567e7f32011-09-22 04:58:26 +00001496 const StackFrameSP stop_frame_sp (context->exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001497 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001498 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001499 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001500 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1501
1502 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001503 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001504 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001505 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001506 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001507 ret_val = g_swig_breakpoint_callback (python_function_name,
1508 python_interpreter->m_dictionary_name.c_str(),
1509 stop_frame_sp,
1510 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001511 }
1512 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001513 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001514 }
Greg Clayton5144f382010-10-07 17:14:24 +00001515 }
1516 // We currently always true so we stop in case anything goes wrong when
1517 // trying to call the script function
1518 return true;
1519}
Caroline Tice2ade6112010-11-10 19:18:14 +00001520
1521lldb::thread_result_t
1522ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1523{
1524 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1525
1526 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1527
1528 if (log)
1529 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1530
1531 char error_str[1024];
1532 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001533
Enrico Granatafa1f6172011-10-24 17:22:21 +00001534 Locker locker(script_interpreter,
1535 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1536 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1537
1538 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001539 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001540 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001541
Caroline Tice0aa2e552011-01-14 00:29:16 +00001542 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1543 PyRun_SimpleString (run_string.GetData());
1544 run_string.Clear ();
1545
1546 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1547 PyRun_SimpleString (run_string.GetData());
1548 run_string.Clear ();
1549
1550 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1551 PyRun_SimpleString (run_string.GetData());
1552 run_string.Clear ();
1553
1554 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1555 pty_slave_name);
1556 PyRun_SimpleString (run_string.GetData());
1557 run_string.Clear ();
1558
Johnny Chen8054ba32011-03-11 00:28:50 +00001559 // The following call drops into the embedded interpreter loop and stays there until the
1560 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001561
Caroline Ticece207c12011-03-11 00:21:55 +00001562 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001563 // 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 +00001564 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1565
1566 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1567 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1568 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1569 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1570 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1571 // hang (it's happened before).
1572
Caroline Tice9d352ce2011-03-07 23:24:28 +00001573 Py_BEGIN_ALLOW_THREADS
1574 PyGILState_STATE gstate = PyGILState_Ensure();
1575
Caroline Tice0aa2e552011-01-14 00:29:16 +00001576 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1577 PyRun_SimpleString (run_string.GetData());
1578 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001579
Caroline Tice9d352ce2011-03-07 23:24:28 +00001580 PyGILState_Release (gstate);
1581 Py_END_ALLOW_THREADS
1582
Caroline Tice0aa2e552011-01-14 00:29:16 +00001583 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1584 PyRun_SimpleString (run_string.GetData());
1585 run_string.Clear();
1586
1587 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1588 PyRun_SimpleString (run_string.GetData());
1589 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001590
Caroline Tice2ade6112010-11-10 19:18:14 +00001591 }
1592
1593 if (script_interpreter->m_embedded_thread_input_reader_sp)
1594 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1595
1596 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001597
Caroline Tice2ade6112010-11-10 19:18:14 +00001598 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1599 if (log)
1600 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1601
1602
Johnny Chen8054ba32011-03-11 00:28:50 +00001603 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001604 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001605 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1606 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1607 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001608
Caroline Tice2ade6112010-11-10 19:18:14 +00001609 return NULL;
1610}
1611
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001612uint32_t
1613ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1614{
1615 if (!implementor)
1616 return 0;
1617
1618 if (!g_swig_calc_children)
1619 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001620
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001621 uint32_t ret_val = 0;
1622
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001623 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001624 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001625 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001626 }
1627
1628 return ret_val;
1629}
1630
Enrico Granata91544802011-09-06 19:20:51 +00001631lldb::ValueObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001632ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1633{
1634 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001635 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001636
Enrico Granata91544802011-09-06 19:20:51 +00001637 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1638 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001639
Enrico Granata91544802011-09-06 19:20:51 +00001640 void* child_ptr = NULL;
1641 lldb::SBValue* value_sb = NULL;
1642 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001643
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001644 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001645 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +00001646 child_ptr = g_swig_get_child_index (implementor,idx);
1647 if (child_ptr != NULL && child_ptr != Py_None)
1648 {
1649 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1650 if (value_sb == NULL)
1651 Py_XDECREF(child_ptr);
1652 else
1653 ret_val = value_sb->get_sp();
1654 }
1655 else
1656 {
1657 Py_XDECREF(child_ptr);
1658 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001659 }
1660
1661 return ret_val;
1662}
1663
1664int
1665ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1666{
1667 if (!implementor)
1668 return UINT32_MAX;
1669
1670 if (!g_swig_get_index_child)
1671 return UINT32_MAX;
1672
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001673 int ret_val = UINT32_MAX;
1674
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001675 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001676 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001677 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001678 }
1679
1680 return ret_val;
1681}
1682
Enrico Granata979e20d2011-07-29 19:53:35 +00001683void
1684ScriptInterpreterPython::UpdateSynthProviderInstance (void* implementor)
1685{
1686 if (!implementor)
1687 return;
1688
1689 if (!g_swig_update_provider)
1690 return;
1691
Enrico Granata979e20d2011-07-29 19:53:35 +00001692 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001693 Locker py_lock(this);
Enrico Granata979e20d2011-07-29 19:53:35 +00001694 g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001695 }
1696
1697 return;
1698}
1699
Enrico Granatac2a28252011-08-16 16:49:25 +00001700bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001701ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00001702 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00001703 lldb_private::Error& error)
1704{
1705 if (!pathname || !pathname[0])
1706 {
1707 error.SetErrorString("invalid pathname");
1708 return false;
1709 }
1710
1711 if (!g_swig_call_module_init)
1712 {
1713 error.SetErrorString("internal helper function missing");
1714 return false;
1715 }
1716
Greg Clayton13d24fb2012-01-29 20:56:30 +00001717 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granatafa1f6172011-10-24 17:22:21 +00001718
Enrico Granata59df36f2011-10-17 21:45:27 +00001719 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001720 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00001721
1722 FileSpec target_file(pathname, true);
1723
1724 // TODO: would we want to reject any other value?
1725 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1726 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1727 {
1728 error.SetErrorString("invalid pathname");
1729 return false;
1730 }
1731
1732 const char* directory = target_file.GetDirectory().GetCString();
1733 std::string basename(target_file.GetFilename().GetCString());
1734
1735 // now make sure that Python has "directory" in the search path
1736 StreamString command_stream;
1737 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1738 directory,
1739 directory);
Enrico Granatafa1f6172011-10-24 17:22:21 +00001740 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData());
Enrico Granata59df36f2011-10-17 21:45:27 +00001741 if (!syspath_retval)
1742 {
1743 error.SetErrorString("Python sys.path handling failed");
1744 return false;
1745 }
1746
1747 // strip .py or .pyc extension
1748 ConstString extension = target_file.GetFileNameExtension();
1749 if (::strcmp(extension.GetCString(), "py") == 0)
1750 basename.resize(basename.length()-3);
1751 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1752 basename.resize(basename.length()-4);
1753
1754 // check if the module is already import-ed
1755 command_stream.Clear();
1756 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1757 int refcount = 0;
1758 // this call will fail if the module does not exist (because the parameter to it is not a string
1759 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00001760 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
1761 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0);
1762 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00001763 {
1764 error.SetErrorString("module already imported");
1765 return false;
1766 }
1767
1768 // now actually do the import
1769 command_stream.Clear();
1770 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafa1f6172011-10-24 17:22:21 +00001771 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL);
Enrico Granata59df36f2011-10-17 21:45:27 +00001772 if (!import_retval)
1773 {
1774 error.SetErrorString("Python import statement failed");
1775 return false;
1776 }
1777
1778 // call __lldb_module_init(debugger,dict)
1779 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001780 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001781 debugger_sp))
1782 {
1783 error.SetErrorString("calling __lldb_module_init failed");
1784 return false;
1785 }
1786 return true;
1787 }
1788}
1789
Enrico Granata6010ace2011-11-07 22:57:04 +00001790ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
1791 ScriptedCommandSynchronicity synchro) :
1792 m_debugger_sp(debugger_sp),
1793 m_synch_wanted(synchro),
1794 m_old_asynch(debugger_sp->GetAsyncExecution())
1795{
1796 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
1797 m_debugger_sp->SetAsyncExecution(false);
1798 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
1799 m_debugger_sp->SetAsyncExecution(true);
1800}
1801
1802ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
1803{
1804 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
1805 m_debugger_sp->SetAsyncExecution(m_old_asynch);
1806}
1807
Enrico Granata59df36f2011-10-17 21:45:27 +00001808bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001809ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1810 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00001811 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001812 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001813 Error& error)
1814{
1815 if (!impl_function)
1816 {
1817 error.SetErrorString("no function to execute");
1818 return false;
1819 }
1820
1821 if (!g_swig_call_command)
1822 {
1823 error.SetErrorString("no helper function to run scripted commands");
1824 return false;
1825 }
1826
Greg Clayton13d24fb2012-01-29 20:56:30 +00001827 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata6010ace2011-11-07 22:57:04 +00001828
1829 if (!debugger_sp.get())
1830 {
1831 error.SetErrorString("invalid Debugger pointer");
1832 return false;
1833 }
Enrico Granatac2a28252011-08-16 16:49:25 +00001834
1835 bool ret_val;
1836
1837 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00001838
Enrico Granatac2a28252011-08-16 16:49:25 +00001839 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001840 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00001841 SynchronicityHandler synch_handler(debugger_sp,
1842 synchronicity);
1843
Enrico Granatac2a28252011-08-16 16:49:25 +00001844 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001845 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00001846 debugger_sp,
1847 args,
1848 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001849 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001850 }
Enrico Granata6010ace2011-11-07 22:57:04 +00001851
Enrico Granatac2a28252011-08-16 16:49:25 +00001852 if (!ret_val)
1853 error.SetErrorString(err_msg.c_str());
1854 else
1855 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00001856
Enrico Granatac2a28252011-08-16 16:49:25 +00001857 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00001858}
1859
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001860// in Python, a special attribute __doc__ contains the docstring
1861// for an object (function, method, class, ...) if any is defined
1862// Otherwise, the attribute's value is None
1863std::string
1864ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1865{
1866 std::string command(item);
1867 command += ".__doc__";
1868
1869 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1870
1871 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001872 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001873 &result_ptr) && result_ptr)
1874 {
1875 return std::string(result_ptr);
1876 }
1877 else
1878 return std::string("");
1879}
Caroline Tice2ade6112010-11-10 19:18:14 +00001880
Caroline Tice0aa2e552011-01-14 00:29:16 +00001881void
Greg Claytone86cbb92011-03-22 01:14:58 +00001882ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00001883 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001884 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
1885 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
1886 SWIGPythonCalculateNumChildren python_swig_calc_children,
1887 SWIGPythonGetChildAtIndex python_swig_get_child_index,
1888 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
Enrico Granata979e20d2011-07-29 19:53:35 +00001889 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue,
Enrico Granatac2a28252011-08-16 16:49:25 +00001890 SWIGPythonUpdateSynthProviderInstance python_swig_update_provider,
Enrico Granata59df36f2011-10-17 21:45:27 +00001891 SWIGPythonCallCommand python_swig_call_command,
1892 SWIGPythonCallModuleInit python_swig_call_mod_init)
Greg Claytone86cbb92011-03-22 01:14:58 +00001893{
1894 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001895 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1896 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001897 g_swig_synthetic_script = python_swig_synthetic_script;
1898 g_swig_calc_children = python_swig_calc_children;
1899 g_swig_get_child_index = python_swig_get_child_index;
1900 g_swig_get_index_child = python_swig_get_index_child;
1901 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Enrico Granata979e20d2011-07-29 19:53:35 +00001902 g_swig_update_provider = python_swig_update_provider;
Enrico Granatac2a28252011-08-16 16:49:25 +00001903 g_swig_call_command = python_swig_call_command;
Enrico Granata59df36f2011-10-17 21:45:27 +00001904 g_swig_call_module_init = python_swig_call_mod_init;
Greg Claytone86cbb92011-03-22 01:14:58 +00001905}
1906
1907void
1908ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001909{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001910 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1911
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001912 // Python will muck with STDIN terminal state, so save off any current TTY
1913 // settings so we can restore them.
1914 TerminalState stdin_tty_state;
1915 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001916
Caroline Tice9d352ce2011-03-07 23:24:28 +00001917 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001918 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001919
Greg Claytone86cbb92011-03-22 01:14:58 +00001920 // Initialize SWIG after setting up python
1921 assert (g_swig_init_callback != NULL);
1922 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001923
1924 // Update the path python uses to search for modules to include the current directory.
1925
Caroline Ticed4d92832011-06-13 21:33:00 +00001926 PyRun_SimpleString ("import sys");
1927 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001928
1929 // Find the module that owns this code and use that path we get to
1930 // set the sys.path appropriately.
1931
1932 FileSpec file_spec;
1933 char python_dir_path[PATH_MAX];
1934 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1935 {
1936 std::string python_path("sys.path.insert(0,\"");
1937 size_t orig_len = python_path.length();
1938 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1939 {
1940 python_path.append (python_dir_path);
1941 python_path.append ("\")");
1942 PyRun_SimpleString (python_path.c_str());
1943 python_path.resize (orig_len);
1944 }
1945
1946 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1947 {
1948 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1949 {
1950 python_path.append (python_dir_path);
1951 python_path.append ("\")");
1952 PyRun_SimpleString (python_path.c_str());
1953 python_path.resize (orig_len);
1954 }
1955 }
1956 }
1957
Jim Ingham4dfa5112011-08-22 19:10:09 +00001958 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001959
Caroline Ticed4d92832011-06-13 21:33:00 +00001960 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001961
Caroline Ticed4d92832011-06-13 21:33:00 +00001962 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1963 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00001964 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001965
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001966 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001967}
1968
Greg Claytone86cbb92011-03-22 01:14:58 +00001969//void
1970//ScriptInterpreterPython::Terminate ()
1971//{
1972// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1973// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1974// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1975// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1976// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1977// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1978// // within Py_Finalize, which results in a seg fault.
1979// //
1980// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1981// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1982// // process exits).
1983// //
1984//// Py_Finalize ();
1985//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00001986
1987#endif // #ifdef LLDB_DISABLE_PYTHON