blob: 691e0d5ae313d7fcaa8510c82e48d5cae96f98ed [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();
211 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
212 PyRun_SimpleString (run_string.GetData());
213
214 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
215 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
216 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
217 // call to Debugger::Terminate is made, the ref-count has the correct value.
218 //
219 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
220 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000221
Caroline Tice0aa2e552011-01-14 00:29:16 +0000222 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000223
Caroline Tice0aa2e552011-01-14 00:29:16 +0000224 run_string.Clear();
225 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
226 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000227
Caroline Tice0aa2e552011-01-14 00:29:16 +0000228 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000229
Caroline Tice0aa2e552011-01-14 00:29:16 +0000230 if (new_count > old_count)
231 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000232
Caroline Tice0aa2e552011-01-14 00:29:16 +0000233 run_string.Clear();
234 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
235 PyRun_SimpleString (run_string.GetData());
236
237 run_string.Clear();
Enrico Granata59df36f2011-10-17 21:45:27 +0000238 run_string.Printf ("run_one_line (%s, 'import os')", m_dictionary_name.c_str());
239 PyRun_SimpleString (run_string.GetData());
240
241 run_string.Clear();
Greg Clayton444e35b2011-10-19 18:09:39 +0000242 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000243 interpreter.GetDebugger().GetID());
244 PyRun_SimpleString (run_string.GetData());
245
Enrico Granata074e3b62011-08-17 19:07:52 +0000246 run_string.Clear();
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000247 run_string.Printf ("run_one_line (%s, 'import gnu_libstdcpp')", m_dictionary_name.c_str());
Enrico Granata074e3b62011-08-17 19:07:52 +0000248 PyRun_SimpleString (run_string.GetData());
249
Caroline Tice0aa2e552011-01-14 00:29:16 +0000250 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000251 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000252 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000253 }
Chris Lattner24943d22010-06-08 16:52:24 +0000254}
255
256ScriptInterpreterPython::~ScriptInterpreterPython ()
257{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000258 Debugger &debugger = GetCommandInterpreter().GetDebugger();
259
260 if (m_embedded_thread_input_reader_sp.get() != NULL)
261 {
262 m_embedded_thread_input_reader_sp->SetIsDone (true);
263 m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000264 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
265 m_embedded_thread_input_reader_sp.reset();
266 debugger.PopInputReader (reader_sp);
267 }
268
269 if (m_new_sysout)
270 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000271 Locker locker(this,
272 ScriptInterpreterPython::Locker::AcquireLock,
273 ScriptInterpreterPython::Locker::FreeLock);
274 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000275 }
Chris Lattner24943d22010-06-08 16:52:24 +0000276}
277
Caroline Tice0aa2e552011-01-14 00:29:16 +0000278void
279ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
280{
281 if (fh == NULL)
282 return;
283
284 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000285
Enrico Granatafa1f6172011-10-24 17:22:21 +0000286 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +0000287
288 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000289}
290
291void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000292ScriptInterpreterPython::SaveTerminalState (int fd)
293{
294 // Python mucks with the terminal state of STDIN. If we can possibly avoid
295 // this by setting the file handles up correctly prior to entering the
296 // interpreter we should. For now we save and restore the terminal state
297 // on the input file handle.
298 m_terminal_state.Save (fd, false);
299}
300
301void
302ScriptInterpreterPython::RestoreTerminalState ()
303{
304 // Python mucks with the terminal state of STDIN. If we can possibly avoid
305 // this by setting the file handles up correctly prior to entering the
306 // interpreter we should. For now we save and restore the terminal state
307 // on the input file handle.
308 m_terminal_state.Restore();
309}
310
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000311void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000312ScriptInterpreterPython::LeaveSession ()
313{
314 m_session_is_active = false;
315}
316
317void
318ScriptInterpreterPython::EnterSession ()
319{
320 // If we have already entered the session, without having officially 'left' it, then there is no need to
321 // 'enter' it again.
322
323 if (m_session_is_active)
324 return;
325
326 m_session_is_active = true;
327
Caroline Tice202f6b82011-01-17 21:55:19 +0000328 StreamString run_string;
329
Greg Clayton2fecc452012-01-28 02:11:02 +0000330 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %llu", m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
331 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)", GetCommandInterpreter().GetDebugger().GetID());
332 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
333 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
334 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
335 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
336 // Make sure STDIN is closed since when we run this as an embedded
337 // interpreter we don't want someone to call "line = sys.stdin.readline()"
338 // and lock up. We don't have multiple windows and when the interpreter is
339 // embedded we don't know we should be feeding input to the embedded
340 // interpreter or to the python sys.stdin. We also don't want to let python
341 // play with the real stdin from this process, so we need to close it...
342 run_string.PutCString ("; sys.stdin.close()");
343 run_string.PutCString ("')");
Caroline Tice0aa2e552011-01-14 00:29:16 +0000344
Caroline Tice6af65cb2011-05-03 21:21:50 +0000345 PyRun_SimpleString (run_string.GetData());
346 run_string.Clear();
347
Caroline Tice0aa2e552011-01-14 00:29:16 +0000348 PyObject *sysmod = PyImport_AddModule ("sys");
349 PyObject *sysdict = PyModule_GetDict (sysmod);
350
Greg Clayton2fecc452012-01-28 02:11:02 +0000351 if (m_new_sysout && sysmod && sysdict)
352 {
353 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
354 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
355 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000356
357 if (PyErr_Occurred())
358 PyErr_Clear ();
Greg Clayton2fecc452012-01-28 02:11:02 +0000359}
Caroline Tice0aa2e552011-01-14 00:29:16 +0000360
Johnny Chen60dde642010-07-30 22:33:14 +0000361bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000362ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000363{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000364 if (!m_valid_session)
365 return false;
366
Caroline Tice4a461da2011-01-14 21:09:29 +0000367 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
368 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
369 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
370 // method to pass the command string directly down to Python.
371
Enrico Granatafa1f6172011-10-24 17:22:21 +0000372 Locker locker(this,
373 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
374 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000375
376 bool success = false;
377
Greg Clayton63094e02010-06-23 01:19:29 +0000378 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000379 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000380 // Find the correct script interpreter dictionary in the main module.
381 PyObject *main_mod = PyImport_AddModule ("__main__");
382 PyObject *script_interpreter_dict = NULL;
383 if (main_mod != NULL)
384 {
385 PyObject *main_dict = PyModule_GetDict (main_mod);
386 if ((main_dict != NULL)
387 && PyDict_Check (main_dict))
388 {
389 // Go through the main dictionary looking for the correct python script interpreter dictionary
390 PyObject *key, *value;
391 Py_ssize_t pos = 0;
392
393 while (PyDict_Next (main_dict, &pos, &key, &value))
394 {
395 // We have stolen references to the key and value objects in the dictionary; we need to increment
396 // them now so that Python's garbage collector doesn't collect them out from under us.
397 Py_INCREF (key);
398 Py_INCREF (value);
399 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
400 {
401 script_interpreter_dict = value;
402 break;
403 }
404 }
405 }
406
407 if (script_interpreter_dict != NULL)
408 {
409 PyObject *pfunc = NULL;
410 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
411 if (pmod != NULL)
412 {
413 PyObject *pmod_dict = PyModule_GetDict (pmod);
414 if ((pmod_dict != NULL)
415 && PyDict_Check (pmod_dict))
416 {
417 PyObject *key, *value;
418 Py_ssize_t pos = 0;
419
420 while (PyDict_Next (pmod_dict, &pos, &key, &value))
421 {
422 Py_INCREF (key);
423 Py_INCREF (value);
424 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
425 {
426 pfunc = value;
427 break;
428 }
429 }
430
431 PyObject *string_arg = PyString_FromString (command);
432 if (pfunc && string_arg && PyCallable_Check (pfunc))
433 {
434 PyObject *pargs = PyTuple_New (2);
435 if (pargs != NULL)
436 {
437 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
438 PyTuple_SetItem (pargs, 1, string_arg);
439 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
440 Py_DECREF (pargs);
441 if (pvalue != NULL)
442 {
443 Py_DECREF (pvalue);
444 success = true;
445 }
446 else if (PyErr_Occurred ())
447 {
448 PyErr_Print();
449 PyErr_Clear();
450 }
451 }
452 }
453 }
454 }
455 Py_INCREF (script_interpreter_dict);
456 }
457 }
Greg Clayton63094e02010-06-23 01:19:29 +0000458
Caroline Tice4a461da2011-01-14 21:09:29 +0000459 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000460 return true;
461
462 // The one-liner failed. Append the error message.
463 if (result)
464 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
465 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000466 }
Johnny Chen60dde642010-07-30 22:33:14 +0000467
468 if (result)
469 result->AppendError ("empty command passed to python\n");
470 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000471}
472
Chris Lattner24943d22010-06-08 16:52:24 +0000473size_t
474ScriptInterpreterPython::InputReaderCallback
475(
476 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000477 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000478 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000479 const char *bytes,
480 size_t bytes_len
481)
482{
Caroline Tice2ade6112010-11-10 19:18:14 +0000483 lldb::thread_t embedded_interpreter_thread;
484 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
485
Chris Lattner24943d22010-06-08 16:52:24 +0000486 if (baton == NULL)
487 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000488
489 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000490
Caroline Tice0aa2e552011-01-14 00:29:16 +0000491 if (script_interpreter->m_script_lang != eScriptLanguagePython)
492 return 0;
493
Caroline Tice892fadd2011-06-16 16:27:19 +0000494 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
495 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
496
Chris Lattner24943d22010-06-08 16:52:24 +0000497 switch (notification)
498 {
499 case eInputReaderActivate:
500 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000501 if (!batch_mode)
502 {
503 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
504 out_stream->Flush();
505 }
Greg Clayton58928562011-02-09 01:08:52 +0000506
Chris Lattner24943d22010-06-08 16:52:24 +0000507 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000508 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
509 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000510 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000511
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000512 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000513
Caroline Tice202f6b82011-01-17 21:55:19 +0000514 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000515 ScriptInterpreterPython::Locker locker(script_interpreter,
516 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
517 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000518 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000519
Caroline Tice2ade6112010-11-10 19:18:14 +0000520 char error_str[1024];
521 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
522 sizeof(error_str)))
523 {
524 if (log)
525 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
526 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
527 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
528 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
529 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000530 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000531 {
532 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000533 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000534 Error detach_error;
535 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
536 }
537 else
538 {
539 if (log)
540 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
541 reader.SetIsDone (true);
542 }
543 }
544 else
545 {
546 if (log)
547 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
548 reader.SetIsDone (true);
549 }
Chris Lattner24943d22010-06-08 16:52:24 +0000550 }
551 break;
552
553 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000554 // When another input reader is pushed, don't leave the session...
555 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000556 break;
557
558 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000559 {
Greg Claytona1cec242012-01-06 00:47:38 +0000560 // Don't try and acquire the interpreter lock here because code like
561 // this:
562 //
563 // (lldb) script
564 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
565 //
566 // This will cause the process to run. The interpreter lock is taken
567 // by the input reader for the "script" command. If we try and acquire
568 // the lock here, when the process runs it might deactivate this input
569 // reader (if STDIN is hooked up to the inferior process) and
570 // reactivate it when the process stops which will deadlock.
571 //ScriptInterpreterPython::Locker locker(script_interpreter,
572 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
573 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000574 }
Chris Lattner24943d22010-06-08 16:52:24 +0000575 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000576
Caroline Tice4a348082011-05-02 20:41:46 +0000577 case eInputReaderAsynchronousOutputWritten:
578 break;
579
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000580 case eInputReaderInterrupt:
581 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
582 break;
583
584 case eInputReaderEndOfFile:
585 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
586 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000587
588 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000589 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000590 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000591 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000592 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000593 bytes_len);
594 if (bytes && bytes_len)
595 {
596 if ((int) bytes[0] == 4)
597 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
598 else
599 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
600 }
601 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000602 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000603 else
604 {
605 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000606 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000607 bytes,
608 bytes_len);
609 reader.SetIsDone (true);
610 }
611
Chris Lattner24943d22010-06-08 16:52:24 +0000612 break;
613
614 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000615 script_interpreter->LeaveSession ();
616
Chris Lattner24943d22010-06-08 16:52:24 +0000617 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000618 if (log)
619 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000620
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000621 script_interpreter->RestoreTerminalState ();
622
Caroline Tice2ade6112010-11-10 19:18:14 +0000623 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000624 break;
625 }
626
627 return bytes_len;
628}
629
630
631void
Greg Clayton238c0a12010-09-18 01:14:36 +0000632ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000633{
634 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
635
Caroline Tice0aa2e552011-01-14 00:29:16 +0000636 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000637
638 // At the moment, the only time the debugger does not have an input file handle is when this is called
639 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
640 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
641 // do it.
642
Greg Clayton58928562011-02-09 01:08:52 +0000643 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000644 return;
645
Greg Clayton63094e02010-06-23 01:19:29 +0000646 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000647 if (reader_sp)
648 {
649 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
650 this, // baton
651 eInputReaderGranularityLine, // token size, to pass to callback function
652 NULL, // end token
653 NULL, // prompt
654 true)); // echo input
655
656 if (error.Success())
657 {
Greg Clayton63094e02010-06-23 01:19:29 +0000658 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000659 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000660 }
661 }
662}
663
664bool
665ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000666 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000667 void *ret_value)
668{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000669
Enrico Granatafa1f6172011-10-24 17:22:21 +0000670 Locker locker(this,
671 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
672 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000673
Chris Lattner24943d22010-06-08 16:52:24 +0000674 PyObject *py_return = NULL;
675 PyObject *mainmod = PyImport_AddModule ("__main__");
676 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000677 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000678 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000679 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000680 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000681 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000682
683 if (PyDict_Check (globals))
684 {
685 PyObject *key, *value;
686 Py_ssize_t pos = 0;
687
688 int i = 0;
689 while (PyDict_Next (globals, &pos, &key, &value))
690 {
691 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
692 // so that Python's garbage collector doesn't collect them out from under us.
693 Py_INCREF (key);
694 Py_INCREF (value);
695 char *c_str = PyString_AsString (key);
696 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
697 locals = value;
698 ++i;
699 }
700 }
Chris Lattner24943d22010-06-08 16:52:24 +0000701
Caroline Tice0aa2e552011-01-14 00:29:16 +0000702 if (locals == NULL)
703 {
704 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
705 should_decrement_locals = true;
706 }
707
708 if (locals == NULL)
709 {
710 locals = globals;
711 should_decrement_locals = false;
712 }
713
714 py_error = PyErr_Occurred();
715 if (py_error != NULL)
716 PyErr_Clear();
717
Chris Lattner24943d22010-06-08 16:52:24 +0000718 if (in_string != NULL)
719 {
720 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
721 if (py_return == NULL)
722 {
723 py_error = PyErr_Occurred ();
724 if (py_error != NULL)
725 PyErr_Clear ();
726
727 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
728 }
729
Caroline Tice0aa2e552011-01-14 00:29:16 +0000730 if (locals != NULL
731 && should_decrement_locals)
732 Py_DECREF (locals);
733
Chris Lattner24943d22010-06-08 16:52:24 +0000734 if (py_return != NULL)
735 {
736 switch (return_type)
737 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000738 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000739 {
740 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000741 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000742 break;
743 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000744 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000745 {
746 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000747 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000748 break;
749 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000750 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000751 {
752 const char format[2] = "b";
753 success = PyArg_Parse (py_return, format, (bool *) ret_value);
754 break;
755 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000756 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000757 {
758 const char format[2] = "h";
759 success = PyArg_Parse (py_return, format, (short *) ret_value);
760 break;
761 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000762 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000763 {
764 const char format[2] = "H";
765 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
766 break;
767 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000768 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000769 {
770 const char format[2] = "i";
771 success = PyArg_Parse (py_return, format, (int *) ret_value);
772 break;
773 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000774 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000775 {
776 const char format[2] = "I";
777 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
778 break;
779 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000780 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000781 {
782 const char format[2] = "l";
783 success = PyArg_Parse (py_return, format, (long *) ret_value);
784 break;
785 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000786 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000787 {
788 const char format[2] = "k";
789 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
790 break;
791 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000792 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000793 {
794 const char format[2] = "L";
795 success = PyArg_Parse (py_return, format, (long long *) ret_value);
796 break;
797 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000798 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000799 {
800 const char format[2] = "K";
801 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
802 break;
803 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000804 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000805 {
806 const char format[2] = "f";
807 success = PyArg_Parse (py_return, format, (float *) ret_value);
808 break;
809 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000810 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000811 {
812 const char format[2] = "d";
813 success = PyArg_Parse (py_return, format, (double *) ret_value);
814 break;
815 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000816 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000817 {
818 const char format[2] = "c";
819 success = PyArg_Parse (py_return, format, (char *) ret_value);
820 break;
821 }
822 default:
823 {}
824 }
825 Py_DECREF (py_return);
826 if (success)
827 ret_success = true;
828 else
829 ret_success = false;
830 }
831 }
832
833 py_error = PyErr_Occurred();
834 if (py_error != NULL)
835 {
836 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
837 PyErr_Print ();
838 PyErr_Clear();
839 ret_success = false;
840 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000841
Chris Lattner24943d22010-06-08 16:52:24 +0000842 return ret_success;
843}
844
845bool
846ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
847{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000848
849
850 Locker locker(this,
851 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
852 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000853
Chris Lattner24943d22010-06-08 16:52:24 +0000854 bool success = false;
855 PyObject *py_return = NULL;
856 PyObject *mainmod = PyImport_AddModule ("__main__");
857 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000858 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000859 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000860 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000861
Caroline Tice0aa2e552011-01-14 00:29:16 +0000862 if (PyDict_Check (globals))
863 {
864 PyObject *key, *value;
865 Py_ssize_t pos = 0;
866
867 while (PyDict_Next (globals, &pos, &key, &value))
868 {
869 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
870 // so that Python's garbage collector doesn't collect them out from under us.
871 Py_INCREF (key);
872 Py_INCREF (value);
873 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
874 locals = value;
875 }
876 }
877
878 if (locals == NULL)
879 {
880 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
881 should_decrement_locals = true;
882 }
883
884 if (locals == NULL)
885 {
886 locals = globals;
887 should_decrement_locals = false;
888 }
889
890 py_error = PyErr_Occurred();
891 if (py_error != NULL)
892 PyErr_Clear();
893
Chris Lattner24943d22010-06-08 16:52:24 +0000894 if (in_string != NULL)
895 {
896 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
897 if (compiled_node)
898 {
899 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
900 if (compiled_code)
901 {
902 py_return = PyEval_EvalCode (compiled_code, globals, locals);
903 if (py_return != NULL)
904 {
905 success = true;
906 Py_DECREF (py_return);
907 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000908 if (locals && should_decrement_locals)
909 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000910 }
911 }
912 }
913
914 py_error = PyErr_Occurred ();
915 if (py_error != NULL)
916 {
917 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
918 PyErr_Print ();
919 PyErr_Clear();
920 success = false;
921 }
922
923 return success;
924}
925
926static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
927
928size_t
929ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
930(
931 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000932 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000933 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000934 const char *bytes,
935 size_t bytes_len
936)
937{
Caroline Tice892fadd2011-06-16 16:27:19 +0000938 static StringList commands_in_progress;
939
940 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
941 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
942
Chris Lattner24943d22010-06-08 16:52:24 +0000943 switch (notification)
944 {
945 case eInputReaderActivate:
946 {
947 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +0000948 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +0000949 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000950 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000951 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +0000952 out_stream->Printf ("%s", reader.GetPrompt());
953 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +0000954 }
955 }
956 break;
957
958 case eInputReaderDeactivate:
959 break;
960
961 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +0000962 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000963 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000964 out_stream->Printf ("%s", reader.GetPrompt());
965 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +0000966 }
Chris Lattner24943d22010-06-08 16:52:24 +0000967 break;
968
Caroline Tice4a348082011-05-02 20:41:46 +0000969 case eInputReaderAsynchronousOutputWritten:
970 break;
971
Chris Lattner24943d22010-06-08 16:52:24 +0000972 case eInputReaderGotToken:
973 {
974 std::string temp_string (bytes, bytes_len);
975 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +0000976 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000977 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000978 out_stream->Printf ("%s", reader.GetPrompt());
979 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +0000980 }
Chris Lattner24943d22010-06-08 16:52:24 +0000981 }
982 break;
983
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000984 case eInputReaderEndOfFile:
985 case eInputReaderInterrupt:
986 // Control-c (SIGINT) & control-d both mean finish & exit.
987 reader.SetIsDone(true);
988
989 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
990 if (notification == eInputReaderInterrupt)
991 commands_in_progress.Clear();
992
993 // Fall through here...
994
Chris Lattner24943d22010-06-08 16:52:24 +0000995 case eInputReaderDone:
996 {
997 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
998 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
999 data_ap->user_source.AppendList (commands_in_progress);
1000 if (data_ap.get())
1001 {
Greg Clayton63094e02010-06-23 01:19:29 +00001002 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001003 if (interpreter)
1004 {
1005 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1006 data_ap->script_source))
1007 {
1008 if (data_ap->script_source.GetSize() == 1)
1009 {
1010 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1011 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1012 }
1013 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001014 else if (!batch_mode)
1015 {
1016 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1017 out_stream->Flush();
1018 }
Chris Lattner24943d22010-06-08 16:52:24 +00001019 }
1020 else
1021 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001022 if (!batch_mode)
1023 {
1024 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1025 out_stream->Flush();
1026 }
Chris Lattner24943d22010-06-08 16:52:24 +00001027 }
1028 }
1029 }
1030 break;
1031
1032 }
1033
1034 return bytes_len;
1035}
1036
1037void
Greg Clayton238c0a12010-09-18 01:14:36 +00001038ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001039 CommandReturnObject &result)
1040{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001041 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1042
Greg Clayton63094e02010-06-23 01:19:29 +00001043 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001044
1045 if (reader_sp)
1046 {
1047 Error err = reader_sp->Initialize (
1048 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1049 bp_options, // baton
1050 eInputReaderGranularityLine, // token size, for feeding data to callback function
1051 "DONE", // end token
1052 "> ", // prompt
1053 true); // echo input
1054
1055 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001056 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001057 else
1058 {
1059 result.AppendError (err.AsCString());
1060 result.SetStatus (eReturnStatusFailed);
1061 }
1062 }
1063 else
1064 {
1065 result.AppendError("out of memory");
1066 result.SetStatus (eReturnStatusFailed);
1067 }
1068}
1069
Johnny Chen3e0571b2010-09-11 00:23:59 +00001070// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001071void
Greg Clayton238c0a12010-09-18 01:14:36 +00001072ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001073 const char *oneliner)
1074{
1075 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1076
1077 // It's necessary to set both user_source and script_source to the oneliner.
1078 // The former is used to generate callback description (as in breakpoint command list)
1079 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001080
Johnny Chend1c2dca2010-09-10 18:21:10 +00001081 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001082
Caroline Tice5136f942010-09-27 21:35:15 +00001083 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1084 {
1085 if (data_ap->script_source.GetSize() == 1)
1086 {
1087 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1088 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1089 }
1090 }
1091
Johnny Chend1c2dca2010-09-10 18:21:10 +00001092 return;
1093}
1094
Chris Lattner24943d22010-06-08 16:52:24 +00001095bool
1096ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1097{
1098 // Convert StringList to one long, newline delimited, const char *.
1099 std::string function_def_string;
1100
1101 int num_lines = function_def.GetSize();
1102
1103 for (int i = 0; i < num_lines; ++i)
1104 {
1105 function_def_string.append (function_def.GetStringAtIndex(i));
1106 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1107 function_def_string.append ("\n");
1108
1109 }
1110
1111 return ExecuteMultipleLines (function_def_string.c_str());
1112}
1113
Enrico Granataf7a9b142011-07-15 02:26:42 +00001114// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1115// use this code to generate their functions
1116bool
1117ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1118{
1119 int num_lines = input.GetSize ();
1120 if (num_lines == 0)
1121 return false;
1122 StreamString sstr;
1123 StringList auto_generated_function;
1124 auto_generated_function.AppendString (signature.c_str());
1125 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1126 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1127 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1128 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1129 // global dictionary.
1130
1131 // Wrap everything up inside the function, increasing the indentation.
1132
1133 for (int i = 0; i < num_lines; ++i)
1134 {
1135 sstr.Clear ();
1136 sstr.Printf (" %s", input.GetStringAtIndex (i));
1137 auto_generated_function.AppendString (sstr.GetData());
1138 }
1139 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1140 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1141 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1142 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1143
1144 // Verify that the results are valid Python.
1145
1146 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1147 return false;
1148
1149 return true;
1150
1151}
1152
1153// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1154// given to generated functions, of course)
1155bool
1156ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output)
1157{
1158 static int num_created_functions = 0;
1159 user_input.RemoveBlankLines ();
1160 int num_lines = user_input.GetSize ();
1161 StreamString sstr;
1162
1163 // Check to see if we have any data; if not, just return.
1164 if (user_input.GetSize() == 0)
1165 return false;
1166
1167 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1168 // ValueObject as parameter to the function.
1169
1170 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1171 ++num_created_functions;
1172 std::string auto_generated_function_name = sstr.GetData();
1173
1174 sstr.Clear();
1175 StringList auto_generated_function;
1176
1177 // Create the function name & definition string.
1178
1179 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1180 auto_generated_function.AppendString (sstr.GetData());
1181
1182 // Pre-pend code for setting up the session dictionary.
1183
1184 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1185 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1186 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1187 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1188 // global dictionary.
1189
1190 // Wrap everything up inside the function, increasing the indentation.
1191
1192 for (int i = 0; i < num_lines; ++i)
1193 {
1194 sstr.Clear ();
1195 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1196 auto_generated_function.AppendString (sstr.GetData());
1197 }
1198
1199 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1200 // got written to the values in the global dictionary, not the session dictionary).
1201
1202 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1203 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1204 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1205 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1206
1207 // Verify that the results are valid Python.
1208
1209 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1210 return false;
1211
1212 // Store the name of the auto-generated function to be called.
1213
1214 output.AppendString (auto_generated_function_name.c_str());
1215 return true;
1216}
1217
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001218bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001219ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, StringList &output)
1220{
1221 static int num_created_functions = 0;
1222 user_input.RemoveBlankLines ();
1223 int num_lines = user_input.GetSize ();
1224 StreamString sstr;
1225
1226 // Check to see if we have any data; if not, just return.
1227 if (user_input.GetSize() == 0)
1228 return false;
1229
1230 // 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 +00001231 // required data as parameters to the function.
Enrico Granatac2a28252011-08-16 16:49:25 +00001232
1233 sstr.Printf ("lldb_autogen_python_cmd_alias_func_%d", num_created_functions);
1234 ++num_created_functions;
1235 std::string auto_generated_function_name = sstr.GetData();
1236
1237 sstr.Clear();
1238 StringList auto_generated_function;
1239
1240 // Create the function name & definition string.
1241
Enrico Granata271568f2011-09-09 01:41:30 +00001242 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001243 auto_generated_function.AppendString (sstr.GetData());
1244
1245 // Pre-pend code for setting up the session dictionary.
1246
1247 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1248 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1249 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1250 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1251 // global dictionary.
1252
1253 // Wrap everything up inside the function, increasing the indentation.
1254
1255 for (int i = 0; i < num_lines; ++i)
1256 {
1257 sstr.Clear ();
1258 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1259 auto_generated_function.AppendString (sstr.GetData());
1260 }
1261
1262 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1263 // got written to the values in the global dictionary, not the session dictionary).
1264
1265 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1266 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1267 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1268 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1269
1270 // Verify that the results are valid Python.
1271
1272 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1273 return false;
1274
1275 // Store the name of the auto-generated function to be called.
1276
1277 output.AppendString (auto_generated_function_name.c_str());
1278 return true;
1279}
1280
1281
1282bool
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001283ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output)
1284{
1285 static int num_created_classes = 0;
1286 user_input.RemoveBlankLines ();
1287 int num_lines = user_input.GetSize ();
1288 StreamString sstr;
1289
1290 // Check to see if we have any data; if not, just return.
1291 if (user_input.GetSize() == 0)
1292 return false;
1293
1294 // Wrap all user input into a Python class
1295
1296 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1297 ++num_created_classes;
1298 std::string auto_generated_class_name = sstr.GetData();
1299
1300 sstr.Clear();
1301 StringList auto_generated_class;
1302
1303 // Create the function name & definition string.
1304
1305 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1306 auto_generated_class.AppendString (sstr.GetData());
1307
1308 // Wrap everything up inside the class, increasing the indentation.
1309
1310 for (int i = 0; i < num_lines; ++i)
1311 {
1312 sstr.Clear ();
1313 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1314 auto_generated_class.AppendString (sstr.GetData());
1315 }
1316
1317
1318 // Verify that the results are valid Python.
1319 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1320 // (TODO: rename that method to ExportDefinitionToInterpreter)
1321 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1322 return false;
1323
1324 // Store the name of the auto-generated class
1325
1326 output.AppendString (auto_generated_class_name.c_str());
1327 return true;
1328}
1329
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001330void*
1331ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1332 lldb::ValueObjectSP valobj)
1333{
1334 if (class_name.empty())
1335 return NULL;
1336
1337 if (!valobj.get())
1338 return NULL;
1339
Enrico Granata979e20d2011-07-29 19:53:35 +00001340 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001341
1342 if (!target)
1343 return NULL;
1344
1345 Debugger &debugger = target->GetDebugger();
1346 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1347 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1348
1349 if (!script_interpreter)
1350 return NULL;
1351
1352 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001353
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001354 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001355 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001356 ret_val = g_swig_synthetic_script (class_name,
1357 python_interpreter->m_dictionary_name.c_str(),
1358 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001359 }
1360
1361 return ret_val;
1362}
1363
Enrico Granataf7a9b142011-07-15 02:26:42 +00001364bool
1365ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output)
1366{
1367 StringList input(oneliner);
1368 return GenerateTypeScriptFunction(input, output);
1369}
1370
Chris Lattner24943d22010-06-08 16:52:24 +00001371bool
1372ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1373{
1374 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001375 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001376 int num_lines = user_input.GetSize ();
1377 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001378
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001379 // Check to see if we have any data; if not, just return.
1380 if (user_input.GetSize() == 0)
1381 return false;
1382
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001383 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1384 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001385
Caroline Ticeb447e842010-09-21 19:25:28 +00001386
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001387 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1388 ++num_created_functions;
1389 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001390
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001391 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001392 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001393
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001394 // Create the function name & definition string.
1395
Caroline Tice0aa2e552011-01-14 00:29:16 +00001396 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001397 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001398
1399 // Pre-pend code for setting up the session dictionary.
1400
1401 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1402 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1403 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1404 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1405 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001406
1407 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001408
1409 for (int i = 0; i < num_lines; ++i)
1410 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001411 sstr.Clear ();
1412 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1413 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001414 }
Chris Lattner24943d22010-06-08 16:52:24 +00001415
Caroline Tice0aa2e552011-01-14 00:29:16 +00001416 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1417 // got written to the values in the global dictionary, not the session dictionary).
1418
1419 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1420 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1421 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1422 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1423
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001424 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001425
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001426 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001427 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001428 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001429 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001430
1431 // Store the name of the auto-generated function to be called.
1432
1433 callback_data.AppendString (auto_generated_function_name.c_str());
1434 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001435}
1436
Enrico Granataf7a9b142011-07-15 02:26:42 +00001437std::string
1438ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1439 lldb::ValueObjectSP valobj)
1440{
1441
1442 if (!python_function_name || !(*python_function_name))
1443 return "<no function>";
1444
1445 if (!valobj.get())
1446 return "<no object>";
1447
Enrico Granata979e20d2011-07-29 19:53:35 +00001448 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001449
1450 if (!target)
1451 return "<no target>";
1452
1453 Debugger &debugger = target->GetDebugger();
1454 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1455 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1456
1457 if (!script_interpreter)
1458 return "<no python>";
1459
1460 std::string ret_val;
1461
1462 if (python_function_name
1463 && *python_function_name)
1464 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001465 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001466 Locker py_lock(python_interpreter);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001467 ret_val = g_swig_typescript_callback (python_function_name,
1468 python_interpreter->m_dictionary_name.c_str(),
1469 valobj);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001470 }
1471 }
1472 else
1473 return "<no function name>";
1474
1475 return ret_val;
1476
1477}
1478
Greg Clayton5144f382010-10-07 17:14:24 +00001479bool
1480ScriptInterpreterPython::BreakpointCallbackFunction
1481(
1482 void *baton,
1483 StoppointCallbackContext *context,
1484 user_id_t break_id,
1485 user_id_t break_loc_id
1486)
1487{
1488 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1489 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001490
1491 if (!context)
1492 return true;
1493
Greg Clayton567e7f32011-09-22 04:58:26 +00001494 Target *target = context->exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001495
1496 if (!target)
1497 return true;
1498
1499 Debugger &debugger = target->GetDebugger();
1500 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1501 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1502
1503 if (!script_interpreter)
1504 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001505
1506 if (python_function_name != NULL
1507 && python_function_name[0] != '\0')
1508 {
Greg Clayton567e7f32011-09-22 04:58:26 +00001509 const StackFrameSP stop_frame_sp (context->exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001510 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001511 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001512 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001513 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1514
1515 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001516 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001517 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001518 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001519 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001520 ret_val = g_swig_breakpoint_callback (python_function_name,
1521 python_interpreter->m_dictionary_name.c_str(),
1522 stop_frame_sp,
1523 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001524 }
1525 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001526 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001527 }
Greg Clayton5144f382010-10-07 17:14:24 +00001528 }
1529 // We currently always true so we stop in case anything goes wrong when
1530 // trying to call the script function
1531 return true;
1532}
Caroline Tice2ade6112010-11-10 19:18:14 +00001533
1534lldb::thread_result_t
1535ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1536{
1537 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1538
1539 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1540
1541 if (log)
1542 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1543
1544 char error_str[1024];
1545 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001546
Enrico Granatafa1f6172011-10-24 17:22:21 +00001547 Locker locker(script_interpreter,
1548 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1549 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1550
1551 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001552 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001553 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001554
Caroline Tice0aa2e552011-01-14 00:29:16 +00001555 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1556 PyRun_SimpleString (run_string.GetData());
1557 run_string.Clear ();
1558
1559 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1560 PyRun_SimpleString (run_string.GetData());
1561 run_string.Clear ();
1562
1563 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1564 PyRun_SimpleString (run_string.GetData());
1565 run_string.Clear ();
1566
1567 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1568 pty_slave_name);
1569 PyRun_SimpleString (run_string.GetData());
1570 run_string.Clear ();
1571
Johnny Chen8054ba32011-03-11 00:28:50 +00001572 // The following call drops into the embedded interpreter loop and stays there until the
1573 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001574
Caroline Ticece207c12011-03-11 00:21:55 +00001575 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001576 // 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 +00001577 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1578
1579 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1580 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1581 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1582 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1583 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1584 // hang (it's happened before).
1585
Caroline Tice9d352ce2011-03-07 23:24:28 +00001586 Py_BEGIN_ALLOW_THREADS
1587 PyGILState_STATE gstate = PyGILState_Ensure();
1588
Caroline Tice0aa2e552011-01-14 00:29:16 +00001589 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1590 PyRun_SimpleString (run_string.GetData());
1591 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001592
Caroline Tice9d352ce2011-03-07 23:24:28 +00001593 PyGILState_Release (gstate);
1594 Py_END_ALLOW_THREADS
1595
Caroline Tice0aa2e552011-01-14 00:29:16 +00001596 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1597 PyRun_SimpleString (run_string.GetData());
1598 run_string.Clear();
1599
1600 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1601 PyRun_SimpleString (run_string.GetData());
1602 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001603
Caroline Tice2ade6112010-11-10 19:18:14 +00001604 }
1605
1606 if (script_interpreter->m_embedded_thread_input_reader_sp)
1607 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1608
1609 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001610
Caroline Tice2ade6112010-11-10 19:18:14 +00001611 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1612 if (log)
1613 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1614
1615
Johnny Chen8054ba32011-03-11 00:28:50 +00001616 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001617 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001618 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1619 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1620 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001621
Caroline Tice2ade6112010-11-10 19:18:14 +00001622 return NULL;
1623}
1624
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001625uint32_t
1626ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1627{
1628 if (!implementor)
1629 return 0;
1630
1631 if (!g_swig_calc_children)
1632 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001633
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001634 uint32_t ret_val = 0;
1635
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001636 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001637 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001638 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001639 }
1640
1641 return ret_val;
1642}
1643
Enrico Granata91544802011-09-06 19:20:51 +00001644lldb::ValueObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001645ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1646{
1647 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001648 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001649
Enrico Granata91544802011-09-06 19:20:51 +00001650 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1651 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001652
Enrico Granata91544802011-09-06 19:20:51 +00001653 void* child_ptr = NULL;
1654 lldb::SBValue* value_sb = NULL;
1655 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001656
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001657 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001658 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +00001659 child_ptr = g_swig_get_child_index (implementor,idx);
1660 if (child_ptr != NULL && child_ptr != Py_None)
1661 {
1662 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1663 if (value_sb == NULL)
1664 Py_XDECREF(child_ptr);
1665 else
1666 ret_val = value_sb->get_sp();
1667 }
1668 else
1669 {
1670 Py_XDECREF(child_ptr);
1671 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001672 }
1673
1674 return ret_val;
1675}
1676
1677int
1678ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1679{
1680 if (!implementor)
1681 return UINT32_MAX;
1682
1683 if (!g_swig_get_index_child)
1684 return UINT32_MAX;
1685
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001686 int ret_val = UINT32_MAX;
1687
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001688 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001689 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001690 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001691 }
1692
1693 return ret_val;
1694}
1695
Enrico Granata979e20d2011-07-29 19:53:35 +00001696void
1697ScriptInterpreterPython::UpdateSynthProviderInstance (void* implementor)
1698{
1699 if (!implementor)
1700 return;
1701
1702 if (!g_swig_update_provider)
1703 return;
1704
Enrico Granata979e20d2011-07-29 19:53:35 +00001705 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001706 Locker py_lock(this);
Enrico Granata979e20d2011-07-29 19:53:35 +00001707 g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001708 }
1709
1710 return;
1711}
1712
Enrico Granatac2a28252011-08-16 16:49:25 +00001713bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001714ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00001715 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00001716 lldb_private::Error& error)
1717{
1718 if (!pathname || !pathname[0])
1719 {
1720 error.SetErrorString("invalid pathname");
1721 return false;
1722 }
1723
1724 if (!g_swig_call_module_init)
1725 {
1726 error.SetErrorString("internal helper function missing");
1727 return false;
1728 }
1729
Enrico Granata59df36f2011-10-17 21:45:27 +00001730 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
Enrico Granatafa1f6172011-10-24 17:22:21 +00001731
Enrico Granata59df36f2011-10-17 21:45:27 +00001732 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001733 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00001734
1735 FileSpec target_file(pathname, true);
1736
1737 // TODO: would we want to reject any other value?
1738 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1739 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1740 {
1741 error.SetErrorString("invalid pathname");
1742 return false;
1743 }
1744
1745 const char* directory = target_file.GetDirectory().GetCString();
1746 std::string basename(target_file.GetFilename().GetCString());
1747
1748 // now make sure that Python has "directory" in the search path
1749 StreamString command_stream;
1750 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1751 directory,
1752 directory);
Enrico Granatafa1f6172011-10-24 17:22:21 +00001753 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData());
Enrico Granata59df36f2011-10-17 21:45:27 +00001754 if (!syspath_retval)
1755 {
1756 error.SetErrorString("Python sys.path handling failed");
1757 return false;
1758 }
1759
1760 // strip .py or .pyc extension
1761 ConstString extension = target_file.GetFileNameExtension();
1762 if (::strcmp(extension.GetCString(), "py") == 0)
1763 basename.resize(basename.length()-3);
1764 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1765 basename.resize(basename.length()-4);
1766
1767 // check if the module is already import-ed
1768 command_stream.Clear();
1769 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1770 int refcount = 0;
1771 // this call will fail if the module does not exist (because the parameter to it is not a string
1772 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00001773 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
1774 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0);
1775 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00001776 {
1777 error.SetErrorString("module already imported");
1778 return false;
1779 }
1780
1781 // now actually do the import
1782 command_stream.Clear();
1783 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafa1f6172011-10-24 17:22:21 +00001784 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL);
Enrico Granata59df36f2011-10-17 21:45:27 +00001785 if (!import_retval)
1786 {
1787 error.SetErrorString("Python import statement failed");
1788 return false;
1789 }
1790
1791 // call __lldb_module_init(debugger,dict)
1792 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001793 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001794 debugger_sp))
1795 {
1796 error.SetErrorString("calling __lldb_module_init failed");
1797 return false;
1798 }
1799 return true;
1800 }
1801}
1802
Enrico Granata6010ace2011-11-07 22:57:04 +00001803ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
1804 ScriptedCommandSynchronicity synchro) :
1805 m_debugger_sp(debugger_sp),
1806 m_synch_wanted(synchro),
1807 m_old_asynch(debugger_sp->GetAsyncExecution())
1808{
1809 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
1810 m_debugger_sp->SetAsyncExecution(false);
1811 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
1812 m_debugger_sp->SetAsyncExecution(true);
1813}
1814
1815ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
1816{
1817 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
1818 m_debugger_sp->SetAsyncExecution(m_old_asynch);
1819}
1820
Enrico Granata59df36f2011-10-17 21:45:27 +00001821bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001822ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1823 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00001824 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001825 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001826 Error& error)
1827{
1828 if (!impl_function)
1829 {
1830 error.SetErrorString("no function to execute");
1831 return false;
1832 }
1833
1834 if (!g_swig_call_command)
1835 {
1836 error.SetErrorString("no helper function to run scripted commands");
1837 return false;
1838 }
1839
Enrico Granatac2a28252011-08-16 16:49:25 +00001840 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
Enrico Granata6010ace2011-11-07 22:57:04 +00001841
1842 if (!debugger_sp.get())
1843 {
1844 error.SetErrorString("invalid Debugger pointer");
1845 return false;
1846 }
Enrico Granatac2a28252011-08-16 16:49:25 +00001847
1848 bool ret_val;
1849
1850 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00001851
Enrico Granatac2a28252011-08-16 16:49:25 +00001852 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001853 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00001854 SynchronicityHandler synch_handler(debugger_sp,
1855 synchronicity);
1856
Enrico Granatac2a28252011-08-16 16:49:25 +00001857 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001858 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00001859 debugger_sp,
1860 args,
1861 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001862 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001863 }
Enrico Granata6010ace2011-11-07 22:57:04 +00001864
Enrico Granatac2a28252011-08-16 16:49:25 +00001865 if (!ret_val)
1866 error.SetErrorString(err_msg.c_str());
1867 else
1868 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00001869
Enrico Granatac2a28252011-08-16 16:49:25 +00001870 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00001871}
1872
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001873// in Python, a special attribute __doc__ contains the docstring
1874// for an object (function, method, class, ...) if any is defined
1875// Otherwise, the attribute's value is None
1876std::string
1877ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1878{
1879 std::string command(item);
1880 command += ".__doc__";
1881
1882 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1883
1884 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001885 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001886 &result_ptr) && result_ptr)
1887 {
1888 return std::string(result_ptr);
1889 }
1890 else
1891 return std::string("");
1892}
Caroline Tice2ade6112010-11-10 19:18:14 +00001893
Caroline Tice0aa2e552011-01-14 00:29:16 +00001894void
Greg Claytone86cbb92011-03-22 01:14:58 +00001895ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00001896 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001897 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
1898 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
1899 SWIGPythonCalculateNumChildren python_swig_calc_children,
1900 SWIGPythonGetChildAtIndex python_swig_get_child_index,
1901 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
Enrico Granata979e20d2011-07-29 19:53:35 +00001902 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue,
Enrico Granatac2a28252011-08-16 16:49:25 +00001903 SWIGPythonUpdateSynthProviderInstance python_swig_update_provider,
Enrico Granata59df36f2011-10-17 21:45:27 +00001904 SWIGPythonCallCommand python_swig_call_command,
1905 SWIGPythonCallModuleInit python_swig_call_mod_init)
Greg Claytone86cbb92011-03-22 01:14:58 +00001906{
1907 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001908 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1909 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001910 g_swig_synthetic_script = python_swig_synthetic_script;
1911 g_swig_calc_children = python_swig_calc_children;
1912 g_swig_get_child_index = python_swig_get_child_index;
1913 g_swig_get_index_child = python_swig_get_index_child;
1914 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Enrico Granata979e20d2011-07-29 19:53:35 +00001915 g_swig_update_provider = python_swig_update_provider;
Enrico Granatac2a28252011-08-16 16:49:25 +00001916 g_swig_call_command = python_swig_call_command;
Enrico Granata59df36f2011-10-17 21:45:27 +00001917 g_swig_call_module_init = python_swig_call_mod_init;
Greg Claytone86cbb92011-03-22 01:14:58 +00001918}
1919
1920void
1921ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001922{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001923 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1924
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001925 // Python will muck with STDIN terminal state, so save off any current TTY
1926 // settings so we can restore them.
1927 TerminalState stdin_tty_state;
1928 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001929
Caroline Tice9d352ce2011-03-07 23:24:28 +00001930 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001931 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001932
Greg Claytone86cbb92011-03-22 01:14:58 +00001933 // Initialize SWIG after setting up python
1934 assert (g_swig_init_callback != NULL);
1935 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001936
1937 // Update the path python uses to search for modules to include the current directory.
1938
Caroline Ticed4d92832011-06-13 21:33:00 +00001939 PyRun_SimpleString ("import sys");
1940 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001941
1942 // Find the module that owns this code and use that path we get to
1943 // set the sys.path appropriately.
1944
1945 FileSpec file_spec;
1946 char python_dir_path[PATH_MAX];
1947 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1948 {
1949 std::string python_path("sys.path.insert(0,\"");
1950 size_t orig_len = python_path.length();
1951 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1952 {
1953 python_path.append (python_dir_path);
1954 python_path.append ("\")");
1955 PyRun_SimpleString (python_path.c_str());
1956 python_path.resize (orig_len);
1957 }
1958
1959 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1960 {
1961 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1962 {
1963 python_path.append (python_dir_path);
1964 python_path.append ("\")");
1965 PyRun_SimpleString (python_path.c_str());
1966 python_path.resize (orig_len);
1967 }
1968 }
1969 }
1970
Jim Ingham4dfa5112011-08-22 19:10:09 +00001971 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001972
Caroline Ticed4d92832011-06-13 21:33:00 +00001973 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001974
Caroline Ticed4d92832011-06-13 21:33:00 +00001975 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1976 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00001977 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001978
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001979 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001980}
1981
Greg Claytone86cbb92011-03-22 01:14:58 +00001982//void
1983//ScriptInterpreterPython::Terminate ()
1984//{
1985// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1986// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1987// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1988// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1989// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1990// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1991// // within Py_Finalize, which results in a seg fault.
1992// //
1993// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1994// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1995// // process exits).
1996// //
1997//// Py_Finalize ();
1998//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00001999
2000#endif // #ifdef LLDB_DISABLE_PYTHON