blob: 213a69ed922cd818634b2578237481ddd1c6852a [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),
190 m_pty_slave_is_open (false),
191 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000192{
193
Greg Clayton7c330d62011-01-27 01:01:10 +0000194 static int g_initialized = false;
195
196 if (!g_initialized)
197 {
198 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000199 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000200 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000201
202 Locker locker(this,
203 ScriptInterpreterPython::Locker::AcquireLock,
204 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Greg Clayton7c330d62011-01-27 01:01:10 +0000205
Caroline Tice0aa2e552011-01-14 00:29:16 +0000206 m_dictionary_name.append("_dict");
207 StreamString run_string;
208 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
209 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000210
Caroline Tice0aa2e552011-01-14 00:29:16 +0000211 run_string.Clear();
212 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
213 PyRun_SimpleString (run_string.GetData());
214
215 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
216 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
217 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
218 // call to Debugger::Terminate is made, the ref-count has the correct value.
219 //
220 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
221 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000222
Caroline Tice0aa2e552011-01-14 00:29:16 +0000223 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000224
Caroline Tice0aa2e552011-01-14 00:29:16 +0000225 run_string.Clear();
226 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
227 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000228
Caroline Tice0aa2e552011-01-14 00:29:16 +0000229 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000230
Caroline Tice0aa2e552011-01-14 00:29:16 +0000231 if (new_count > old_count)
232 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000233
Caroline Tice0aa2e552011-01-14 00:29:16 +0000234 run_string.Clear();
235 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
236 PyRun_SimpleString (run_string.GetData());
237
238 run_string.Clear();
Enrico Granata59df36f2011-10-17 21:45:27 +0000239 run_string.Printf ("run_one_line (%s, 'import os')", m_dictionary_name.c_str());
240 PyRun_SimpleString (run_string.GetData());
241
242 run_string.Clear();
Greg Clayton444e35b2011-10-19 18:09:39 +0000243 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000244 interpreter.GetDebugger().GetID());
245 PyRun_SimpleString (run_string.GetData());
246
Enrico Granata074e3b62011-08-17 19:07:52 +0000247 run_string.Clear();
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000248 run_string.Printf ("run_one_line (%s, 'import gnu_libstdcpp')", m_dictionary_name.c_str());
Enrico Granata074e3b62011-08-17 19:07:52 +0000249 PyRun_SimpleString (run_string.GetData());
250
Caroline Tice0aa2e552011-01-14 00:29:16 +0000251 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000252 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000253 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000254 }
Chris Lattner24943d22010-06-08 16:52:24 +0000255}
256
257ScriptInterpreterPython::~ScriptInterpreterPython ()
258{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000259 Debugger &debugger = GetCommandInterpreter().GetDebugger();
260
261 if (m_embedded_thread_input_reader_sp.get() != NULL)
262 {
263 m_embedded_thread_input_reader_sp->SetIsDone (true);
264 m_embedded_python_pty.CloseSlaveFileDescriptor();
265 m_pty_slave_is_open = false;
266 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
267 m_embedded_thread_input_reader_sp.reset();
268 debugger.PopInputReader (reader_sp);
269 }
270
271 if (m_new_sysout)
272 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000273 Locker locker(this,
274 ScriptInterpreterPython::Locker::AcquireLock,
275 ScriptInterpreterPython::Locker::FreeLock);
276 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000277 }
Chris Lattner24943d22010-06-08 16:52:24 +0000278}
279
Caroline Tice0aa2e552011-01-14 00:29:16 +0000280void
281ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
282{
283 if (fh == NULL)
284 return;
285
286 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000287
Enrico Granatafa1f6172011-10-24 17:22:21 +0000288 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +0000289
290 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000291}
292
293void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000294ScriptInterpreterPython::SaveTerminalState (int fd)
295{
296 // Python mucks with the terminal state of STDIN. If we can possibly avoid
297 // this by setting the file handles up correctly prior to entering the
298 // interpreter we should. For now we save and restore the terminal state
299 // on the input file handle.
300 m_terminal_state.Save (fd, false);
301}
302
303void
304ScriptInterpreterPython::RestoreTerminalState ()
305{
306 // Python mucks with the terminal state of STDIN. If we can possibly avoid
307 // this by setting the file handles up correctly prior to entering the
308 // interpreter we should. For now we save and restore the terminal state
309 // on the input file handle.
310 m_terminal_state.Restore();
311}
312
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000313void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000314ScriptInterpreterPython::LeaveSession ()
315{
316 m_session_is_active = false;
317}
318
319void
320ScriptInterpreterPython::EnterSession ()
321{
322 // If we have already entered the session, without having officially 'left' it, then there is no need to
323 // 'enter' it again.
324
325 if (m_session_is_active)
326 return;
327
328 m_session_is_active = true;
329
Caroline Tice202f6b82011-01-17 21:55:19 +0000330 StreamString run_string;
331
Greg Clayton444e35b2011-10-19 18:09:39 +0000332 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice202f6b82011-01-17 21:55:19 +0000333 GetCommandInterpreter().GetDebugger().GetID());
334 PyRun_SimpleString (run_string.GetData());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000335 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +0000336
Caroline Tice0aa2e552011-01-14 00:29:16 +0000337
Greg Clayton444e35b2011-10-19 18:09:39 +0000338 run_string.Printf ("run_one_line (%s, 'lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)')",
Caroline Tice6af65cb2011-05-03 21:21:50 +0000339 m_dictionary_name.c_str(),
340 GetCommandInterpreter().GetDebugger().GetID());
341 PyRun_SimpleString (run_string.GetData());
342 run_string.Clear();
343
344
Greg Clayton567e7f32011-09-22 04:58:26 +0000345 ExecutionContext exe_ctx (m_interpreter.GetDebugger().GetSelectedExecutionContext());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000346
Greg Clayton567e7f32011-09-22 04:58:26 +0000347 if (exe_ctx.GetTargetPtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000348 run_string.Printf ("run_one_line (%s, 'lldb.target = lldb.debugger.GetSelectedTarget()')",
349 m_dictionary_name.c_str());
350 else
351 run_string.Printf ("run_one_line (%s, 'lldb.target = None')", m_dictionary_name.c_str());
352 PyRun_SimpleString (run_string.GetData());
353 run_string.Clear();
354
Greg Clayton567e7f32011-09-22 04:58:26 +0000355 if (exe_ctx.GetProcessPtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000356 run_string.Printf ("run_one_line (%s, 'lldb.process = lldb.target.GetProcess()')", m_dictionary_name.c_str());
357 else
358 run_string.Printf ("run_one_line (%s, 'lldb.process = None')", m_dictionary_name.c_str());
359 PyRun_SimpleString (run_string.GetData());
360 run_string.Clear();
361
Greg Clayton567e7f32011-09-22 04:58:26 +0000362 if (exe_ctx.GetThreadPtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000363 run_string.Printf ("run_one_line (%s, 'lldb.thread = lldb.process.GetSelectedThread ()')",
364 m_dictionary_name.c_str());
365 else
366 run_string.Printf ("run_one_line (%s, 'lldb.thread = None')", m_dictionary_name.c_str());
367 PyRun_SimpleString (run_string.GetData());
368 run_string.Clear();
369
Greg Clayton567e7f32011-09-22 04:58:26 +0000370 if (exe_ctx.GetFramePtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000371 run_string.Printf ("run_one_line (%s, 'lldb.frame = lldb.thread.GetSelectedFrame ()')",
372 m_dictionary_name.c_str());
373 else
374 run_string.Printf ("run_one_line (%s, 'lldb.frame = None')", m_dictionary_name.c_str());
375 PyRun_SimpleString (run_string.GetData());
376 run_string.Clear();
377
Caroline Tice0aa2e552011-01-14 00:29:16 +0000378 PyObject *sysmod = PyImport_AddModule ("sys");
379 PyObject *sysdict = PyModule_GetDict (sysmod);
380
381 if ((m_new_sysout != NULL)
382 && (sysmod != NULL)
383 && (sysdict != NULL))
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +0000384 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000385
386 if (PyErr_Occurred())
387 PyErr_Clear ();
388
Caroline Tice0aa2e552011-01-14 00:29:16 +0000389 if (!m_pty_slave_is_open)
390 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000391 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000392 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
393 m_pty_slave_name.c_str());
394 PyRun_SimpleString (run_string.GetData());
395 m_pty_slave_is_open = true;
396
397 run_string.Clear();
398 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
399 PyRun_SimpleString (run_string.GetData());
400 }
401}
402
403
Johnny Chen60dde642010-07-30 22:33:14 +0000404bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000405ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000406{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000407 if (!m_valid_session)
408 return false;
409
Caroline Tice4a461da2011-01-14 21:09:29 +0000410 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
411 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
412 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
413 // method to pass the command string directly down to Python.
414
Enrico Granatafa1f6172011-10-24 17:22:21 +0000415 Locker locker(this,
416 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
417 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000418
419 bool success = false;
420
Greg Clayton63094e02010-06-23 01:19:29 +0000421 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000422 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000423 // Find the correct script interpreter dictionary in the main module.
424 PyObject *main_mod = PyImport_AddModule ("__main__");
425 PyObject *script_interpreter_dict = NULL;
426 if (main_mod != NULL)
427 {
428 PyObject *main_dict = PyModule_GetDict (main_mod);
429 if ((main_dict != NULL)
430 && PyDict_Check (main_dict))
431 {
432 // Go through the main dictionary looking for the correct python script interpreter dictionary
433 PyObject *key, *value;
434 Py_ssize_t pos = 0;
435
436 while (PyDict_Next (main_dict, &pos, &key, &value))
437 {
438 // We have stolen references to the key and value objects in the dictionary; we need to increment
439 // them now so that Python's garbage collector doesn't collect them out from under us.
440 Py_INCREF (key);
441 Py_INCREF (value);
442 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
443 {
444 script_interpreter_dict = value;
445 break;
446 }
447 }
448 }
449
450 if (script_interpreter_dict != NULL)
451 {
452 PyObject *pfunc = NULL;
453 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
454 if (pmod != NULL)
455 {
456 PyObject *pmod_dict = PyModule_GetDict (pmod);
457 if ((pmod_dict != NULL)
458 && PyDict_Check (pmod_dict))
459 {
460 PyObject *key, *value;
461 Py_ssize_t pos = 0;
462
463 while (PyDict_Next (pmod_dict, &pos, &key, &value))
464 {
465 Py_INCREF (key);
466 Py_INCREF (value);
467 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
468 {
469 pfunc = value;
470 break;
471 }
472 }
473
474 PyObject *string_arg = PyString_FromString (command);
475 if (pfunc && string_arg && PyCallable_Check (pfunc))
476 {
477 PyObject *pargs = PyTuple_New (2);
478 if (pargs != NULL)
479 {
480 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
481 PyTuple_SetItem (pargs, 1, string_arg);
482 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
483 Py_DECREF (pargs);
484 if (pvalue != NULL)
485 {
486 Py_DECREF (pvalue);
487 success = true;
488 }
489 else if (PyErr_Occurred ())
490 {
491 PyErr_Print();
492 PyErr_Clear();
493 }
494 }
495 }
496 }
497 }
498 Py_INCREF (script_interpreter_dict);
499 }
500 }
Greg Clayton63094e02010-06-23 01:19:29 +0000501
Caroline Tice4a461da2011-01-14 21:09:29 +0000502 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000503 return true;
504
505 // The one-liner failed. Append the error message.
506 if (result)
507 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
508 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000509 }
Johnny Chen60dde642010-07-30 22:33:14 +0000510
511 if (result)
512 result->AppendError ("empty command passed to python\n");
513 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000514}
515
Chris Lattner24943d22010-06-08 16:52:24 +0000516size_t
517ScriptInterpreterPython::InputReaderCallback
518(
519 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000520 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000521 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000522 const char *bytes,
523 size_t bytes_len
524)
525{
Caroline Tice2ade6112010-11-10 19:18:14 +0000526 lldb::thread_t embedded_interpreter_thread;
527 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
528
Chris Lattner24943d22010-06-08 16:52:24 +0000529 if (baton == NULL)
530 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000531
532 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000533
Caroline Tice0aa2e552011-01-14 00:29:16 +0000534 if (script_interpreter->m_script_lang != eScriptLanguagePython)
535 return 0;
536
Caroline Tice892fadd2011-06-16 16:27:19 +0000537 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
538 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
539
Chris Lattner24943d22010-06-08 16:52:24 +0000540 switch (notification)
541 {
542 case eInputReaderActivate:
543 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000544 if (!batch_mode)
545 {
546 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
547 out_stream->Flush();
548 }
Greg Clayton58928562011-02-09 01:08:52 +0000549
Chris Lattner24943d22010-06-08 16:52:24 +0000550 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000551 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
552 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000553 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000554
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000555 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000556
Caroline Tice202f6b82011-01-17 21:55:19 +0000557 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000558 ScriptInterpreterPython::Locker locker(script_interpreter,
559 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
560 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000561 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000562
Caroline Tice2ade6112010-11-10 19:18:14 +0000563 char error_str[1024];
564 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
565 sizeof(error_str)))
566 {
567 if (log)
568 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
569 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
570 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
571 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
572 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000573 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000574 {
575 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000576 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000577 Error detach_error;
578 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
579 }
580 else
581 {
582 if (log)
583 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
584 reader.SetIsDone (true);
585 }
586 }
587 else
588 {
589 if (log)
590 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
591 reader.SetIsDone (true);
592 }
Chris Lattner24943d22010-06-08 16:52:24 +0000593 }
594 break;
595
596 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000597 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000598 break;
599
600 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000601 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000602 ScriptInterpreterPython::Locker locker(script_interpreter,
603 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
604 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000605 }
Chris Lattner24943d22010-06-08 16:52:24 +0000606 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000607
Caroline Tice4a348082011-05-02 20:41:46 +0000608 case eInputReaderAsynchronousOutputWritten:
609 break;
610
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000611 case eInputReaderInterrupt:
612 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
613 break;
614
615 case eInputReaderEndOfFile:
616 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
617 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000618
619 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000620 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000621 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000622 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000623 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000624 bytes_len);
625 if (bytes && bytes_len)
626 {
627 if ((int) bytes[0] == 4)
628 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
629 else
630 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
631 }
632 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000633 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000634 else
635 {
636 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000637 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000638 bytes,
639 bytes_len);
640 reader.SetIsDone (true);
641 }
642
Chris Lattner24943d22010-06-08 16:52:24 +0000643 break;
644
645 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000646 script_interpreter->LeaveSession ();
647
Chris Lattner24943d22010-06-08 16:52:24 +0000648 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000649 if (log)
650 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000651
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000652 script_interpreter->RestoreTerminalState ();
653
Caroline Tice2ade6112010-11-10 19:18:14 +0000654 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000655 break;
656 }
657
658 return bytes_len;
659}
660
661
662void
Greg Clayton238c0a12010-09-18 01:14:36 +0000663ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000664{
665 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
666
Caroline Tice0aa2e552011-01-14 00:29:16 +0000667 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000668
669 // At the moment, the only time the debugger does not have an input file handle is when this is called
670 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
671 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
672 // do it.
673
Greg Clayton58928562011-02-09 01:08:52 +0000674 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000675 return;
676
Greg Clayton63094e02010-06-23 01:19:29 +0000677 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000678 if (reader_sp)
679 {
680 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
681 this, // baton
682 eInputReaderGranularityLine, // token size, to pass to callback function
683 NULL, // end token
684 NULL, // prompt
685 true)); // echo input
686
687 if (error.Success())
688 {
Greg Clayton63094e02010-06-23 01:19:29 +0000689 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000690 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000691 }
692 }
693}
694
695bool
696ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000697 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000698 void *ret_value)
699{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000700
Enrico Granatafa1f6172011-10-24 17:22:21 +0000701 Locker locker(this,
702 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
703 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000704
Chris Lattner24943d22010-06-08 16:52:24 +0000705 PyObject *py_return = NULL;
706 PyObject *mainmod = PyImport_AddModule ("__main__");
707 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000708 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000709 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000710 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000711 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000712 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000713
714 if (PyDict_Check (globals))
715 {
716 PyObject *key, *value;
717 Py_ssize_t pos = 0;
718
719 int i = 0;
720 while (PyDict_Next (globals, &pos, &key, &value))
721 {
722 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
723 // so that Python's garbage collector doesn't collect them out from under us.
724 Py_INCREF (key);
725 Py_INCREF (value);
726 char *c_str = PyString_AsString (key);
727 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
728 locals = value;
729 ++i;
730 }
731 }
Chris Lattner24943d22010-06-08 16:52:24 +0000732
Caroline Tice0aa2e552011-01-14 00:29:16 +0000733 if (locals == NULL)
734 {
735 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
736 should_decrement_locals = true;
737 }
738
739 if (locals == NULL)
740 {
741 locals = globals;
742 should_decrement_locals = false;
743 }
744
745 py_error = PyErr_Occurred();
746 if (py_error != NULL)
747 PyErr_Clear();
748
Chris Lattner24943d22010-06-08 16:52:24 +0000749 if (in_string != NULL)
750 {
751 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
752 if (py_return == NULL)
753 {
754 py_error = PyErr_Occurred ();
755 if (py_error != NULL)
756 PyErr_Clear ();
757
758 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
759 }
760
Caroline Tice0aa2e552011-01-14 00:29:16 +0000761 if (locals != NULL
762 && should_decrement_locals)
763 Py_DECREF (locals);
764
Chris Lattner24943d22010-06-08 16:52:24 +0000765 if (py_return != NULL)
766 {
767 switch (return_type)
768 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000769 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000770 {
771 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000772 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000773 break;
774 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000775 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000776 {
777 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000778 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000779 break;
780 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000781 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000782 {
783 const char format[2] = "b";
784 success = PyArg_Parse (py_return, format, (bool *) ret_value);
785 break;
786 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000787 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000788 {
789 const char format[2] = "h";
790 success = PyArg_Parse (py_return, format, (short *) ret_value);
791 break;
792 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000793 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000794 {
795 const char format[2] = "H";
796 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
797 break;
798 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000799 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000800 {
801 const char format[2] = "i";
802 success = PyArg_Parse (py_return, format, (int *) ret_value);
803 break;
804 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000805 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000806 {
807 const char format[2] = "I";
808 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
809 break;
810 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000811 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000812 {
813 const char format[2] = "l";
814 success = PyArg_Parse (py_return, format, (long *) ret_value);
815 break;
816 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000817 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000818 {
819 const char format[2] = "k";
820 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
821 break;
822 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000823 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000824 {
825 const char format[2] = "L";
826 success = PyArg_Parse (py_return, format, (long long *) ret_value);
827 break;
828 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000829 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000830 {
831 const char format[2] = "K";
832 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
833 break;
834 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000835 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000836 {
837 const char format[2] = "f";
838 success = PyArg_Parse (py_return, format, (float *) ret_value);
839 break;
840 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000841 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000842 {
843 const char format[2] = "d";
844 success = PyArg_Parse (py_return, format, (double *) ret_value);
845 break;
846 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000847 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000848 {
849 const char format[2] = "c";
850 success = PyArg_Parse (py_return, format, (char *) ret_value);
851 break;
852 }
853 default:
854 {}
855 }
856 Py_DECREF (py_return);
857 if (success)
858 ret_success = true;
859 else
860 ret_success = false;
861 }
862 }
863
864 py_error = PyErr_Occurred();
865 if (py_error != NULL)
866 {
867 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
868 PyErr_Print ();
869 PyErr_Clear();
870 ret_success = false;
871 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000872
Chris Lattner24943d22010-06-08 16:52:24 +0000873 return ret_success;
874}
875
876bool
877ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
878{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000879
880
881 Locker locker(this,
882 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
883 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000884
Chris Lattner24943d22010-06-08 16:52:24 +0000885 bool success = false;
886 PyObject *py_return = NULL;
887 PyObject *mainmod = PyImport_AddModule ("__main__");
888 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000889 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000890 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000891 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000892
Caroline Tice0aa2e552011-01-14 00:29:16 +0000893 if (PyDict_Check (globals))
894 {
895 PyObject *key, *value;
896 Py_ssize_t pos = 0;
897
898 while (PyDict_Next (globals, &pos, &key, &value))
899 {
900 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
901 // so that Python's garbage collector doesn't collect them out from under us.
902 Py_INCREF (key);
903 Py_INCREF (value);
904 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
905 locals = value;
906 }
907 }
908
909 if (locals == NULL)
910 {
911 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
912 should_decrement_locals = true;
913 }
914
915 if (locals == NULL)
916 {
917 locals = globals;
918 should_decrement_locals = false;
919 }
920
921 py_error = PyErr_Occurred();
922 if (py_error != NULL)
923 PyErr_Clear();
924
Chris Lattner24943d22010-06-08 16:52:24 +0000925 if (in_string != NULL)
926 {
927 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
928 if (compiled_node)
929 {
930 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
931 if (compiled_code)
932 {
933 py_return = PyEval_EvalCode (compiled_code, globals, locals);
934 if (py_return != NULL)
935 {
936 success = true;
937 Py_DECREF (py_return);
938 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000939 if (locals && should_decrement_locals)
940 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000941 }
942 }
943 }
944
945 py_error = PyErr_Occurred ();
946 if (py_error != NULL)
947 {
948 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
949 PyErr_Print ();
950 PyErr_Clear();
951 success = false;
952 }
953
954 return success;
955}
956
957static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
958
959size_t
960ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
961(
962 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000963 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000964 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000965 const char *bytes,
966 size_t bytes_len
967)
968{
Caroline Tice892fadd2011-06-16 16:27:19 +0000969 static StringList commands_in_progress;
970
971 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
972 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
973
Chris Lattner24943d22010-06-08 16:52:24 +0000974 switch (notification)
975 {
976 case eInputReaderActivate:
977 {
978 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +0000979 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +0000980 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000981 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000982 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +0000983 out_stream->Printf ("%s", reader.GetPrompt());
984 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +0000985 }
986 }
987 break;
988
989 case eInputReaderDeactivate:
990 break;
991
992 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +0000993 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000994 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000995 out_stream->Printf ("%s", reader.GetPrompt());
996 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +0000997 }
Chris Lattner24943d22010-06-08 16:52:24 +0000998 break;
999
Caroline Tice4a348082011-05-02 20:41:46 +00001000 case eInputReaderAsynchronousOutputWritten:
1001 break;
1002
Chris Lattner24943d22010-06-08 16:52:24 +00001003 case eInputReaderGotToken:
1004 {
1005 std::string temp_string (bytes, bytes_len);
1006 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001007 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001008 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001009 out_stream->Printf ("%s", reader.GetPrompt());
1010 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001011 }
Chris Lattner24943d22010-06-08 16:52:24 +00001012 }
1013 break;
1014
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001015 case eInputReaderEndOfFile:
1016 case eInputReaderInterrupt:
1017 // Control-c (SIGINT) & control-d both mean finish & exit.
1018 reader.SetIsDone(true);
1019
1020 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1021 if (notification == eInputReaderInterrupt)
1022 commands_in_progress.Clear();
1023
1024 // Fall through here...
1025
Chris Lattner24943d22010-06-08 16:52:24 +00001026 case eInputReaderDone:
1027 {
1028 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1029 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1030 data_ap->user_source.AppendList (commands_in_progress);
1031 if (data_ap.get())
1032 {
Greg Clayton63094e02010-06-23 01:19:29 +00001033 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001034 if (interpreter)
1035 {
1036 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1037 data_ap->script_source))
1038 {
1039 if (data_ap->script_source.GetSize() == 1)
1040 {
1041 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1042 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1043 }
1044 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001045 else if (!batch_mode)
1046 {
1047 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1048 out_stream->Flush();
1049 }
Chris Lattner24943d22010-06-08 16:52:24 +00001050 }
1051 else
1052 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001053 if (!batch_mode)
1054 {
1055 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1056 out_stream->Flush();
1057 }
Chris Lattner24943d22010-06-08 16:52:24 +00001058 }
1059 }
1060 }
1061 break;
1062
1063 }
1064
1065 return bytes_len;
1066}
1067
1068void
Greg Clayton238c0a12010-09-18 01:14:36 +00001069ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001070 CommandReturnObject &result)
1071{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001072 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1073
Greg Clayton63094e02010-06-23 01:19:29 +00001074 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001075
1076 if (reader_sp)
1077 {
1078 Error err = reader_sp->Initialize (
1079 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1080 bp_options, // baton
1081 eInputReaderGranularityLine, // token size, for feeding data to callback function
1082 "DONE", // end token
1083 "> ", // prompt
1084 true); // echo input
1085
1086 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001087 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001088 else
1089 {
1090 result.AppendError (err.AsCString());
1091 result.SetStatus (eReturnStatusFailed);
1092 }
1093 }
1094 else
1095 {
1096 result.AppendError("out of memory");
1097 result.SetStatus (eReturnStatusFailed);
1098 }
1099}
1100
Johnny Chen3e0571b2010-09-11 00:23:59 +00001101// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001102void
Greg Clayton238c0a12010-09-18 01:14:36 +00001103ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001104 const char *oneliner)
1105{
1106 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1107
1108 // It's necessary to set both user_source and script_source to the oneliner.
1109 // The former is used to generate callback description (as in breakpoint command list)
1110 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001111
Johnny Chend1c2dca2010-09-10 18:21:10 +00001112 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001113
Caroline Tice5136f942010-09-27 21:35:15 +00001114 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1115 {
1116 if (data_ap->script_source.GetSize() == 1)
1117 {
1118 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1119 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1120 }
1121 }
1122
Johnny Chend1c2dca2010-09-10 18:21:10 +00001123 return;
1124}
1125
Chris Lattner24943d22010-06-08 16:52:24 +00001126bool
1127ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1128{
1129 // Convert StringList to one long, newline delimited, const char *.
1130 std::string function_def_string;
1131
1132 int num_lines = function_def.GetSize();
1133
1134 for (int i = 0; i < num_lines; ++i)
1135 {
1136 function_def_string.append (function_def.GetStringAtIndex(i));
1137 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1138 function_def_string.append ("\n");
1139
1140 }
1141
1142 return ExecuteMultipleLines (function_def_string.c_str());
1143}
1144
Enrico Granataf7a9b142011-07-15 02:26:42 +00001145// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1146// use this code to generate their functions
1147bool
1148ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1149{
1150 int num_lines = input.GetSize ();
1151 if (num_lines == 0)
1152 return false;
1153 StreamString sstr;
1154 StringList auto_generated_function;
1155 auto_generated_function.AppendString (signature.c_str());
1156 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1157 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1158 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1159 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1160 // global dictionary.
1161
1162 // Wrap everything up inside the function, increasing the indentation.
1163
1164 for (int i = 0; i < num_lines; ++i)
1165 {
1166 sstr.Clear ();
1167 sstr.Printf (" %s", input.GetStringAtIndex (i));
1168 auto_generated_function.AppendString (sstr.GetData());
1169 }
1170 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1171 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1172 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1173 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1174
1175 // Verify that the results are valid Python.
1176
1177 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1178 return false;
1179
1180 return true;
1181
1182}
1183
1184// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1185// given to generated functions, of course)
1186bool
1187ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output)
1188{
1189 static int num_created_functions = 0;
1190 user_input.RemoveBlankLines ();
1191 int num_lines = user_input.GetSize ();
1192 StreamString sstr;
1193
1194 // Check to see if we have any data; if not, just return.
1195 if (user_input.GetSize() == 0)
1196 return false;
1197
1198 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1199 // ValueObject as parameter to the function.
1200
1201 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1202 ++num_created_functions;
1203 std::string auto_generated_function_name = sstr.GetData();
1204
1205 sstr.Clear();
1206 StringList auto_generated_function;
1207
1208 // Create the function name & definition string.
1209
1210 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1211 auto_generated_function.AppendString (sstr.GetData());
1212
1213 // Pre-pend code for setting up the session dictionary.
1214
1215 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1216 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1217 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1218 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1219 // global dictionary.
1220
1221 // Wrap everything up inside the function, increasing the indentation.
1222
1223 for (int i = 0; i < num_lines; ++i)
1224 {
1225 sstr.Clear ();
1226 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1227 auto_generated_function.AppendString (sstr.GetData());
1228 }
1229
1230 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1231 // got written to the values in the global dictionary, not the session dictionary).
1232
1233 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1234 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1235 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1236 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1237
1238 // Verify that the results are valid Python.
1239
1240 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1241 return false;
1242
1243 // Store the name of the auto-generated function to be called.
1244
1245 output.AppendString (auto_generated_function_name.c_str());
1246 return true;
1247}
1248
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001249bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001250ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, StringList &output)
1251{
1252 static int num_created_functions = 0;
1253 user_input.RemoveBlankLines ();
1254 int num_lines = user_input.GetSize ();
1255 StreamString sstr;
1256
1257 // Check to see if we have any data; if not, just return.
1258 if (user_input.GetSize() == 0)
1259 return false;
1260
1261 // 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 +00001262 // required data as parameters to the function.
Enrico Granatac2a28252011-08-16 16:49:25 +00001263
1264 sstr.Printf ("lldb_autogen_python_cmd_alias_func_%d", num_created_functions);
1265 ++num_created_functions;
1266 std::string auto_generated_function_name = sstr.GetData();
1267
1268 sstr.Clear();
1269 StringList auto_generated_function;
1270
1271 // Create the function name & definition string.
1272
Enrico Granata271568f2011-09-09 01:41:30 +00001273 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001274 auto_generated_function.AppendString (sstr.GetData());
1275
1276 // Pre-pend code for setting up the session dictionary.
1277
1278 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1279 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1280 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1281 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1282 // global dictionary.
1283
1284 // Wrap everything up inside the function, increasing the indentation.
1285
1286 for (int i = 0; i < num_lines; ++i)
1287 {
1288 sstr.Clear ();
1289 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1290 auto_generated_function.AppendString (sstr.GetData());
1291 }
1292
1293 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1294 // got written to the values in the global dictionary, not the session dictionary).
1295
1296 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1297 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1298 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1299 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1300
1301 // Verify that the results are valid Python.
1302
1303 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1304 return false;
1305
1306 // Store the name of the auto-generated function to be called.
1307
1308 output.AppendString (auto_generated_function_name.c_str());
1309 return true;
1310}
1311
1312
1313bool
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001314ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output)
1315{
1316 static int num_created_classes = 0;
1317 user_input.RemoveBlankLines ();
1318 int num_lines = user_input.GetSize ();
1319 StreamString sstr;
1320
1321 // Check to see if we have any data; if not, just return.
1322 if (user_input.GetSize() == 0)
1323 return false;
1324
1325 // Wrap all user input into a Python class
1326
1327 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1328 ++num_created_classes;
1329 std::string auto_generated_class_name = sstr.GetData();
1330
1331 sstr.Clear();
1332 StringList auto_generated_class;
1333
1334 // Create the function name & definition string.
1335
1336 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1337 auto_generated_class.AppendString (sstr.GetData());
1338
1339 // Wrap everything up inside the class, increasing the indentation.
1340
1341 for (int i = 0; i < num_lines; ++i)
1342 {
1343 sstr.Clear ();
1344 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1345 auto_generated_class.AppendString (sstr.GetData());
1346 }
1347
1348
1349 // Verify that the results are valid Python.
1350 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1351 // (TODO: rename that method to ExportDefinitionToInterpreter)
1352 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1353 return false;
1354
1355 // Store the name of the auto-generated class
1356
1357 output.AppendString (auto_generated_class_name.c_str());
1358 return true;
1359}
1360
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001361void*
1362ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1363 lldb::ValueObjectSP valobj)
1364{
1365 if (class_name.empty())
1366 return NULL;
1367
1368 if (!valobj.get())
1369 return NULL;
1370
Enrico Granata979e20d2011-07-29 19:53:35 +00001371 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001372
1373 if (!target)
1374 return NULL;
1375
1376 Debugger &debugger = target->GetDebugger();
1377 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1378 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1379
1380 if (!script_interpreter)
1381 return NULL;
1382
1383 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001384
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001385 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001386 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001387 ret_val = g_swig_synthetic_script (class_name,
1388 python_interpreter->m_dictionary_name.c_str(),
1389 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001390 }
1391
1392 return ret_val;
1393}
1394
Enrico Granataf7a9b142011-07-15 02:26:42 +00001395bool
1396ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output)
1397{
1398 StringList input(oneliner);
1399 return GenerateTypeScriptFunction(input, output);
1400}
1401
Chris Lattner24943d22010-06-08 16:52:24 +00001402bool
1403ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1404{
1405 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001406 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001407 int num_lines = user_input.GetSize ();
1408 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001409
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001410 // Check to see if we have any data; if not, just return.
1411 if (user_input.GetSize() == 0)
1412 return false;
1413
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001414 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1415 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001416
Caroline Ticeb447e842010-09-21 19:25:28 +00001417
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001418 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1419 ++num_created_functions;
1420 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001421
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001422 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001423 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001424
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001425 // Create the function name & definition string.
1426
Caroline Tice0aa2e552011-01-14 00:29:16 +00001427 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001428 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001429
1430 // Pre-pend code for setting up the session dictionary.
1431
1432 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1433 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1434 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1435 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1436 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001437
1438 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001439
1440 for (int i = 0; i < num_lines; ++i)
1441 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001442 sstr.Clear ();
1443 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1444 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001445 }
Chris Lattner24943d22010-06-08 16:52:24 +00001446
Caroline Tice0aa2e552011-01-14 00:29:16 +00001447 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1448 // got written to the values in the global dictionary, not the session dictionary).
1449
1450 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1451 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1452 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1453 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1454
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001455 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001456
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001457 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001458 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001459 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001460 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001461
1462 // Store the name of the auto-generated function to be called.
1463
1464 callback_data.AppendString (auto_generated_function_name.c_str());
1465 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001466}
1467
Enrico Granataf7a9b142011-07-15 02:26:42 +00001468std::string
1469ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1470 lldb::ValueObjectSP valobj)
1471{
1472
1473 if (!python_function_name || !(*python_function_name))
1474 return "<no function>";
1475
1476 if (!valobj.get())
1477 return "<no object>";
1478
Enrico Granata979e20d2011-07-29 19:53:35 +00001479 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001480
1481 if (!target)
1482 return "<no target>";
1483
1484 Debugger &debugger = target->GetDebugger();
1485 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1486 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1487
1488 if (!script_interpreter)
1489 return "<no python>";
1490
1491 std::string ret_val;
1492
1493 if (python_function_name
1494 && *python_function_name)
1495 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001496 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001497 Locker py_lock(python_interpreter);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001498 ret_val = g_swig_typescript_callback (python_function_name,
1499 python_interpreter->m_dictionary_name.c_str(),
1500 valobj);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001501 }
1502 }
1503 else
1504 return "<no function name>";
1505
1506 return ret_val;
1507
1508}
1509
Greg Clayton5144f382010-10-07 17:14:24 +00001510bool
1511ScriptInterpreterPython::BreakpointCallbackFunction
1512(
1513 void *baton,
1514 StoppointCallbackContext *context,
1515 user_id_t break_id,
1516 user_id_t break_loc_id
1517)
1518{
1519 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1520 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001521
1522 if (!context)
1523 return true;
1524
Greg Clayton567e7f32011-09-22 04:58:26 +00001525 Target *target = context->exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001526
1527 if (!target)
1528 return true;
1529
1530 Debugger &debugger = target->GetDebugger();
1531 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1532 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1533
1534 if (!script_interpreter)
1535 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001536
1537 if (python_function_name != NULL
1538 && python_function_name[0] != '\0')
1539 {
Greg Clayton567e7f32011-09-22 04:58:26 +00001540 const StackFrameSP stop_frame_sp (context->exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001541 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001542 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001543 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001544 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1545
1546 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001547 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001548 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001549 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001550 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001551 ret_val = g_swig_breakpoint_callback (python_function_name,
1552 python_interpreter->m_dictionary_name.c_str(),
1553 stop_frame_sp,
1554 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001555 }
1556 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001557 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001558 }
Greg Clayton5144f382010-10-07 17:14:24 +00001559 }
1560 // We currently always true so we stop in case anything goes wrong when
1561 // trying to call the script function
1562 return true;
1563}
Caroline Tice2ade6112010-11-10 19:18:14 +00001564
1565lldb::thread_result_t
1566ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1567{
1568 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1569
1570 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1571
1572 if (log)
1573 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1574
1575 char error_str[1024];
1576 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001577
Enrico Granatafa1f6172011-10-24 17:22:21 +00001578 Locker locker(script_interpreter,
1579 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1580 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1581
1582 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001583 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001584 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001585
Caroline Tice0aa2e552011-01-14 00:29:16 +00001586 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1587 PyRun_SimpleString (run_string.GetData());
1588 run_string.Clear ();
1589
1590 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1591 PyRun_SimpleString (run_string.GetData());
1592 run_string.Clear ();
1593
1594 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1595 PyRun_SimpleString (run_string.GetData());
1596 run_string.Clear ();
1597
1598 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1599 pty_slave_name);
1600 PyRun_SimpleString (run_string.GetData());
1601 run_string.Clear ();
1602
Johnny Chen8054ba32011-03-11 00:28:50 +00001603 // The following call drops into the embedded interpreter loop and stays there until the
1604 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001605
Caroline Ticece207c12011-03-11 00:21:55 +00001606 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001607 // 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 +00001608 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1609
1610 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1611 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1612 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1613 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1614 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1615 // hang (it's happened before).
1616
Caroline Tice9d352ce2011-03-07 23:24:28 +00001617 Py_BEGIN_ALLOW_THREADS
1618 PyGILState_STATE gstate = PyGILState_Ensure();
1619
Caroline Tice0aa2e552011-01-14 00:29:16 +00001620 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1621 PyRun_SimpleString (run_string.GetData());
1622 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001623
Caroline Tice9d352ce2011-03-07 23:24:28 +00001624 PyGILState_Release (gstate);
1625 Py_END_ALLOW_THREADS
1626
Caroline Tice0aa2e552011-01-14 00:29:16 +00001627 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1628 PyRun_SimpleString (run_string.GetData());
1629 run_string.Clear();
1630
1631 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1632 PyRun_SimpleString (run_string.GetData());
1633 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001634
Caroline Tice2ade6112010-11-10 19:18:14 +00001635 }
1636
1637 if (script_interpreter->m_embedded_thread_input_reader_sp)
1638 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1639
1640 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001641
1642 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001643
1644 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1645 if (log)
1646 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1647
1648
Johnny Chen8054ba32011-03-11 00:28:50 +00001649 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001650 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001651 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1652 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1653 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001654
Caroline Tice2ade6112010-11-10 19:18:14 +00001655 return NULL;
1656}
1657
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001658uint32_t
1659ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1660{
1661 if (!implementor)
1662 return 0;
1663
1664 if (!g_swig_calc_children)
1665 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001666
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001667 uint32_t ret_val = 0;
1668
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001669 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001670 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001671 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001672 }
1673
1674 return ret_val;
1675}
1676
Enrico Granata91544802011-09-06 19:20:51 +00001677lldb::ValueObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001678ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1679{
1680 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001681 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001682
Enrico Granata91544802011-09-06 19:20:51 +00001683 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1684 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001685
Enrico Granata91544802011-09-06 19:20:51 +00001686 void* child_ptr = NULL;
1687 lldb::SBValue* value_sb = NULL;
1688 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001689
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001690 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001691 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +00001692 child_ptr = g_swig_get_child_index (implementor,idx);
1693 if (child_ptr != NULL && child_ptr != Py_None)
1694 {
1695 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1696 if (value_sb == NULL)
1697 Py_XDECREF(child_ptr);
1698 else
1699 ret_val = value_sb->get_sp();
1700 }
1701 else
1702 {
1703 Py_XDECREF(child_ptr);
1704 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001705 }
1706
1707 return ret_val;
1708}
1709
1710int
1711ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1712{
1713 if (!implementor)
1714 return UINT32_MAX;
1715
1716 if (!g_swig_get_index_child)
1717 return UINT32_MAX;
1718
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001719 int ret_val = UINT32_MAX;
1720
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001721 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001722 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001723 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001724 }
1725
1726 return ret_val;
1727}
1728
Enrico Granata979e20d2011-07-29 19:53:35 +00001729void
1730ScriptInterpreterPython::UpdateSynthProviderInstance (void* implementor)
1731{
1732 if (!implementor)
1733 return;
1734
1735 if (!g_swig_update_provider)
1736 return;
1737
Enrico Granata979e20d2011-07-29 19:53:35 +00001738 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001739 Locker py_lock(this);
Enrico Granata979e20d2011-07-29 19:53:35 +00001740 g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001741 }
1742
1743 return;
1744}
1745
Enrico Granatac2a28252011-08-16 16:49:25 +00001746bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001747ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
1748 lldb_private::Error& error)
1749{
1750 if (!pathname || !pathname[0])
1751 {
1752 error.SetErrorString("invalid pathname");
1753 return false;
1754 }
1755
1756 if (!g_swig_call_module_init)
1757 {
1758 error.SetErrorString("internal helper function missing");
1759 return false;
1760 }
1761
Enrico Granata59df36f2011-10-17 21:45:27 +00001762 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
Enrico Granatafa1f6172011-10-24 17:22:21 +00001763
Enrico Granata59df36f2011-10-17 21:45:27 +00001764 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001765 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00001766
1767 FileSpec target_file(pathname, true);
1768
1769 // TODO: would we want to reject any other value?
1770 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1771 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1772 {
1773 error.SetErrorString("invalid pathname");
1774 return false;
1775 }
1776
1777 const char* directory = target_file.GetDirectory().GetCString();
1778 std::string basename(target_file.GetFilename().GetCString());
1779
1780 // now make sure that Python has "directory" in the search path
1781 StreamString command_stream;
1782 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1783 directory,
1784 directory);
Enrico Granatafa1f6172011-10-24 17:22:21 +00001785 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData());
Enrico Granata59df36f2011-10-17 21:45:27 +00001786 if (!syspath_retval)
1787 {
1788 error.SetErrorString("Python sys.path handling failed");
1789 return false;
1790 }
1791
1792 // strip .py or .pyc extension
1793 ConstString extension = target_file.GetFileNameExtension();
1794 if (::strcmp(extension.GetCString(), "py") == 0)
1795 basename.resize(basename.length()-3);
1796 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1797 basename.resize(basename.length()-4);
1798
1799 // check if the module is already import-ed
1800 command_stream.Clear();
1801 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1802 int refcount = 0;
1803 // this call will fail if the module does not exist (because the parameter to it is not a string
1804 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granatafa1f6172011-10-24 17:22:21 +00001805 if (ExecuteOneLineWithReturn(command_stream.GetData(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001806 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0)
1807 {
1808 error.SetErrorString("module already imported");
1809 return false;
1810 }
1811
1812 // now actually do the import
1813 command_stream.Clear();
1814 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafa1f6172011-10-24 17:22:21 +00001815 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL);
Enrico Granata59df36f2011-10-17 21:45:27 +00001816 if (!import_retval)
1817 {
1818 error.SetErrorString("Python import statement failed");
1819 return false;
1820 }
1821
1822 // call __lldb_module_init(debugger,dict)
1823 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001824 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001825 debugger_sp))
1826 {
1827 error.SetErrorString("calling __lldb_module_init failed");
1828 return false;
1829 }
1830 return true;
1831 }
1832}
1833
1834bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001835ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1836 const char* args,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001837 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001838 Error& error)
1839{
1840 if (!impl_function)
1841 {
1842 error.SetErrorString("no function to execute");
1843 return false;
1844 }
1845
1846 if (!g_swig_call_command)
1847 {
1848 error.SetErrorString("no helper function to run scripted commands");
1849 return false;
1850 }
1851
Enrico Granatac2a28252011-08-16 16:49:25 +00001852 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
1853
1854 bool ret_val;
1855
1856 std::string err_msg;
1857
Enrico Granatac2a28252011-08-16 16:49:25 +00001858 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001859 Locker py_lock(this);
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 }
1867
1868 if (!ret_val)
1869 error.SetErrorString(err_msg.c_str());
1870 else
1871 error.Clear();
Enrico Granata3370f0c2011-08-19 23:56:34 +00001872
Enrico Granatac2a28252011-08-16 16:49:25 +00001873 return ret_val;
1874
1875
1876 return true;
1877
1878}
1879
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001880// in Python, a special attribute __doc__ contains the docstring
1881// for an object (function, method, class, ...) if any is defined
1882// Otherwise, the attribute's value is None
1883std::string
1884ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1885{
1886 std::string command(item);
1887 command += ".__doc__";
1888
1889 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1890
1891 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001892 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001893 &result_ptr) && result_ptr)
1894 {
1895 return std::string(result_ptr);
1896 }
1897 else
1898 return std::string("");
1899}
Caroline Tice2ade6112010-11-10 19:18:14 +00001900
Caroline Tice0aa2e552011-01-14 00:29:16 +00001901void
Greg Claytone86cbb92011-03-22 01:14:58 +00001902ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00001903 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001904 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
1905 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
1906 SWIGPythonCalculateNumChildren python_swig_calc_children,
1907 SWIGPythonGetChildAtIndex python_swig_get_child_index,
1908 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
Enrico Granata979e20d2011-07-29 19:53:35 +00001909 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue,
Enrico Granatac2a28252011-08-16 16:49:25 +00001910 SWIGPythonUpdateSynthProviderInstance python_swig_update_provider,
Enrico Granata59df36f2011-10-17 21:45:27 +00001911 SWIGPythonCallCommand python_swig_call_command,
1912 SWIGPythonCallModuleInit python_swig_call_mod_init)
Greg Claytone86cbb92011-03-22 01:14:58 +00001913{
1914 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001915 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1916 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001917 g_swig_synthetic_script = python_swig_synthetic_script;
1918 g_swig_calc_children = python_swig_calc_children;
1919 g_swig_get_child_index = python_swig_get_child_index;
1920 g_swig_get_index_child = python_swig_get_index_child;
1921 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Enrico Granata979e20d2011-07-29 19:53:35 +00001922 g_swig_update_provider = python_swig_update_provider;
Enrico Granatac2a28252011-08-16 16:49:25 +00001923 g_swig_call_command = python_swig_call_command;
Enrico Granata59df36f2011-10-17 21:45:27 +00001924 g_swig_call_module_init = python_swig_call_mod_init;
Greg Claytone86cbb92011-03-22 01:14:58 +00001925}
1926
1927void
1928ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001929{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001930 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1931
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001932 // Python will muck with STDIN terminal state, so save off any current TTY
1933 // settings so we can restore them.
1934 TerminalState stdin_tty_state;
1935 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001936
Caroline Tice9d352ce2011-03-07 23:24:28 +00001937 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001938 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001939
Greg Claytone86cbb92011-03-22 01:14:58 +00001940 // Initialize SWIG after setting up python
1941 assert (g_swig_init_callback != NULL);
1942 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001943
1944 // Update the path python uses to search for modules to include the current directory.
1945
Caroline Ticed4d92832011-06-13 21:33:00 +00001946 PyRun_SimpleString ("import sys");
1947 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001948
1949 // Find the module that owns this code and use that path we get to
1950 // set the sys.path appropriately.
1951
1952 FileSpec file_spec;
1953 char python_dir_path[PATH_MAX];
1954 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1955 {
1956 std::string python_path("sys.path.insert(0,\"");
1957 size_t orig_len = python_path.length();
1958 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1959 {
1960 python_path.append (python_dir_path);
1961 python_path.append ("\")");
1962 PyRun_SimpleString (python_path.c_str());
1963 python_path.resize (orig_len);
1964 }
1965
1966 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1967 {
1968 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1969 {
1970 python_path.append (python_dir_path);
1971 python_path.append ("\")");
1972 PyRun_SimpleString (python_path.c_str());
1973 python_path.resize (orig_len);
1974 }
1975 }
1976 }
1977
Jim Ingham4dfa5112011-08-22 19:10:09 +00001978 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001979
Caroline Ticed4d92832011-06-13 21:33:00 +00001980 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001981
Caroline Ticed4d92832011-06-13 21:33:00 +00001982 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1983 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00001984 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001985
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001986 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001987}
1988
Greg Claytone86cbb92011-03-22 01:14:58 +00001989//void
1990//ScriptInterpreterPython::Terminate ()
1991//{
1992// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1993// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1994// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1995// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1996// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1997// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1998// // within Py_Finalize, which results in a seg fault.
1999// //
2000// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
2001// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
2002// // process exits).
2003// //
2004//// Py_Finalize ();
2005//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00002006
2007#endif // #ifdef LLDB_DISABLE_PYTHON