blob: 71b7162102aab3e1e231e4f622c0bbff307c5209 [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
Enrico Granata16376ed2012-02-15 02:34:21 +00001143ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001144{
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
Enrico Granata16376ed2012-02-15 02:34:21 +00001157 if (!name_token)
1158 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1159 else
1160 sstr.Printf ("lldb_gen_python_type_print_func_%p", name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001161 ++num_created_functions;
1162 std::string auto_generated_function_name = sstr.GetData();
1163
1164 sstr.Clear();
1165 StringList auto_generated_function;
1166
1167 // Create the function name & definition string.
1168
1169 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1170 auto_generated_function.AppendString (sstr.GetData());
1171
1172 // Pre-pend code for setting up the session dictionary.
1173
1174 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1175 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1176 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1177 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1178 // global dictionary.
1179
1180 // Wrap everything up inside the function, increasing the indentation.
1181
1182 for (int i = 0; i < num_lines; ++i)
1183 {
1184 sstr.Clear ();
1185 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1186 auto_generated_function.AppendString (sstr.GetData());
1187 }
1188
1189 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1190 // got written to the values in the global dictionary, not the session dictionary).
1191
1192 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1193 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1194 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1195 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1196
1197 // Verify that the results are valid Python.
1198
1199 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1200 return false;
1201
1202 // Store the name of the auto-generated function to be called.
1203
1204 output.AppendString (auto_generated_function_name.c_str());
1205 return true;
1206}
1207
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001208bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001209ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, StringList &output)
1210{
1211 static int num_created_functions = 0;
1212 user_input.RemoveBlankLines ();
1213 int num_lines = user_input.GetSize ();
1214 StreamString sstr;
1215
1216 // Check to see if we have any data; if not, just return.
1217 if (user_input.GetSize() == 0)
1218 return false;
1219
1220 // 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 +00001221 // required data as parameters to the function.
Enrico Granatac2a28252011-08-16 16:49:25 +00001222
1223 sstr.Printf ("lldb_autogen_python_cmd_alias_func_%d", num_created_functions);
1224 ++num_created_functions;
1225 std::string auto_generated_function_name = sstr.GetData();
1226
1227 sstr.Clear();
1228 StringList auto_generated_function;
1229
1230 // Create the function name & definition string.
1231
Enrico Granata271568f2011-09-09 01:41:30 +00001232 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001233 auto_generated_function.AppendString (sstr.GetData());
1234
1235 // Pre-pend code for setting up the session dictionary.
1236
1237 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1238 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1239 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1240 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1241 // global dictionary.
1242
1243 // Wrap everything up inside the function, increasing the indentation.
1244
1245 for (int i = 0; i < num_lines; ++i)
1246 {
1247 sstr.Clear ();
1248 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1249 auto_generated_function.AppendString (sstr.GetData());
1250 }
1251
1252 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1253 // got written to the values in the global dictionary, not the session dictionary).
1254
1255 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1256 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1257 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1258 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1259
1260 // Verify that the results are valid Python.
1261
1262 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1263 return false;
1264
1265 // Store the name of the auto-generated function to be called.
1266
1267 output.AppendString (auto_generated_function_name.c_str());
1268 return true;
1269}
1270
1271
1272bool
Enrico Granata16376ed2012-02-15 02:34:21 +00001273ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output, void* name_token)
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001274{
1275 static int num_created_classes = 0;
1276 user_input.RemoveBlankLines ();
1277 int num_lines = user_input.GetSize ();
1278 StreamString sstr;
1279
1280 // Check to see if we have any data; if not, just return.
1281 if (user_input.GetSize() == 0)
1282 return false;
1283
1284 // Wrap all user input into a Python class
1285
Enrico Granata16376ed2012-02-15 02:34:21 +00001286 if (!name_token)
1287 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1288 else
1289 sstr.Printf ("lldb_gen_python_type_synth_class_%p", name_token);
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001290 ++num_created_classes;
1291 std::string auto_generated_class_name = sstr.GetData();
1292
1293 sstr.Clear();
1294 StringList auto_generated_class;
1295
1296 // Create the function name & definition string.
1297
1298 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1299 auto_generated_class.AppendString (sstr.GetData());
1300
1301 // Wrap everything up inside the class, increasing the indentation.
1302
1303 for (int i = 0; i < num_lines; ++i)
1304 {
1305 sstr.Clear ();
1306 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1307 auto_generated_class.AppendString (sstr.GetData());
1308 }
1309
1310
1311 // Verify that the results are valid Python.
1312 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1313 // (TODO: rename that method to ExportDefinitionToInterpreter)
1314 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1315 return false;
1316
1317 // Store the name of the auto-generated class
1318
1319 output.AppendString (auto_generated_class_name.c_str());
1320 return true;
1321}
1322
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001323void*
1324ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1325 lldb::ValueObjectSP valobj)
1326{
1327 if (class_name.empty())
1328 return NULL;
1329
1330 if (!valobj.get())
1331 return NULL;
1332
Enrico Granata979e20d2011-07-29 19:53:35 +00001333 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001334
1335 if (!target)
1336 return NULL;
1337
1338 Debugger &debugger = target->GetDebugger();
1339 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1340 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1341
1342 if (!script_interpreter)
1343 return NULL;
1344
1345 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001346
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001347 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001348 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001349 ret_val = g_swig_synthetic_script (class_name,
1350 python_interpreter->m_dictionary_name.c_str(),
1351 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001352 }
1353
1354 return ret_val;
1355}
1356
Enrico Granataf7a9b142011-07-15 02:26:42 +00001357bool
Enrico Granata16376ed2012-02-15 02:34:21 +00001358ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001359{
Enrico Granata16376ed2012-02-15 02:34:21 +00001360 StringList input;
1361 input.SplitIntoLines(oneliner, strlen(oneliner));
1362 return GenerateTypeScriptFunction(input, output, name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001363}
1364
Chris Lattner24943d22010-06-08 16:52:24 +00001365bool
Enrico Granata16376ed2012-02-15 02:34:21 +00001366ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, StringList &output, void* name_token)
1367{
1368 StringList input;
1369 input.SplitIntoLines(oneliner, strlen(oneliner));
1370 return GenerateTypeSynthClass(input, output, name_token);
1371}
1372
1373
1374bool
Chris Lattner24943d22010-06-08 16:52:24 +00001375ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1376{
1377 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001378 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001379 int num_lines = user_input.GetSize ();
1380 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001381
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001382 // Check to see if we have any data; if not, just return.
1383 if (user_input.GetSize() == 0)
1384 return false;
1385
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001386 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1387 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001388
Caroline Ticeb447e842010-09-21 19:25:28 +00001389
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001390 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1391 ++num_created_functions;
1392 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001393
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001394 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001395 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001396
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001397 // Create the function name & definition string.
1398
Caroline Tice0aa2e552011-01-14 00:29:16 +00001399 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001400 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001401
1402 // Pre-pend code for setting up the session dictionary.
1403
1404 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1405 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1406 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1407 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1408 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001409
1410 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001411
1412 for (int i = 0; i < num_lines; ++i)
1413 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001414 sstr.Clear ();
1415 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1416 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001417 }
Chris Lattner24943d22010-06-08 16:52:24 +00001418
Caroline Tice0aa2e552011-01-14 00:29:16 +00001419 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1420 // got written to the values in the global dictionary, not the session dictionary).
1421
1422 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1423 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1424 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1425 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1426
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001427 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001428
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001429 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001430 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001431 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001432 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001433
1434 // Store the name of the auto-generated function to be called.
1435
1436 callback_data.AppendString (auto_generated_function_name.c_str());
1437 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001438}
1439
Enrico Granataf7a9b142011-07-15 02:26:42 +00001440std::string
1441ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1442 lldb::ValueObjectSP valobj)
1443{
1444
1445 if (!python_function_name || !(*python_function_name))
1446 return "<no function>";
1447
1448 if (!valobj.get())
1449 return "<no object>";
1450
Enrico Granata979e20d2011-07-29 19:53:35 +00001451 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001452
1453 if (!target)
1454 return "<no target>";
1455
1456 Debugger &debugger = target->GetDebugger();
1457 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1458 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1459
1460 if (!script_interpreter)
1461 return "<no python>";
1462
1463 std::string ret_val;
1464
1465 if (python_function_name
1466 && *python_function_name)
1467 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001468 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001469 Locker py_lock(python_interpreter);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001470 ret_val = g_swig_typescript_callback (python_function_name,
1471 python_interpreter->m_dictionary_name.c_str(),
1472 valobj);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001473 }
1474 }
1475 else
1476 return "<no function name>";
1477
1478 return ret_val;
1479
1480}
1481
Greg Clayton5144f382010-10-07 17:14:24 +00001482bool
1483ScriptInterpreterPython::BreakpointCallbackFunction
1484(
1485 void *baton,
1486 StoppointCallbackContext *context,
1487 user_id_t break_id,
1488 user_id_t break_loc_id
1489)
1490{
1491 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1492 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001493
1494 if (!context)
1495 return true;
1496
Greg Clayton567e7f32011-09-22 04:58:26 +00001497 Target *target = context->exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001498
1499 if (!target)
1500 return true;
1501
1502 Debugger &debugger = target->GetDebugger();
1503 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1504 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1505
1506 if (!script_interpreter)
1507 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001508
1509 if (python_function_name != NULL
1510 && python_function_name[0] != '\0')
1511 {
Greg Clayton567e7f32011-09-22 04:58:26 +00001512 const StackFrameSP stop_frame_sp (context->exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001513 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001514 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001515 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001516 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1517
1518 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001519 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001520 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001521 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001522 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001523 ret_val = g_swig_breakpoint_callback (python_function_name,
1524 python_interpreter->m_dictionary_name.c_str(),
1525 stop_frame_sp,
1526 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001527 }
1528 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001529 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001530 }
Greg Clayton5144f382010-10-07 17:14:24 +00001531 }
1532 // We currently always true so we stop in case anything goes wrong when
1533 // trying to call the script function
1534 return true;
1535}
Caroline Tice2ade6112010-11-10 19:18:14 +00001536
1537lldb::thread_result_t
1538ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1539{
1540 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1541
1542 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1543
1544 if (log)
1545 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1546
1547 char error_str[1024];
1548 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001549
Enrico Granatafa1f6172011-10-24 17:22:21 +00001550 Locker locker(script_interpreter,
1551 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1552 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1553
1554 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001555 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001556 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001557
Caroline Tice0aa2e552011-01-14 00:29:16 +00001558 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1559 PyRun_SimpleString (run_string.GetData());
1560 run_string.Clear ();
1561
1562 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1563 PyRun_SimpleString (run_string.GetData());
1564 run_string.Clear ();
1565
1566 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1567 PyRun_SimpleString (run_string.GetData());
1568 run_string.Clear ();
1569
1570 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1571 pty_slave_name);
1572 PyRun_SimpleString (run_string.GetData());
1573 run_string.Clear ();
1574
Johnny Chen8054ba32011-03-11 00:28:50 +00001575 // The following call drops into the embedded interpreter loop and stays there until the
1576 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001577
Caroline Ticece207c12011-03-11 00:21:55 +00001578 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001579 // 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 +00001580 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1581
1582 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1583 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1584 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1585 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1586 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1587 // hang (it's happened before).
1588
Caroline Tice9d352ce2011-03-07 23:24:28 +00001589 Py_BEGIN_ALLOW_THREADS
1590 PyGILState_STATE gstate = PyGILState_Ensure();
1591
Caroline Tice0aa2e552011-01-14 00:29:16 +00001592 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1593 PyRun_SimpleString (run_string.GetData());
1594 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001595
Caroline Tice9d352ce2011-03-07 23:24:28 +00001596 PyGILState_Release (gstate);
1597 Py_END_ALLOW_THREADS
1598
Caroline Tice0aa2e552011-01-14 00:29:16 +00001599 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1600 PyRun_SimpleString (run_string.GetData());
1601 run_string.Clear();
1602
1603 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1604 PyRun_SimpleString (run_string.GetData());
1605 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001606
Caroline Tice2ade6112010-11-10 19:18:14 +00001607 }
1608
1609 if (script_interpreter->m_embedded_thread_input_reader_sp)
1610 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1611
1612 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001613
Caroline Tice2ade6112010-11-10 19:18:14 +00001614 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1615 if (log)
1616 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1617
1618
Johnny Chen8054ba32011-03-11 00:28:50 +00001619 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001620 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001621 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1622 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1623 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001624
Caroline Tice2ade6112010-11-10 19:18:14 +00001625 return NULL;
1626}
1627
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001628uint32_t
1629ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1630{
1631 if (!implementor)
1632 return 0;
1633
1634 if (!g_swig_calc_children)
1635 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001636
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001637 uint32_t ret_val = 0;
1638
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001639 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001640 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001641 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001642 }
1643
1644 return ret_val;
1645}
1646
Enrico Granata91544802011-09-06 19:20:51 +00001647lldb::ValueObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001648ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1649{
1650 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001651 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001652
Enrico Granata91544802011-09-06 19:20:51 +00001653 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1654 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001655
Enrico Granata91544802011-09-06 19:20:51 +00001656 void* child_ptr = NULL;
1657 lldb::SBValue* value_sb = NULL;
1658 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001659
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001660 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001661 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +00001662 child_ptr = g_swig_get_child_index (implementor,idx);
1663 if (child_ptr != NULL && child_ptr != Py_None)
1664 {
1665 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1666 if (value_sb == NULL)
1667 Py_XDECREF(child_ptr);
1668 else
1669 ret_val = value_sb->get_sp();
1670 }
1671 else
1672 {
1673 Py_XDECREF(child_ptr);
1674 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001675 }
1676
1677 return ret_val;
1678}
1679
1680int
1681ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1682{
1683 if (!implementor)
1684 return UINT32_MAX;
1685
1686 if (!g_swig_get_index_child)
1687 return UINT32_MAX;
1688
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001689 int ret_val = UINT32_MAX;
1690
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001691 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001692 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001693 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001694 }
1695
1696 return ret_val;
1697}
1698
Enrico Granata979e20d2011-07-29 19:53:35 +00001699void
1700ScriptInterpreterPython::UpdateSynthProviderInstance (void* implementor)
1701{
1702 if (!implementor)
1703 return;
1704
1705 if (!g_swig_update_provider)
1706 return;
1707
Enrico Granata979e20d2011-07-29 19:53:35 +00001708 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001709 Locker py_lock(this);
Enrico Granata979e20d2011-07-29 19:53:35 +00001710 g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001711 }
1712
1713 return;
1714}
1715
Enrico Granatac2a28252011-08-16 16:49:25 +00001716bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001717ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00001718 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00001719 lldb_private::Error& error)
1720{
1721 if (!pathname || !pathname[0])
1722 {
1723 error.SetErrorString("invalid pathname");
1724 return false;
1725 }
1726
1727 if (!g_swig_call_module_init)
1728 {
1729 error.SetErrorString("internal helper function missing");
1730 return false;
1731 }
1732
Greg Clayton13d24fb2012-01-29 20:56:30 +00001733 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granatafa1f6172011-10-24 17:22:21 +00001734
Enrico Granata59df36f2011-10-17 21:45:27 +00001735 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001736 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00001737
1738 FileSpec target_file(pathname, true);
1739
1740 // TODO: would we want to reject any other value?
1741 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1742 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1743 {
1744 error.SetErrorString("invalid pathname");
1745 return false;
1746 }
1747
1748 const char* directory = target_file.GetDirectory().GetCString();
1749 std::string basename(target_file.GetFilename().GetCString());
1750
1751 // now make sure that Python has "directory" in the search path
1752 StreamString command_stream;
1753 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1754 directory,
1755 directory);
Enrico Granatafa1f6172011-10-24 17:22:21 +00001756 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData());
Enrico Granata59df36f2011-10-17 21:45:27 +00001757 if (!syspath_retval)
1758 {
1759 error.SetErrorString("Python sys.path handling failed");
1760 return false;
1761 }
1762
1763 // strip .py or .pyc extension
1764 ConstString extension = target_file.GetFileNameExtension();
1765 if (::strcmp(extension.GetCString(), "py") == 0)
1766 basename.resize(basename.length()-3);
1767 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1768 basename.resize(basename.length()-4);
1769
1770 // check if the module is already import-ed
1771 command_stream.Clear();
1772 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1773 int refcount = 0;
1774 // this call will fail if the module does not exist (because the parameter to it is not a string
1775 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00001776 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
1777 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0);
1778 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00001779 {
1780 error.SetErrorString("module already imported");
1781 return false;
1782 }
1783
1784 // now actually do the import
1785 command_stream.Clear();
1786 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafa1f6172011-10-24 17:22:21 +00001787 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL);
Enrico Granata59df36f2011-10-17 21:45:27 +00001788 if (!import_retval)
1789 {
1790 error.SetErrorString("Python import statement failed");
1791 return false;
1792 }
1793
Enrico Granata16376ed2012-02-15 02:34:21 +00001794 // call __lldb_init_module(debugger,dict)
Enrico Granata59df36f2011-10-17 21:45:27 +00001795 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001796 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001797 debugger_sp))
1798 {
Enrico Granata16376ed2012-02-15 02:34:21 +00001799 error.SetErrorString("calling __lldb_init_module failed");
Enrico Granata59df36f2011-10-17 21:45:27 +00001800 return false;
1801 }
1802 return true;
1803 }
1804}
1805
Enrico Granata6010ace2011-11-07 22:57:04 +00001806ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
1807 ScriptedCommandSynchronicity synchro) :
1808 m_debugger_sp(debugger_sp),
1809 m_synch_wanted(synchro),
1810 m_old_asynch(debugger_sp->GetAsyncExecution())
1811{
1812 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
1813 m_debugger_sp->SetAsyncExecution(false);
1814 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
1815 m_debugger_sp->SetAsyncExecution(true);
1816}
1817
1818ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
1819{
1820 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
1821 m_debugger_sp->SetAsyncExecution(m_old_asynch);
1822}
1823
Enrico Granata59df36f2011-10-17 21:45:27 +00001824bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001825ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1826 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00001827 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001828 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001829 Error& error)
1830{
1831 if (!impl_function)
1832 {
1833 error.SetErrorString("no function to execute");
1834 return false;
1835 }
1836
1837 if (!g_swig_call_command)
1838 {
1839 error.SetErrorString("no helper function to run scripted commands");
1840 return false;
1841 }
1842
Greg Clayton13d24fb2012-01-29 20:56:30 +00001843 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata6010ace2011-11-07 22:57:04 +00001844
1845 if (!debugger_sp.get())
1846 {
1847 error.SetErrorString("invalid Debugger pointer");
1848 return false;
1849 }
Enrico Granatac2a28252011-08-16 16:49:25 +00001850
1851 bool ret_val;
1852
1853 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00001854
Enrico Granatac2a28252011-08-16 16:49:25 +00001855 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001856 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00001857 SynchronicityHandler synch_handler(debugger_sp,
1858 synchronicity);
1859
Enrico Granatac2a28252011-08-16 16:49:25 +00001860 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001861 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00001862 debugger_sp,
1863 args,
1864 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001865 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001866 }
Enrico Granata6010ace2011-11-07 22:57:04 +00001867
Enrico Granatac2a28252011-08-16 16:49:25 +00001868 if (!ret_val)
1869 error.SetErrorString(err_msg.c_str());
1870 else
1871 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00001872
Enrico Granatac2a28252011-08-16 16:49:25 +00001873 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00001874}
1875
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001876// in Python, a special attribute __doc__ contains the docstring
1877// for an object (function, method, class, ...) if any is defined
1878// Otherwise, the attribute's value is None
1879std::string
1880ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1881{
1882 std::string command(item);
1883 command += ".__doc__";
1884
1885 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1886
1887 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001888 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001889 &result_ptr) && result_ptr)
1890 {
1891 return std::string(result_ptr);
1892 }
1893 else
1894 return std::string("");
1895}
Caroline Tice2ade6112010-11-10 19:18:14 +00001896
Caroline Tice0aa2e552011-01-14 00:29:16 +00001897void
Greg Claytone86cbb92011-03-22 01:14:58 +00001898ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00001899 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001900 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
1901 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
1902 SWIGPythonCalculateNumChildren python_swig_calc_children,
1903 SWIGPythonGetChildAtIndex python_swig_get_child_index,
1904 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
Enrico Granata979e20d2011-07-29 19:53:35 +00001905 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue,
Enrico Granatac2a28252011-08-16 16:49:25 +00001906 SWIGPythonUpdateSynthProviderInstance python_swig_update_provider,
Enrico Granata59df36f2011-10-17 21:45:27 +00001907 SWIGPythonCallCommand python_swig_call_command,
1908 SWIGPythonCallModuleInit python_swig_call_mod_init)
Greg Claytone86cbb92011-03-22 01:14:58 +00001909{
1910 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001911 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1912 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001913 g_swig_synthetic_script = python_swig_synthetic_script;
1914 g_swig_calc_children = python_swig_calc_children;
1915 g_swig_get_child_index = python_swig_get_child_index;
1916 g_swig_get_index_child = python_swig_get_index_child;
1917 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Enrico Granata979e20d2011-07-29 19:53:35 +00001918 g_swig_update_provider = python_swig_update_provider;
Enrico Granatac2a28252011-08-16 16:49:25 +00001919 g_swig_call_command = python_swig_call_command;
Enrico Granata59df36f2011-10-17 21:45:27 +00001920 g_swig_call_module_init = python_swig_call_mod_init;
Greg Claytone86cbb92011-03-22 01:14:58 +00001921}
1922
1923void
1924ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001925{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001926 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1927
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001928 // Python will muck with STDIN terminal state, so save off any current TTY
1929 // settings so we can restore them.
1930 TerminalState stdin_tty_state;
1931 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001932
Caroline Tice9d352ce2011-03-07 23:24:28 +00001933 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001934 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001935
Greg Claytone86cbb92011-03-22 01:14:58 +00001936 // Initialize SWIG after setting up python
1937 assert (g_swig_init_callback != NULL);
1938 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001939
1940 // Update the path python uses to search for modules to include the current directory.
1941
Caroline Ticed4d92832011-06-13 21:33:00 +00001942 PyRun_SimpleString ("import sys");
1943 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001944
1945 // Find the module that owns this code and use that path we get to
1946 // set the sys.path appropriately.
1947
1948 FileSpec file_spec;
1949 char python_dir_path[PATH_MAX];
1950 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1951 {
1952 std::string python_path("sys.path.insert(0,\"");
1953 size_t orig_len = python_path.length();
1954 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1955 {
1956 python_path.append (python_dir_path);
1957 python_path.append ("\")");
1958 PyRun_SimpleString (python_path.c_str());
1959 python_path.resize (orig_len);
1960 }
1961
1962 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1963 {
1964 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1965 {
1966 python_path.append (python_dir_path);
1967 python_path.append ("\")");
1968 PyRun_SimpleString (python_path.c_str());
1969 python_path.resize (orig_len);
1970 }
1971 }
1972 }
1973
Jim Ingham4dfa5112011-08-22 19:10:09 +00001974 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001975
Caroline Ticed4d92832011-06-13 21:33:00 +00001976 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001977
Caroline Ticed4d92832011-06-13 21:33:00 +00001978 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1979 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00001980 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001981
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001982 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001983}
1984
Greg Claytone86cbb92011-03-22 01:14:58 +00001985//void
1986//ScriptInterpreterPython::Terminate ()
1987//{
1988// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1989// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1990// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1991// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1992// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1993// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1994// // within Py_Finalize, which results in a seg fault.
1995// //
1996// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1997// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1998// // process exits).
1999// //
2000//// Py_Finalize ();
2001//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00002002
2003#endif // #ifdef LLDB_DISABLE_PYTHON