blob: 26d058c9574b25d932711ccc3a2c04a1a71391b7 [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
Enrico Granatab8dc7332012-01-31 17:01:51 +0000250 run_string.Clear();
251 run_string.Printf ("run_one_line (%s, 'import objc')", m_dictionary_name.c_str());
252 PyRun_SimpleString (run_string.GetData());
253
Caroline Tice0aa2e552011-01-14 00:29:16 +0000254 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000255 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000256 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000257 }
Chris Lattner24943d22010-06-08 16:52:24 +0000258}
259
260ScriptInterpreterPython::~ScriptInterpreterPython ()
261{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000262 Debugger &debugger = GetCommandInterpreter().GetDebugger();
263
264 if (m_embedded_thread_input_reader_sp.get() != NULL)
265 {
266 m_embedded_thread_input_reader_sp->SetIsDone (true);
267 m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000268 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
269 m_embedded_thread_input_reader_sp.reset();
270 debugger.PopInputReader (reader_sp);
271 }
272
273 if (m_new_sysout)
274 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000275 Locker locker(this,
276 ScriptInterpreterPython::Locker::AcquireLock,
277 ScriptInterpreterPython::Locker::FreeLock);
278 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000279 }
Chris Lattner24943d22010-06-08 16:52:24 +0000280}
281
Caroline Tice0aa2e552011-01-14 00:29:16 +0000282void
283ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
284{
285 if (fh == NULL)
286 return;
287
288 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000289
Enrico Granatafa1f6172011-10-24 17:22:21 +0000290 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +0000291
292 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000293}
294
295void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000296ScriptInterpreterPython::SaveTerminalState (int fd)
297{
298 // Python mucks with the terminal state of STDIN. If we can possibly avoid
299 // this by setting the file handles up correctly prior to entering the
300 // interpreter we should. For now we save and restore the terminal state
301 // on the input file handle.
302 m_terminal_state.Save (fd, false);
303}
304
305void
306ScriptInterpreterPython::RestoreTerminalState ()
307{
308 // Python mucks with the terminal state of STDIN. If we can possibly avoid
309 // this by setting the file handles up correctly prior to entering the
310 // interpreter we should. For now we save and restore the terminal state
311 // on the input file handle.
312 m_terminal_state.Restore();
313}
314
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000315void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000316ScriptInterpreterPython::LeaveSession ()
317{
318 m_session_is_active = false;
319}
320
321void
322ScriptInterpreterPython::EnterSession ()
323{
324 // If we have already entered the session, without having officially 'left' it, then there is no need to
325 // 'enter' it again.
326
327 if (m_session_is_active)
328 return;
329
330 m_session_is_active = true;
331
Caroline Tice202f6b82011-01-17 21:55:19 +0000332 StreamString run_string;
333
Greg Clayton2fecc452012-01-28 02:11:02 +0000334 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %llu", m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
335 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)", GetCommandInterpreter().GetDebugger().GetID());
336 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
337 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
338 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
339 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
340 // Make sure STDIN is closed since when we run this as an embedded
341 // interpreter we don't want someone to call "line = sys.stdin.readline()"
342 // and lock up. We don't have multiple windows and when the interpreter is
343 // embedded we don't know we should be feeding input to the embedded
344 // interpreter or to the python sys.stdin. We also don't want to let python
345 // play with the real stdin from this process, so we need to close it...
346 run_string.PutCString ("; sys.stdin.close()");
347 run_string.PutCString ("')");
Caroline Tice0aa2e552011-01-14 00:29:16 +0000348
Caroline Tice6af65cb2011-05-03 21:21:50 +0000349 PyRun_SimpleString (run_string.GetData());
350 run_string.Clear();
351
Caroline Tice0aa2e552011-01-14 00:29:16 +0000352 PyObject *sysmod = PyImport_AddModule ("sys");
353 PyObject *sysdict = PyModule_GetDict (sysmod);
354
Greg Clayton2fecc452012-01-28 02:11:02 +0000355 if (m_new_sysout && sysmod && sysdict)
356 {
357 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
358 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
359 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000360
361 if (PyErr_Occurred())
362 PyErr_Clear ();
Greg Clayton2fecc452012-01-28 02:11:02 +0000363}
Caroline Tice0aa2e552011-01-14 00:29:16 +0000364
Johnny Chen60dde642010-07-30 22:33:14 +0000365bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000366ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000367{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000368 if (!m_valid_session)
369 return false;
370
Caroline Tice4a461da2011-01-14 21:09:29 +0000371 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
372 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
373 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
374 // method to pass the command string directly down to Python.
375
Enrico Granatafa1f6172011-10-24 17:22:21 +0000376 Locker locker(this,
377 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
378 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000379
380 bool success = false;
381
Greg Clayton63094e02010-06-23 01:19:29 +0000382 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000383 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000384 // Find the correct script interpreter dictionary in the main module.
385 PyObject *main_mod = PyImport_AddModule ("__main__");
386 PyObject *script_interpreter_dict = NULL;
387 if (main_mod != NULL)
388 {
389 PyObject *main_dict = PyModule_GetDict (main_mod);
390 if ((main_dict != NULL)
391 && PyDict_Check (main_dict))
392 {
393 // Go through the main dictionary looking for the correct python script interpreter dictionary
394 PyObject *key, *value;
395 Py_ssize_t pos = 0;
396
397 while (PyDict_Next (main_dict, &pos, &key, &value))
398 {
399 // We have stolen references to the key and value objects in the dictionary; we need to increment
400 // them now so that Python's garbage collector doesn't collect them out from under us.
401 Py_INCREF (key);
402 Py_INCREF (value);
403 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
404 {
405 script_interpreter_dict = value;
406 break;
407 }
408 }
409 }
410
411 if (script_interpreter_dict != NULL)
412 {
413 PyObject *pfunc = NULL;
414 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
415 if (pmod != NULL)
416 {
417 PyObject *pmod_dict = PyModule_GetDict (pmod);
418 if ((pmod_dict != NULL)
419 && PyDict_Check (pmod_dict))
420 {
421 PyObject *key, *value;
422 Py_ssize_t pos = 0;
423
424 while (PyDict_Next (pmod_dict, &pos, &key, &value))
425 {
426 Py_INCREF (key);
427 Py_INCREF (value);
428 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
429 {
430 pfunc = value;
431 break;
432 }
433 }
434
435 PyObject *string_arg = PyString_FromString (command);
436 if (pfunc && string_arg && PyCallable_Check (pfunc))
437 {
438 PyObject *pargs = PyTuple_New (2);
439 if (pargs != NULL)
440 {
441 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
442 PyTuple_SetItem (pargs, 1, string_arg);
443 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
444 Py_DECREF (pargs);
445 if (pvalue != NULL)
446 {
447 Py_DECREF (pvalue);
448 success = true;
449 }
450 else if (PyErr_Occurred ())
451 {
452 PyErr_Print();
453 PyErr_Clear();
454 }
455 }
456 }
457 }
458 }
459 Py_INCREF (script_interpreter_dict);
460 }
461 }
Greg Clayton63094e02010-06-23 01:19:29 +0000462
Caroline Tice4a461da2011-01-14 21:09:29 +0000463 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000464 return true;
465
466 // The one-liner failed. Append the error message.
467 if (result)
468 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
469 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000470 }
Johnny Chen60dde642010-07-30 22:33:14 +0000471
472 if (result)
473 result->AppendError ("empty command passed to python\n");
474 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000475}
476
Chris Lattner24943d22010-06-08 16:52:24 +0000477size_t
478ScriptInterpreterPython::InputReaderCallback
479(
480 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000481 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000482 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000483 const char *bytes,
484 size_t bytes_len
485)
486{
Caroline Tice2ade6112010-11-10 19:18:14 +0000487 lldb::thread_t embedded_interpreter_thread;
488 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
489
Chris Lattner24943d22010-06-08 16:52:24 +0000490 if (baton == NULL)
491 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000492
493 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000494
Caroline Tice0aa2e552011-01-14 00:29:16 +0000495 if (script_interpreter->m_script_lang != eScriptLanguagePython)
496 return 0;
497
Caroline Tice892fadd2011-06-16 16:27:19 +0000498 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
499 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
500
Chris Lattner24943d22010-06-08 16:52:24 +0000501 switch (notification)
502 {
503 case eInputReaderActivate:
504 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000505 if (!batch_mode)
506 {
507 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
508 out_stream->Flush();
509 }
Greg Clayton58928562011-02-09 01:08:52 +0000510
Chris Lattner24943d22010-06-08 16:52:24 +0000511 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000512 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
513 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000514 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000515
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000516 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000517
Caroline Tice202f6b82011-01-17 21:55:19 +0000518 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000519 ScriptInterpreterPython::Locker locker(script_interpreter,
520 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
521 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000522 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000523
Caroline Tice2ade6112010-11-10 19:18:14 +0000524 char error_str[1024];
525 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
526 sizeof(error_str)))
527 {
528 if (log)
529 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
530 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
531 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
532 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
533 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000534 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000535 {
536 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000537 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000538 Error detach_error;
539 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
540 }
541 else
542 {
543 if (log)
544 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
545 reader.SetIsDone (true);
546 }
547 }
548 else
549 {
550 if (log)
551 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
552 reader.SetIsDone (true);
553 }
Chris Lattner24943d22010-06-08 16:52:24 +0000554 }
555 break;
556
557 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000558 // When another input reader is pushed, don't leave the session...
559 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000560 break;
561
562 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000563 {
Greg Claytona1cec242012-01-06 00:47:38 +0000564 // Don't try and acquire the interpreter lock here because code like
565 // this:
566 //
567 // (lldb) script
568 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
569 //
570 // This will cause the process to run. The interpreter lock is taken
571 // by the input reader for the "script" command. If we try and acquire
572 // the lock here, when the process runs it might deactivate this input
573 // reader (if STDIN is hooked up to the inferior process) and
574 // reactivate it when the process stops which will deadlock.
575 //ScriptInterpreterPython::Locker locker(script_interpreter,
576 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
577 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000578 }
Chris Lattner24943d22010-06-08 16:52:24 +0000579 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000580
Caroline Tice4a348082011-05-02 20:41:46 +0000581 case eInputReaderAsynchronousOutputWritten:
582 break;
583
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000584 case eInputReaderInterrupt:
585 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
586 break;
587
588 case eInputReaderEndOfFile:
589 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
590 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000591
592 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000593 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000594 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000595 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000596 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000597 bytes_len);
598 if (bytes && bytes_len)
599 {
600 if ((int) bytes[0] == 4)
601 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
602 else
603 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
604 }
605 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000606 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000607 else
608 {
609 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000610 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000611 bytes,
612 bytes_len);
613 reader.SetIsDone (true);
614 }
615
Chris Lattner24943d22010-06-08 16:52:24 +0000616 break;
617
618 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000619 script_interpreter->LeaveSession ();
620
Chris Lattner24943d22010-06-08 16:52:24 +0000621 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000622 if (log)
623 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000624
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000625 script_interpreter->RestoreTerminalState ();
626
Caroline Tice2ade6112010-11-10 19:18:14 +0000627 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000628 break;
629 }
630
631 return bytes_len;
632}
633
634
635void
Greg Clayton238c0a12010-09-18 01:14:36 +0000636ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000637{
638 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
639
Caroline Tice0aa2e552011-01-14 00:29:16 +0000640 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000641
642 // At the moment, the only time the debugger does not have an input file handle is when this is called
643 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
644 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
645 // do it.
646
Greg Clayton58928562011-02-09 01:08:52 +0000647 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000648 return;
649
Greg Clayton63094e02010-06-23 01:19:29 +0000650 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000651 if (reader_sp)
652 {
653 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
654 this, // baton
655 eInputReaderGranularityLine, // token size, to pass to callback function
656 NULL, // end token
657 NULL, // prompt
658 true)); // echo input
659
660 if (error.Success())
661 {
Greg Clayton63094e02010-06-23 01:19:29 +0000662 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000663 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000664 }
665 }
666}
667
668bool
669ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000670 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000671 void *ret_value)
672{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000673
Enrico Granatafa1f6172011-10-24 17:22:21 +0000674 Locker locker(this,
675 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
676 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000677
Chris Lattner24943d22010-06-08 16:52:24 +0000678 PyObject *py_return = NULL;
679 PyObject *mainmod = PyImport_AddModule ("__main__");
680 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000681 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000682 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000683 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000684 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000685 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000686
687 if (PyDict_Check (globals))
688 {
689 PyObject *key, *value;
690 Py_ssize_t pos = 0;
691
692 int i = 0;
693 while (PyDict_Next (globals, &pos, &key, &value))
694 {
695 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
696 // so that Python's garbage collector doesn't collect them out from under us.
697 Py_INCREF (key);
698 Py_INCREF (value);
699 char *c_str = PyString_AsString (key);
700 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
701 locals = value;
702 ++i;
703 }
704 }
Chris Lattner24943d22010-06-08 16:52:24 +0000705
Caroline Tice0aa2e552011-01-14 00:29:16 +0000706 if (locals == NULL)
707 {
708 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
709 should_decrement_locals = true;
710 }
711
712 if (locals == NULL)
713 {
714 locals = globals;
715 should_decrement_locals = false;
716 }
717
718 py_error = PyErr_Occurred();
719 if (py_error != NULL)
720 PyErr_Clear();
721
Chris Lattner24943d22010-06-08 16:52:24 +0000722 if (in_string != NULL)
723 {
724 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
725 if (py_return == NULL)
726 {
727 py_error = PyErr_Occurred ();
728 if (py_error != NULL)
729 PyErr_Clear ();
730
731 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
732 }
733
Caroline Tice0aa2e552011-01-14 00:29:16 +0000734 if (locals != NULL
735 && should_decrement_locals)
736 Py_DECREF (locals);
737
Chris Lattner24943d22010-06-08 16:52:24 +0000738 if (py_return != NULL)
739 {
740 switch (return_type)
741 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000742 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000743 {
744 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000745 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000746 break;
747 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000748 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000749 {
750 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000751 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000752 break;
753 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000754 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000755 {
756 const char format[2] = "b";
757 success = PyArg_Parse (py_return, format, (bool *) ret_value);
758 break;
759 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000760 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000761 {
762 const char format[2] = "h";
763 success = PyArg_Parse (py_return, format, (short *) ret_value);
764 break;
765 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000766 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000767 {
768 const char format[2] = "H";
769 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
770 break;
771 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000772 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000773 {
774 const char format[2] = "i";
775 success = PyArg_Parse (py_return, format, (int *) ret_value);
776 break;
777 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000778 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000779 {
780 const char format[2] = "I";
781 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
782 break;
783 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000784 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000785 {
786 const char format[2] = "l";
787 success = PyArg_Parse (py_return, format, (long *) ret_value);
788 break;
789 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000790 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000791 {
792 const char format[2] = "k";
793 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
794 break;
795 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000796 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000797 {
798 const char format[2] = "L";
799 success = PyArg_Parse (py_return, format, (long long *) ret_value);
800 break;
801 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000802 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000803 {
804 const char format[2] = "K";
805 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
806 break;
807 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000808 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000809 {
810 const char format[2] = "f";
811 success = PyArg_Parse (py_return, format, (float *) ret_value);
812 break;
813 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000814 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000815 {
816 const char format[2] = "d";
817 success = PyArg_Parse (py_return, format, (double *) ret_value);
818 break;
819 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000820 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000821 {
822 const char format[2] = "c";
823 success = PyArg_Parse (py_return, format, (char *) ret_value);
824 break;
825 }
826 default:
827 {}
828 }
829 Py_DECREF (py_return);
830 if (success)
831 ret_success = true;
832 else
833 ret_success = false;
834 }
835 }
836
837 py_error = PyErr_Occurred();
838 if (py_error != NULL)
839 {
840 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
841 PyErr_Print ();
842 PyErr_Clear();
843 ret_success = false;
844 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000845
Chris Lattner24943d22010-06-08 16:52:24 +0000846 return ret_success;
847}
848
849bool
850ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
851{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000852
853
854 Locker locker(this,
855 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
856 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000857
Chris Lattner24943d22010-06-08 16:52:24 +0000858 bool success = false;
859 PyObject *py_return = NULL;
860 PyObject *mainmod = PyImport_AddModule ("__main__");
861 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000862 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000863 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000864 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000865
Caroline Tice0aa2e552011-01-14 00:29:16 +0000866 if (PyDict_Check (globals))
867 {
868 PyObject *key, *value;
869 Py_ssize_t pos = 0;
870
871 while (PyDict_Next (globals, &pos, &key, &value))
872 {
873 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
874 // so that Python's garbage collector doesn't collect them out from under us.
875 Py_INCREF (key);
876 Py_INCREF (value);
877 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
878 locals = value;
879 }
880 }
881
882 if (locals == NULL)
883 {
884 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
885 should_decrement_locals = true;
886 }
887
888 if (locals == NULL)
889 {
890 locals = globals;
891 should_decrement_locals = false;
892 }
893
894 py_error = PyErr_Occurred();
895 if (py_error != NULL)
896 PyErr_Clear();
897
Chris Lattner24943d22010-06-08 16:52:24 +0000898 if (in_string != NULL)
899 {
900 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
901 if (compiled_node)
902 {
903 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
904 if (compiled_code)
905 {
906 py_return = PyEval_EvalCode (compiled_code, globals, locals);
907 if (py_return != NULL)
908 {
909 success = true;
910 Py_DECREF (py_return);
911 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000912 if (locals && should_decrement_locals)
913 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000914 }
915 }
916 }
917
918 py_error = PyErr_Occurred ();
919 if (py_error != NULL)
920 {
921 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
922 PyErr_Print ();
923 PyErr_Clear();
924 success = false;
925 }
926
927 return success;
928}
929
930static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
931
932size_t
933ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
934(
935 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000936 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000937 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000938 const char *bytes,
939 size_t bytes_len
940)
941{
Caroline Tice892fadd2011-06-16 16:27:19 +0000942 static StringList commands_in_progress;
943
944 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
945 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
946
Chris Lattner24943d22010-06-08 16:52:24 +0000947 switch (notification)
948 {
949 case eInputReaderActivate:
950 {
951 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +0000952 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +0000953 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000954 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000955 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +0000956 out_stream->Printf ("%s", reader.GetPrompt());
957 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +0000958 }
959 }
960 break;
961
962 case eInputReaderDeactivate:
963 break;
964
965 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +0000966 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000967 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000968 out_stream->Printf ("%s", reader.GetPrompt());
969 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +0000970 }
Chris Lattner24943d22010-06-08 16:52:24 +0000971 break;
972
Caroline Tice4a348082011-05-02 20:41:46 +0000973 case eInputReaderAsynchronousOutputWritten:
974 break;
975
Chris Lattner24943d22010-06-08 16:52:24 +0000976 case eInputReaderGotToken:
977 {
978 std::string temp_string (bytes, bytes_len);
979 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +0000980 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000981 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000982 out_stream->Printf ("%s", reader.GetPrompt());
983 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +0000984 }
Chris Lattner24943d22010-06-08 16:52:24 +0000985 }
986 break;
987
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000988 case eInputReaderEndOfFile:
989 case eInputReaderInterrupt:
990 // Control-c (SIGINT) & control-d both mean finish & exit.
991 reader.SetIsDone(true);
992
993 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
994 if (notification == eInputReaderInterrupt)
995 commands_in_progress.Clear();
996
997 // Fall through here...
998
Chris Lattner24943d22010-06-08 16:52:24 +0000999 case eInputReaderDone:
1000 {
1001 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1002 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1003 data_ap->user_source.AppendList (commands_in_progress);
1004 if (data_ap.get())
1005 {
Greg Clayton63094e02010-06-23 01:19:29 +00001006 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001007 if (interpreter)
1008 {
1009 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1010 data_ap->script_source))
1011 {
1012 if (data_ap->script_source.GetSize() == 1)
1013 {
1014 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1015 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1016 }
1017 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001018 else if (!batch_mode)
1019 {
1020 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1021 out_stream->Flush();
1022 }
Chris Lattner24943d22010-06-08 16:52:24 +00001023 }
1024 else
1025 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001026 if (!batch_mode)
1027 {
1028 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1029 out_stream->Flush();
1030 }
Chris Lattner24943d22010-06-08 16:52:24 +00001031 }
1032 }
1033 }
1034 break;
1035
1036 }
1037
1038 return bytes_len;
1039}
1040
1041void
Greg Clayton238c0a12010-09-18 01:14:36 +00001042ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001043 CommandReturnObject &result)
1044{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001045 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1046
Greg Clayton63094e02010-06-23 01:19:29 +00001047 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001048
1049 if (reader_sp)
1050 {
1051 Error err = reader_sp->Initialize (
1052 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1053 bp_options, // baton
1054 eInputReaderGranularityLine, // token size, for feeding data to callback function
1055 "DONE", // end token
1056 "> ", // prompt
1057 true); // echo input
1058
1059 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001060 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001061 else
1062 {
1063 result.AppendError (err.AsCString());
1064 result.SetStatus (eReturnStatusFailed);
1065 }
1066 }
1067 else
1068 {
1069 result.AppendError("out of memory");
1070 result.SetStatus (eReturnStatusFailed);
1071 }
1072}
1073
Johnny Chen3e0571b2010-09-11 00:23:59 +00001074// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001075void
Greg Clayton238c0a12010-09-18 01:14:36 +00001076ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001077 const char *oneliner)
1078{
1079 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1080
1081 // It's necessary to set both user_source and script_source to the oneliner.
1082 // The former is used to generate callback description (as in breakpoint command list)
1083 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001084
Johnny Chend1c2dca2010-09-10 18:21:10 +00001085 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001086
Caroline Tice5136f942010-09-27 21:35:15 +00001087 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1088 {
1089 if (data_ap->script_source.GetSize() == 1)
1090 {
1091 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1092 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1093 }
1094 }
1095
Johnny Chend1c2dca2010-09-10 18:21:10 +00001096 return;
1097}
1098
Chris Lattner24943d22010-06-08 16:52:24 +00001099bool
1100ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1101{
1102 // Convert StringList to one long, newline delimited, const char *.
1103 std::string function_def_string;
1104
1105 int num_lines = function_def.GetSize();
1106
1107 for (int i = 0; i < num_lines; ++i)
1108 {
1109 function_def_string.append (function_def.GetStringAtIndex(i));
1110 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1111 function_def_string.append ("\n");
1112
1113 }
1114
1115 return ExecuteMultipleLines (function_def_string.c_str());
1116}
1117
Enrico Granataf7a9b142011-07-15 02:26:42 +00001118// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1119// use this code to generate their functions
1120bool
1121ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1122{
1123 int num_lines = input.GetSize ();
1124 if (num_lines == 0)
1125 return false;
1126 StreamString sstr;
1127 StringList auto_generated_function;
1128 auto_generated_function.AppendString (signature.c_str());
1129 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1130 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1131 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1132 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1133 // global dictionary.
1134
1135 // Wrap everything up inside the function, increasing the indentation.
1136
1137 for (int i = 0; i < num_lines; ++i)
1138 {
1139 sstr.Clear ();
1140 sstr.Printf (" %s", input.GetStringAtIndex (i));
1141 auto_generated_function.AppendString (sstr.GetData());
1142 }
1143 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1144 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1145 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1146 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1147
1148 // Verify that the results are valid Python.
1149
1150 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1151 return false;
1152
1153 return true;
1154
1155}
1156
1157// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1158// given to generated functions, of course)
1159bool
1160ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output)
1161{
1162 static int num_created_functions = 0;
1163 user_input.RemoveBlankLines ();
1164 int num_lines = user_input.GetSize ();
1165 StreamString sstr;
1166
1167 // Check to see if we have any data; if not, just return.
1168 if (user_input.GetSize() == 0)
1169 return false;
1170
1171 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1172 // ValueObject as parameter to the function.
1173
1174 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1175 ++num_created_functions;
1176 std::string auto_generated_function_name = sstr.GetData();
1177
1178 sstr.Clear();
1179 StringList auto_generated_function;
1180
1181 // Create the function name & definition string.
1182
1183 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1184 auto_generated_function.AppendString (sstr.GetData());
1185
1186 // Pre-pend code for setting up the session dictionary.
1187
1188 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1189 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1190 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1191 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1192 // global dictionary.
1193
1194 // Wrap everything up inside the function, increasing the indentation.
1195
1196 for (int i = 0; i < num_lines; ++i)
1197 {
1198 sstr.Clear ();
1199 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1200 auto_generated_function.AppendString (sstr.GetData());
1201 }
1202
1203 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1204 // got written to the values in the global dictionary, not the session dictionary).
1205
1206 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1207 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1208 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1209 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1210
1211 // Verify that the results are valid Python.
1212
1213 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1214 return false;
1215
1216 // Store the name of the auto-generated function to be called.
1217
1218 output.AppendString (auto_generated_function_name.c_str());
1219 return true;
1220}
1221
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001222bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001223ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, StringList &output)
1224{
1225 static int num_created_functions = 0;
1226 user_input.RemoveBlankLines ();
1227 int num_lines = user_input.GetSize ();
1228 StreamString sstr;
1229
1230 // Check to see if we have any data; if not, just return.
1231 if (user_input.GetSize() == 0)
1232 return false;
1233
1234 // 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 +00001235 // required data as parameters to the function.
Enrico Granatac2a28252011-08-16 16:49:25 +00001236
1237 sstr.Printf ("lldb_autogen_python_cmd_alias_func_%d", num_created_functions);
1238 ++num_created_functions;
1239 std::string auto_generated_function_name = sstr.GetData();
1240
1241 sstr.Clear();
1242 StringList auto_generated_function;
1243
1244 // Create the function name & definition string.
1245
Enrico Granata271568f2011-09-09 01:41:30 +00001246 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001247 auto_generated_function.AppendString (sstr.GetData());
1248
1249 // Pre-pend code for setting up the session dictionary.
1250
1251 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1252 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1253 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1254 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1255 // global dictionary.
1256
1257 // Wrap everything up inside the function, increasing the indentation.
1258
1259 for (int i = 0; i < num_lines; ++i)
1260 {
1261 sstr.Clear ();
1262 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1263 auto_generated_function.AppendString (sstr.GetData());
1264 }
1265
1266 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1267 // got written to the values in the global dictionary, not the session dictionary).
1268
1269 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1270 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1271 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1272 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1273
1274 // Verify that the results are valid Python.
1275
1276 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1277 return false;
1278
1279 // Store the name of the auto-generated function to be called.
1280
1281 output.AppendString (auto_generated_function_name.c_str());
1282 return true;
1283}
1284
1285
1286bool
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001287ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output)
1288{
1289 static int num_created_classes = 0;
1290 user_input.RemoveBlankLines ();
1291 int num_lines = user_input.GetSize ();
1292 StreamString sstr;
1293
1294 // Check to see if we have any data; if not, just return.
1295 if (user_input.GetSize() == 0)
1296 return false;
1297
1298 // Wrap all user input into a Python class
1299
1300 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1301 ++num_created_classes;
1302 std::string auto_generated_class_name = sstr.GetData();
1303
1304 sstr.Clear();
1305 StringList auto_generated_class;
1306
1307 // Create the function name & definition string.
1308
1309 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1310 auto_generated_class.AppendString (sstr.GetData());
1311
1312 // Wrap everything up inside the class, increasing the indentation.
1313
1314 for (int i = 0; i < num_lines; ++i)
1315 {
1316 sstr.Clear ();
1317 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1318 auto_generated_class.AppendString (sstr.GetData());
1319 }
1320
1321
1322 // Verify that the results are valid Python.
1323 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1324 // (TODO: rename that method to ExportDefinitionToInterpreter)
1325 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1326 return false;
1327
1328 // Store the name of the auto-generated class
1329
1330 output.AppendString (auto_generated_class_name.c_str());
1331 return true;
1332}
1333
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001334void*
1335ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1336 lldb::ValueObjectSP valobj)
1337{
1338 if (class_name.empty())
1339 return NULL;
1340
1341 if (!valobj.get())
1342 return NULL;
1343
Enrico Granata979e20d2011-07-29 19:53:35 +00001344 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001345
1346 if (!target)
1347 return NULL;
1348
1349 Debugger &debugger = target->GetDebugger();
1350 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1351 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1352
1353 if (!script_interpreter)
1354 return NULL;
1355
1356 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001357
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001358 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001359 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001360 ret_val = g_swig_synthetic_script (class_name,
1361 python_interpreter->m_dictionary_name.c_str(),
1362 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001363 }
1364
1365 return ret_val;
1366}
1367
Enrico Granataf7a9b142011-07-15 02:26:42 +00001368bool
1369ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output)
1370{
1371 StringList input(oneliner);
1372 return GenerateTypeScriptFunction(input, output);
1373}
1374
Chris Lattner24943d22010-06-08 16:52:24 +00001375bool
1376ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1377{
1378 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001379 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001380 int num_lines = user_input.GetSize ();
1381 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001382
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001383 // Check to see if we have any data; if not, just return.
1384 if (user_input.GetSize() == 0)
1385 return false;
1386
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001387 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1388 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001389
Caroline Ticeb447e842010-09-21 19:25:28 +00001390
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001391 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1392 ++num_created_functions;
1393 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001394
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001395 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001396 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001397
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001398 // Create the function name & definition string.
1399
Caroline Tice0aa2e552011-01-14 00:29:16 +00001400 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001401 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001402
1403 // Pre-pend code for setting up the session dictionary.
1404
1405 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1406 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1407 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1408 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1409 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001410
1411 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001412
1413 for (int i = 0; i < num_lines; ++i)
1414 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001415 sstr.Clear ();
1416 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1417 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001418 }
Chris Lattner24943d22010-06-08 16:52:24 +00001419
Caroline Tice0aa2e552011-01-14 00:29:16 +00001420 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1421 // got written to the values in the global dictionary, not the session dictionary).
1422
1423 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1424 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1425 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1426 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1427
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001428 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001429
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001430 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001431 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001432 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001433 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001434
1435 // Store the name of the auto-generated function to be called.
1436
1437 callback_data.AppendString (auto_generated_function_name.c_str());
1438 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001439}
1440
Enrico Granataf7a9b142011-07-15 02:26:42 +00001441std::string
1442ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1443 lldb::ValueObjectSP valobj)
1444{
1445
1446 if (!python_function_name || !(*python_function_name))
1447 return "<no function>";
1448
1449 if (!valobj.get())
1450 return "<no object>";
1451
Enrico Granata979e20d2011-07-29 19:53:35 +00001452 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001453
1454 if (!target)
1455 return "<no target>";
1456
1457 Debugger &debugger = target->GetDebugger();
1458 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1459 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1460
1461 if (!script_interpreter)
1462 return "<no python>";
1463
1464 std::string ret_val;
1465
1466 if (python_function_name
1467 && *python_function_name)
1468 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001469 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001470 Locker py_lock(python_interpreter);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001471 ret_val = g_swig_typescript_callback (python_function_name,
1472 python_interpreter->m_dictionary_name.c_str(),
1473 valobj);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001474 }
1475 }
1476 else
1477 return "<no function name>";
1478
1479 return ret_val;
1480
1481}
1482
Greg Clayton5144f382010-10-07 17:14:24 +00001483bool
1484ScriptInterpreterPython::BreakpointCallbackFunction
1485(
1486 void *baton,
1487 StoppointCallbackContext *context,
1488 user_id_t break_id,
1489 user_id_t break_loc_id
1490)
1491{
1492 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1493 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001494
1495 if (!context)
1496 return true;
1497
Greg Clayton567e7f32011-09-22 04:58:26 +00001498 Target *target = context->exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001499
1500 if (!target)
1501 return true;
1502
1503 Debugger &debugger = target->GetDebugger();
1504 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1505 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1506
1507 if (!script_interpreter)
1508 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001509
1510 if (python_function_name != NULL
1511 && python_function_name[0] != '\0')
1512 {
Greg Clayton567e7f32011-09-22 04:58:26 +00001513 const StackFrameSP stop_frame_sp (context->exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001514 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001515 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001516 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001517 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1518
1519 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001520 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001521 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001522 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001523 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001524 ret_val = g_swig_breakpoint_callback (python_function_name,
1525 python_interpreter->m_dictionary_name.c_str(),
1526 stop_frame_sp,
1527 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001528 }
1529 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001530 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001531 }
Greg Clayton5144f382010-10-07 17:14:24 +00001532 }
1533 // We currently always true so we stop in case anything goes wrong when
1534 // trying to call the script function
1535 return true;
1536}
Caroline Tice2ade6112010-11-10 19:18:14 +00001537
1538lldb::thread_result_t
1539ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1540{
1541 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1542
1543 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1544
1545 if (log)
1546 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1547
1548 char error_str[1024];
1549 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001550
Enrico Granatafa1f6172011-10-24 17:22:21 +00001551 Locker locker(script_interpreter,
1552 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1553 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1554
1555 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001556 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001557 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001558
Caroline Tice0aa2e552011-01-14 00:29:16 +00001559 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", 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, 'sys.stderr = sys.stdout')", 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, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1568 PyRun_SimpleString (run_string.GetData());
1569 run_string.Clear ();
1570
1571 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1572 pty_slave_name);
1573 PyRun_SimpleString (run_string.GetData());
1574 run_string.Clear ();
1575
Johnny Chen8054ba32011-03-11 00:28:50 +00001576 // The following call drops into the embedded interpreter loop and stays there until the
1577 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001578
Caroline Ticece207c12011-03-11 00:21:55 +00001579 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001580 // 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 +00001581 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1582
1583 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1584 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1585 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1586 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1587 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1588 // hang (it's happened before).
1589
Caroline Tice9d352ce2011-03-07 23:24:28 +00001590 Py_BEGIN_ALLOW_THREADS
1591 PyGILState_STATE gstate = PyGILState_Ensure();
1592
Caroline Tice0aa2e552011-01-14 00:29:16 +00001593 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1594 PyRun_SimpleString (run_string.GetData());
1595 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001596
Caroline Tice9d352ce2011-03-07 23:24:28 +00001597 PyGILState_Release (gstate);
1598 Py_END_ALLOW_THREADS
1599
Caroline Tice0aa2e552011-01-14 00:29:16 +00001600 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1601 PyRun_SimpleString (run_string.GetData());
1602 run_string.Clear();
1603
1604 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1605 PyRun_SimpleString (run_string.GetData());
1606 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001607
Caroline Tice2ade6112010-11-10 19:18:14 +00001608 }
1609
1610 if (script_interpreter->m_embedded_thread_input_reader_sp)
1611 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1612
1613 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001614
Caroline Tice2ade6112010-11-10 19:18:14 +00001615 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1616 if (log)
1617 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1618
1619
Johnny Chen8054ba32011-03-11 00:28:50 +00001620 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001621 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001622 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1623 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1624 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001625
Caroline Tice2ade6112010-11-10 19:18:14 +00001626 return NULL;
1627}
1628
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001629uint32_t
1630ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1631{
1632 if (!implementor)
1633 return 0;
1634
1635 if (!g_swig_calc_children)
1636 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001637
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001638 uint32_t ret_val = 0;
1639
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001640 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001641 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001642 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001643 }
1644
1645 return ret_val;
1646}
1647
Enrico Granata91544802011-09-06 19:20:51 +00001648lldb::ValueObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001649ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1650{
1651 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001652 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001653
Enrico Granata91544802011-09-06 19:20:51 +00001654 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1655 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001656
Enrico Granata91544802011-09-06 19:20:51 +00001657 void* child_ptr = NULL;
1658 lldb::SBValue* value_sb = NULL;
1659 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001660
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001661 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001662 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +00001663 child_ptr = g_swig_get_child_index (implementor,idx);
1664 if (child_ptr != NULL && child_ptr != Py_None)
1665 {
1666 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1667 if (value_sb == NULL)
1668 Py_XDECREF(child_ptr);
1669 else
1670 ret_val = value_sb->get_sp();
1671 }
1672 else
1673 {
1674 Py_XDECREF(child_ptr);
1675 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001676 }
1677
1678 return ret_val;
1679}
1680
1681int
1682ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1683{
1684 if (!implementor)
1685 return UINT32_MAX;
1686
1687 if (!g_swig_get_index_child)
1688 return UINT32_MAX;
1689
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001690 int ret_val = UINT32_MAX;
1691
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001692 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001693 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001694 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001695 }
1696
1697 return ret_val;
1698}
1699
Enrico Granata979e20d2011-07-29 19:53:35 +00001700void
1701ScriptInterpreterPython::UpdateSynthProviderInstance (void* implementor)
1702{
1703 if (!implementor)
1704 return;
1705
1706 if (!g_swig_update_provider)
1707 return;
1708
Enrico Granata979e20d2011-07-29 19:53:35 +00001709 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001710 Locker py_lock(this);
Enrico Granata979e20d2011-07-29 19:53:35 +00001711 g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001712 }
1713
1714 return;
1715}
1716
Enrico Granatac2a28252011-08-16 16:49:25 +00001717bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001718ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00001719 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00001720 lldb_private::Error& error)
1721{
1722 if (!pathname || !pathname[0])
1723 {
1724 error.SetErrorString("invalid pathname");
1725 return false;
1726 }
1727
1728 if (!g_swig_call_module_init)
1729 {
1730 error.SetErrorString("internal helper function missing");
1731 return false;
1732 }
1733
Greg Clayton13d24fb2012-01-29 20:56:30 +00001734 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granatafa1f6172011-10-24 17:22:21 +00001735
Enrico Granata59df36f2011-10-17 21:45:27 +00001736 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001737 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00001738
1739 FileSpec target_file(pathname, true);
1740
1741 // TODO: would we want to reject any other value?
1742 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1743 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1744 {
1745 error.SetErrorString("invalid pathname");
1746 return false;
1747 }
1748
1749 const char* directory = target_file.GetDirectory().GetCString();
1750 std::string basename(target_file.GetFilename().GetCString());
1751
1752 // now make sure that Python has "directory" in the search path
1753 StreamString command_stream;
1754 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1755 directory,
1756 directory);
Enrico Granatafa1f6172011-10-24 17:22:21 +00001757 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData());
Enrico Granata59df36f2011-10-17 21:45:27 +00001758 if (!syspath_retval)
1759 {
1760 error.SetErrorString("Python sys.path handling failed");
1761 return false;
1762 }
1763
1764 // strip .py or .pyc extension
1765 ConstString extension = target_file.GetFileNameExtension();
1766 if (::strcmp(extension.GetCString(), "py") == 0)
1767 basename.resize(basename.length()-3);
1768 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1769 basename.resize(basename.length()-4);
1770
1771 // check if the module is already import-ed
1772 command_stream.Clear();
1773 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1774 int refcount = 0;
1775 // this call will fail if the module does not exist (because the parameter to it is not a string
1776 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00001777 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
1778 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0);
1779 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00001780 {
1781 error.SetErrorString("module already imported");
1782 return false;
1783 }
1784
1785 // now actually do the import
1786 command_stream.Clear();
1787 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafa1f6172011-10-24 17:22:21 +00001788 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL);
Enrico Granata59df36f2011-10-17 21:45:27 +00001789 if (!import_retval)
1790 {
1791 error.SetErrorString("Python import statement failed");
1792 return false;
1793 }
1794
1795 // call __lldb_module_init(debugger,dict)
1796 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001797 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001798 debugger_sp))
1799 {
1800 error.SetErrorString("calling __lldb_module_init failed");
1801 return false;
1802 }
1803 return true;
1804 }
1805}
1806
Enrico Granata6010ace2011-11-07 22:57:04 +00001807ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
1808 ScriptedCommandSynchronicity synchro) :
1809 m_debugger_sp(debugger_sp),
1810 m_synch_wanted(synchro),
1811 m_old_asynch(debugger_sp->GetAsyncExecution())
1812{
1813 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
1814 m_debugger_sp->SetAsyncExecution(false);
1815 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
1816 m_debugger_sp->SetAsyncExecution(true);
1817}
1818
1819ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
1820{
1821 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
1822 m_debugger_sp->SetAsyncExecution(m_old_asynch);
1823}
1824
Enrico Granata59df36f2011-10-17 21:45:27 +00001825bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001826ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1827 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00001828 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001829 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001830 Error& error)
1831{
1832 if (!impl_function)
1833 {
1834 error.SetErrorString("no function to execute");
1835 return false;
1836 }
1837
1838 if (!g_swig_call_command)
1839 {
1840 error.SetErrorString("no helper function to run scripted commands");
1841 return false;
1842 }
1843
Greg Clayton13d24fb2012-01-29 20:56:30 +00001844 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata6010ace2011-11-07 22:57:04 +00001845
1846 if (!debugger_sp.get())
1847 {
1848 error.SetErrorString("invalid Debugger pointer");
1849 return false;
1850 }
Enrico Granatac2a28252011-08-16 16:49:25 +00001851
1852 bool ret_val;
1853
1854 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00001855
Enrico Granatac2a28252011-08-16 16:49:25 +00001856 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001857 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00001858 SynchronicityHandler synch_handler(debugger_sp,
1859 synchronicity);
1860
Enrico Granatac2a28252011-08-16 16:49:25 +00001861 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001862 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00001863 debugger_sp,
1864 args,
1865 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001866 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001867 }
Enrico Granata6010ace2011-11-07 22:57:04 +00001868
Enrico Granatac2a28252011-08-16 16:49:25 +00001869 if (!ret_val)
1870 error.SetErrorString(err_msg.c_str());
1871 else
1872 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00001873
Enrico Granatac2a28252011-08-16 16:49:25 +00001874 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00001875}
1876
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001877// in Python, a special attribute __doc__ contains the docstring
1878// for an object (function, method, class, ...) if any is defined
1879// Otherwise, the attribute's value is None
1880std::string
1881ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1882{
1883 std::string command(item);
1884 command += ".__doc__";
1885
1886 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1887
1888 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001889 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001890 &result_ptr) && result_ptr)
1891 {
1892 return std::string(result_ptr);
1893 }
1894 else
1895 return std::string("");
1896}
Caroline Tice2ade6112010-11-10 19:18:14 +00001897
Caroline Tice0aa2e552011-01-14 00:29:16 +00001898void
Greg Claytone86cbb92011-03-22 01:14:58 +00001899ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00001900 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001901 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
1902 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
1903 SWIGPythonCalculateNumChildren python_swig_calc_children,
1904 SWIGPythonGetChildAtIndex python_swig_get_child_index,
1905 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
Enrico Granata979e20d2011-07-29 19:53:35 +00001906 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue,
Enrico Granatac2a28252011-08-16 16:49:25 +00001907 SWIGPythonUpdateSynthProviderInstance python_swig_update_provider,
Enrico Granata59df36f2011-10-17 21:45:27 +00001908 SWIGPythonCallCommand python_swig_call_command,
1909 SWIGPythonCallModuleInit python_swig_call_mod_init)
Greg Claytone86cbb92011-03-22 01:14:58 +00001910{
1911 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001912 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1913 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001914 g_swig_synthetic_script = python_swig_synthetic_script;
1915 g_swig_calc_children = python_swig_calc_children;
1916 g_swig_get_child_index = python_swig_get_child_index;
1917 g_swig_get_index_child = python_swig_get_index_child;
1918 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Enrico Granata979e20d2011-07-29 19:53:35 +00001919 g_swig_update_provider = python_swig_update_provider;
Enrico Granatac2a28252011-08-16 16:49:25 +00001920 g_swig_call_command = python_swig_call_command;
Enrico Granata59df36f2011-10-17 21:45:27 +00001921 g_swig_call_module_init = python_swig_call_mod_init;
Greg Claytone86cbb92011-03-22 01:14:58 +00001922}
1923
1924void
1925ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001926{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001927 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1928
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001929 // Python will muck with STDIN terminal state, so save off any current TTY
1930 // settings so we can restore them.
1931 TerminalState stdin_tty_state;
1932 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001933
Caroline Tice9d352ce2011-03-07 23:24:28 +00001934 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001935 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001936
Greg Claytone86cbb92011-03-22 01:14:58 +00001937 // Initialize SWIG after setting up python
1938 assert (g_swig_init_callback != NULL);
1939 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001940
1941 // Update the path python uses to search for modules to include the current directory.
1942
Caroline Ticed4d92832011-06-13 21:33:00 +00001943 PyRun_SimpleString ("import sys");
1944 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001945
1946 // Find the module that owns this code and use that path we get to
1947 // set the sys.path appropriately.
1948
1949 FileSpec file_spec;
1950 char python_dir_path[PATH_MAX];
1951 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1952 {
1953 std::string python_path("sys.path.insert(0,\"");
1954 size_t orig_len = python_path.length();
1955 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1956 {
1957 python_path.append (python_dir_path);
1958 python_path.append ("\")");
1959 PyRun_SimpleString (python_path.c_str());
1960 python_path.resize (orig_len);
1961 }
1962
1963 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1964 {
1965 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1966 {
1967 python_path.append (python_dir_path);
1968 python_path.append ("\")");
1969 PyRun_SimpleString (python_path.c_str());
1970 python_path.resize (orig_len);
1971 }
1972 }
1973 }
1974
Jim Ingham4dfa5112011-08-22 19:10:09 +00001975 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001976
Caroline Ticed4d92832011-06-13 21:33:00 +00001977 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001978
Caroline Ticed4d92832011-06-13 21:33:00 +00001979 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1980 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00001981 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001982
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001983 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001984}
1985
Greg Claytone86cbb92011-03-22 01:14:58 +00001986//void
1987//ScriptInterpreterPython::Terminate ()
1988//{
1989// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1990// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1991// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1992// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1993// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1994// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1995// // within Py_Finalize, which results in a seg fault.
1996// //
1997// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1998// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1999// // process exits).
2000// //
2001//// Py_Finalize ();
2002//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00002003
2004#endif // #ifdef LLDB_DISABLE_PYTHON