blob: ee3f14c8e62e9c8da11fcfda81f8750c465bfab1 [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:
Greg Claytona1cec242012-01-06 00:47:38 +0000597 // When another input reader is pushed, don't leave the session...
598 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000599 break;
600
601 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000602 {
Greg Claytona1cec242012-01-06 00:47:38 +0000603 // Don't try and acquire the interpreter lock here because code like
604 // this:
605 //
606 // (lldb) script
607 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
608 //
609 // This will cause the process to run. The interpreter lock is taken
610 // by the input reader for the "script" command. If we try and acquire
611 // the lock here, when the process runs it might deactivate this input
612 // reader (if STDIN is hooked up to the inferior process) and
613 // reactivate it when the process stops which will deadlock.
614 //ScriptInterpreterPython::Locker locker(script_interpreter,
615 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
616 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000617 }
Chris Lattner24943d22010-06-08 16:52:24 +0000618 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000619
Caroline Tice4a348082011-05-02 20:41:46 +0000620 case eInputReaderAsynchronousOutputWritten:
621 break;
622
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000623 case eInputReaderInterrupt:
624 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
625 break;
626
627 case eInputReaderEndOfFile:
628 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
629 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000630
631 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000632 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000633 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000634 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000635 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000636 bytes_len);
637 if (bytes && bytes_len)
638 {
639 if ((int) bytes[0] == 4)
640 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
641 else
642 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
643 }
644 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000645 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000646 else
647 {
648 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000649 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000650 bytes,
651 bytes_len);
652 reader.SetIsDone (true);
653 }
654
Chris Lattner24943d22010-06-08 16:52:24 +0000655 break;
656
657 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000658 script_interpreter->LeaveSession ();
659
Chris Lattner24943d22010-06-08 16:52:24 +0000660 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000661 if (log)
662 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000663
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000664 script_interpreter->RestoreTerminalState ();
665
Caroline Tice2ade6112010-11-10 19:18:14 +0000666 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000667 break;
668 }
669
670 return bytes_len;
671}
672
673
674void
Greg Clayton238c0a12010-09-18 01:14:36 +0000675ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000676{
677 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
678
Caroline Tice0aa2e552011-01-14 00:29:16 +0000679 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000680
681 // At the moment, the only time the debugger does not have an input file handle is when this is called
682 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
683 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
684 // do it.
685
Greg Clayton58928562011-02-09 01:08:52 +0000686 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000687 return;
688
Greg Clayton63094e02010-06-23 01:19:29 +0000689 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000690 if (reader_sp)
691 {
692 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
693 this, // baton
694 eInputReaderGranularityLine, // token size, to pass to callback function
695 NULL, // end token
696 NULL, // prompt
697 true)); // echo input
698
699 if (error.Success())
700 {
Greg Clayton63094e02010-06-23 01:19:29 +0000701 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000702 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000703 }
704 }
705}
706
707bool
708ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000709 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000710 void *ret_value)
711{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000712
Enrico Granatafa1f6172011-10-24 17:22:21 +0000713 Locker locker(this,
714 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
715 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000716
Chris Lattner24943d22010-06-08 16:52:24 +0000717 PyObject *py_return = NULL;
718 PyObject *mainmod = PyImport_AddModule ("__main__");
719 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000720 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000721 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000722 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000723 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000724 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000725
726 if (PyDict_Check (globals))
727 {
728 PyObject *key, *value;
729 Py_ssize_t pos = 0;
730
731 int i = 0;
732 while (PyDict_Next (globals, &pos, &key, &value))
733 {
734 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
735 // so that Python's garbage collector doesn't collect them out from under us.
736 Py_INCREF (key);
737 Py_INCREF (value);
738 char *c_str = PyString_AsString (key);
739 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
740 locals = value;
741 ++i;
742 }
743 }
Chris Lattner24943d22010-06-08 16:52:24 +0000744
Caroline Tice0aa2e552011-01-14 00:29:16 +0000745 if (locals == NULL)
746 {
747 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
748 should_decrement_locals = true;
749 }
750
751 if (locals == NULL)
752 {
753 locals = globals;
754 should_decrement_locals = false;
755 }
756
757 py_error = PyErr_Occurred();
758 if (py_error != NULL)
759 PyErr_Clear();
760
Chris Lattner24943d22010-06-08 16:52:24 +0000761 if (in_string != NULL)
762 {
763 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
764 if (py_return == NULL)
765 {
766 py_error = PyErr_Occurred ();
767 if (py_error != NULL)
768 PyErr_Clear ();
769
770 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
771 }
772
Caroline Tice0aa2e552011-01-14 00:29:16 +0000773 if (locals != NULL
774 && should_decrement_locals)
775 Py_DECREF (locals);
776
Chris Lattner24943d22010-06-08 16:52:24 +0000777 if (py_return != NULL)
778 {
779 switch (return_type)
780 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000781 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000782 {
783 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000784 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000785 break;
786 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000787 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000788 {
789 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000790 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000791 break;
792 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000793 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000794 {
795 const char format[2] = "b";
796 success = PyArg_Parse (py_return, format, (bool *) ret_value);
797 break;
798 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000799 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000800 {
801 const char format[2] = "h";
802 success = PyArg_Parse (py_return, format, (short *) ret_value);
803 break;
804 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000805 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000806 {
807 const char format[2] = "H";
808 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
809 break;
810 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000811 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000812 {
813 const char format[2] = "i";
814 success = PyArg_Parse (py_return, format, (int *) ret_value);
815 break;
816 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000817 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000818 {
819 const char format[2] = "I";
820 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
821 break;
822 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000823 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000824 {
825 const char format[2] = "l";
826 success = PyArg_Parse (py_return, format, (long *) ret_value);
827 break;
828 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000829 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000830 {
831 const char format[2] = "k";
832 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
833 break;
834 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000835 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000836 {
837 const char format[2] = "L";
838 success = PyArg_Parse (py_return, format, (long long *) ret_value);
839 break;
840 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000841 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000842 {
843 const char format[2] = "K";
844 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
845 break;
846 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000847 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000848 {
849 const char format[2] = "f";
850 success = PyArg_Parse (py_return, format, (float *) ret_value);
851 break;
852 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000853 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000854 {
855 const char format[2] = "d";
856 success = PyArg_Parse (py_return, format, (double *) ret_value);
857 break;
858 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000859 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000860 {
861 const char format[2] = "c";
862 success = PyArg_Parse (py_return, format, (char *) ret_value);
863 break;
864 }
865 default:
866 {}
867 }
868 Py_DECREF (py_return);
869 if (success)
870 ret_success = true;
871 else
872 ret_success = false;
873 }
874 }
875
876 py_error = PyErr_Occurred();
877 if (py_error != NULL)
878 {
879 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
880 PyErr_Print ();
881 PyErr_Clear();
882 ret_success = false;
883 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000884
Chris Lattner24943d22010-06-08 16:52:24 +0000885 return ret_success;
886}
887
888bool
889ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
890{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000891
892
893 Locker locker(this,
894 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
895 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000896
Chris Lattner24943d22010-06-08 16:52:24 +0000897 bool success = false;
898 PyObject *py_return = NULL;
899 PyObject *mainmod = PyImport_AddModule ("__main__");
900 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000901 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000902 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000903 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000904
Caroline Tice0aa2e552011-01-14 00:29:16 +0000905 if (PyDict_Check (globals))
906 {
907 PyObject *key, *value;
908 Py_ssize_t pos = 0;
909
910 while (PyDict_Next (globals, &pos, &key, &value))
911 {
912 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
913 // so that Python's garbage collector doesn't collect them out from under us.
914 Py_INCREF (key);
915 Py_INCREF (value);
916 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
917 locals = value;
918 }
919 }
920
921 if (locals == NULL)
922 {
923 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
924 should_decrement_locals = true;
925 }
926
927 if (locals == NULL)
928 {
929 locals = globals;
930 should_decrement_locals = false;
931 }
932
933 py_error = PyErr_Occurred();
934 if (py_error != NULL)
935 PyErr_Clear();
936
Chris Lattner24943d22010-06-08 16:52:24 +0000937 if (in_string != NULL)
938 {
939 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
940 if (compiled_node)
941 {
942 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
943 if (compiled_code)
944 {
945 py_return = PyEval_EvalCode (compiled_code, globals, locals);
946 if (py_return != NULL)
947 {
948 success = true;
949 Py_DECREF (py_return);
950 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000951 if (locals && should_decrement_locals)
952 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000953 }
954 }
955 }
956
957 py_error = PyErr_Occurred ();
958 if (py_error != NULL)
959 {
960 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
961 PyErr_Print ();
962 PyErr_Clear();
963 success = false;
964 }
965
966 return success;
967}
968
969static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
970
971size_t
972ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
973(
974 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000975 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000976 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000977 const char *bytes,
978 size_t bytes_len
979)
980{
Caroline Tice892fadd2011-06-16 16:27:19 +0000981 static StringList commands_in_progress;
982
983 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
984 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
985
Chris Lattner24943d22010-06-08 16:52:24 +0000986 switch (notification)
987 {
988 case eInputReaderActivate:
989 {
990 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +0000991 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +0000992 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000993 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000994 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +0000995 out_stream->Printf ("%s", reader.GetPrompt());
996 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +0000997 }
998 }
999 break;
1000
1001 case eInputReaderDeactivate:
1002 break;
1003
1004 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001005 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001006 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001007 out_stream->Printf ("%s", reader.GetPrompt());
1008 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001009 }
Chris Lattner24943d22010-06-08 16:52:24 +00001010 break;
1011
Caroline Tice4a348082011-05-02 20:41:46 +00001012 case eInputReaderAsynchronousOutputWritten:
1013 break;
1014
Chris Lattner24943d22010-06-08 16:52:24 +00001015 case eInputReaderGotToken:
1016 {
1017 std::string temp_string (bytes, bytes_len);
1018 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001019 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001020 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001021 out_stream->Printf ("%s", reader.GetPrompt());
1022 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001023 }
Chris Lattner24943d22010-06-08 16:52:24 +00001024 }
1025 break;
1026
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001027 case eInputReaderEndOfFile:
1028 case eInputReaderInterrupt:
1029 // Control-c (SIGINT) & control-d both mean finish & exit.
1030 reader.SetIsDone(true);
1031
1032 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1033 if (notification == eInputReaderInterrupt)
1034 commands_in_progress.Clear();
1035
1036 // Fall through here...
1037
Chris Lattner24943d22010-06-08 16:52:24 +00001038 case eInputReaderDone:
1039 {
1040 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1041 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1042 data_ap->user_source.AppendList (commands_in_progress);
1043 if (data_ap.get())
1044 {
Greg Clayton63094e02010-06-23 01:19:29 +00001045 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001046 if (interpreter)
1047 {
1048 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1049 data_ap->script_source))
1050 {
1051 if (data_ap->script_source.GetSize() == 1)
1052 {
1053 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1054 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1055 }
1056 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001057 else if (!batch_mode)
1058 {
1059 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1060 out_stream->Flush();
1061 }
Chris Lattner24943d22010-06-08 16:52:24 +00001062 }
1063 else
1064 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001065 if (!batch_mode)
1066 {
1067 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1068 out_stream->Flush();
1069 }
Chris Lattner24943d22010-06-08 16:52:24 +00001070 }
1071 }
1072 }
1073 break;
1074
1075 }
1076
1077 return bytes_len;
1078}
1079
1080void
Greg Clayton238c0a12010-09-18 01:14:36 +00001081ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001082 CommandReturnObject &result)
1083{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001084 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1085
Greg Clayton63094e02010-06-23 01:19:29 +00001086 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001087
1088 if (reader_sp)
1089 {
1090 Error err = reader_sp->Initialize (
1091 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1092 bp_options, // baton
1093 eInputReaderGranularityLine, // token size, for feeding data to callback function
1094 "DONE", // end token
1095 "> ", // prompt
1096 true); // echo input
1097
1098 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001099 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001100 else
1101 {
1102 result.AppendError (err.AsCString());
1103 result.SetStatus (eReturnStatusFailed);
1104 }
1105 }
1106 else
1107 {
1108 result.AppendError("out of memory");
1109 result.SetStatus (eReturnStatusFailed);
1110 }
1111}
1112
Johnny Chen3e0571b2010-09-11 00:23:59 +00001113// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001114void
Greg Clayton238c0a12010-09-18 01:14:36 +00001115ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001116 const char *oneliner)
1117{
1118 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1119
1120 // It's necessary to set both user_source and script_source to the oneliner.
1121 // The former is used to generate callback description (as in breakpoint command list)
1122 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001123
Johnny Chend1c2dca2010-09-10 18:21:10 +00001124 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001125
Caroline Tice5136f942010-09-27 21:35:15 +00001126 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1127 {
1128 if (data_ap->script_source.GetSize() == 1)
1129 {
1130 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1131 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1132 }
1133 }
1134
Johnny Chend1c2dca2010-09-10 18:21:10 +00001135 return;
1136}
1137
Chris Lattner24943d22010-06-08 16:52:24 +00001138bool
1139ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1140{
1141 // Convert StringList to one long, newline delimited, const char *.
1142 std::string function_def_string;
1143
1144 int num_lines = function_def.GetSize();
1145
1146 for (int i = 0; i < num_lines; ++i)
1147 {
1148 function_def_string.append (function_def.GetStringAtIndex(i));
1149 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1150 function_def_string.append ("\n");
1151
1152 }
1153
1154 return ExecuteMultipleLines (function_def_string.c_str());
1155}
1156
Enrico Granataf7a9b142011-07-15 02:26:42 +00001157// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1158// use this code to generate their functions
1159bool
1160ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1161{
1162 int num_lines = input.GetSize ();
1163 if (num_lines == 0)
1164 return false;
1165 StreamString sstr;
1166 StringList auto_generated_function;
1167 auto_generated_function.AppendString (signature.c_str());
1168 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1169 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1170 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1171 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1172 // global dictionary.
1173
1174 // Wrap everything up inside the function, increasing the indentation.
1175
1176 for (int i = 0; i < num_lines; ++i)
1177 {
1178 sstr.Clear ();
1179 sstr.Printf (" %s", input.GetStringAtIndex (i));
1180 auto_generated_function.AppendString (sstr.GetData());
1181 }
1182 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1183 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1184 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1185 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1186
1187 // Verify that the results are valid Python.
1188
1189 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1190 return false;
1191
1192 return true;
1193
1194}
1195
1196// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1197// given to generated functions, of course)
1198bool
1199ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output)
1200{
1201 static int num_created_functions = 0;
1202 user_input.RemoveBlankLines ();
1203 int num_lines = user_input.GetSize ();
1204 StreamString sstr;
1205
1206 // Check to see if we have any data; if not, just return.
1207 if (user_input.GetSize() == 0)
1208 return false;
1209
1210 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1211 // ValueObject as parameter to the function.
1212
1213 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1214 ++num_created_functions;
1215 std::string auto_generated_function_name = sstr.GetData();
1216
1217 sstr.Clear();
1218 StringList auto_generated_function;
1219
1220 // Create the function name & definition string.
1221
1222 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1223 auto_generated_function.AppendString (sstr.GetData());
1224
1225 // Pre-pend code for setting up the session dictionary.
1226
1227 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1228 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1229 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1230 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1231 // global dictionary.
1232
1233 // Wrap everything up inside the function, increasing the indentation.
1234
1235 for (int i = 0; i < num_lines; ++i)
1236 {
1237 sstr.Clear ();
1238 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1239 auto_generated_function.AppendString (sstr.GetData());
1240 }
1241
1242 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1243 // got written to the values in the global dictionary, not the session dictionary).
1244
1245 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1246 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1247 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1248 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1249
1250 // Verify that the results are valid Python.
1251
1252 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1253 return false;
1254
1255 // Store the name of the auto-generated function to be called.
1256
1257 output.AppendString (auto_generated_function_name.c_str());
1258 return true;
1259}
1260
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001261bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001262ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, StringList &output)
1263{
1264 static int num_created_functions = 0;
1265 user_input.RemoveBlankLines ();
1266 int num_lines = user_input.GetSize ();
1267 StreamString sstr;
1268
1269 // Check to see if we have any data; if not, just return.
1270 if (user_input.GetSize() == 0)
1271 return false;
1272
1273 // 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 +00001274 // required data as parameters to the function.
Enrico Granatac2a28252011-08-16 16:49:25 +00001275
1276 sstr.Printf ("lldb_autogen_python_cmd_alias_func_%d", num_created_functions);
1277 ++num_created_functions;
1278 std::string auto_generated_function_name = sstr.GetData();
1279
1280 sstr.Clear();
1281 StringList auto_generated_function;
1282
1283 // Create the function name & definition string.
1284
Enrico Granata271568f2011-09-09 01:41:30 +00001285 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001286 auto_generated_function.AppendString (sstr.GetData());
1287
1288 // Pre-pend code for setting up the session dictionary.
1289
1290 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1291 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1292 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1293 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1294 // global dictionary.
1295
1296 // Wrap everything up inside the function, increasing the indentation.
1297
1298 for (int i = 0; i < num_lines; ++i)
1299 {
1300 sstr.Clear ();
1301 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1302 auto_generated_function.AppendString (sstr.GetData());
1303 }
1304
1305 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1306 // got written to the values in the global dictionary, not the session dictionary).
1307
1308 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1309 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1310 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1311 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1312
1313 // Verify that the results are valid Python.
1314
1315 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1316 return false;
1317
1318 // Store the name of the auto-generated function to be called.
1319
1320 output.AppendString (auto_generated_function_name.c_str());
1321 return true;
1322}
1323
1324
1325bool
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001326ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output)
1327{
1328 static int num_created_classes = 0;
1329 user_input.RemoveBlankLines ();
1330 int num_lines = user_input.GetSize ();
1331 StreamString sstr;
1332
1333 // Check to see if we have any data; if not, just return.
1334 if (user_input.GetSize() == 0)
1335 return false;
1336
1337 // Wrap all user input into a Python class
1338
1339 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1340 ++num_created_classes;
1341 std::string auto_generated_class_name = sstr.GetData();
1342
1343 sstr.Clear();
1344 StringList auto_generated_class;
1345
1346 // Create the function name & definition string.
1347
1348 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1349 auto_generated_class.AppendString (sstr.GetData());
1350
1351 // Wrap everything up inside the class, increasing the indentation.
1352
1353 for (int i = 0; i < num_lines; ++i)
1354 {
1355 sstr.Clear ();
1356 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1357 auto_generated_class.AppendString (sstr.GetData());
1358 }
1359
1360
1361 // Verify that the results are valid Python.
1362 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1363 // (TODO: rename that method to ExportDefinitionToInterpreter)
1364 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1365 return false;
1366
1367 // Store the name of the auto-generated class
1368
1369 output.AppendString (auto_generated_class_name.c_str());
1370 return true;
1371}
1372
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001373void*
1374ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1375 lldb::ValueObjectSP valobj)
1376{
1377 if (class_name.empty())
1378 return NULL;
1379
1380 if (!valobj.get())
1381 return NULL;
1382
Enrico Granata979e20d2011-07-29 19:53:35 +00001383 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001384
1385 if (!target)
1386 return NULL;
1387
1388 Debugger &debugger = target->GetDebugger();
1389 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1390 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1391
1392 if (!script_interpreter)
1393 return NULL;
1394
1395 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001396
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001397 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001398 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001399 ret_val = g_swig_synthetic_script (class_name,
1400 python_interpreter->m_dictionary_name.c_str(),
1401 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001402 }
1403
1404 return ret_val;
1405}
1406
Enrico Granataf7a9b142011-07-15 02:26:42 +00001407bool
1408ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output)
1409{
1410 StringList input(oneliner);
1411 return GenerateTypeScriptFunction(input, output);
1412}
1413
Chris Lattner24943d22010-06-08 16:52:24 +00001414bool
1415ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1416{
1417 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001418 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001419 int num_lines = user_input.GetSize ();
1420 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001421
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001422 // Check to see if we have any data; if not, just return.
1423 if (user_input.GetSize() == 0)
1424 return false;
1425
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001426 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1427 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001428
Caroline Ticeb447e842010-09-21 19:25:28 +00001429
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001430 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1431 ++num_created_functions;
1432 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001433
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001434 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001435 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001436
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001437 // Create the function name & definition string.
1438
Caroline Tice0aa2e552011-01-14 00:29:16 +00001439 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001440 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001441
1442 // Pre-pend code for setting up the session dictionary.
1443
1444 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1445 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1446 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1447 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1448 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001449
1450 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001451
1452 for (int i = 0; i < num_lines; ++i)
1453 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001454 sstr.Clear ();
1455 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1456 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001457 }
Chris Lattner24943d22010-06-08 16:52:24 +00001458
Caroline Tice0aa2e552011-01-14 00:29:16 +00001459 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1460 // got written to the values in the global dictionary, not the session dictionary).
1461
1462 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1463 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1464 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1465 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1466
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001467 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001468
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001469 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001470 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001471 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001472 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001473
1474 // Store the name of the auto-generated function to be called.
1475
1476 callback_data.AppendString (auto_generated_function_name.c_str());
1477 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001478}
1479
Enrico Granataf7a9b142011-07-15 02:26:42 +00001480std::string
1481ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1482 lldb::ValueObjectSP valobj)
1483{
1484
1485 if (!python_function_name || !(*python_function_name))
1486 return "<no function>";
1487
1488 if (!valobj.get())
1489 return "<no object>";
1490
Enrico Granata979e20d2011-07-29 19:53:35 +00001491 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001492
1493 if (!target)
1494 return "<no target>";
1495
1496 Debugger &debugger = target->GetDebugger();
1497 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1498 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1499
1500 if (!script_interpreter)
1501 return "<no python>";
1502
1503 std::string ret_val;
1504
1505 if (python_function_name
1506 && *python_function_name)
1507 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001508 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001509 Locker py_lock(python_interpreter);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001510 ret_val = g_swig_typescript_callback (python_function_name,
1511 python_interpreter->m_dictionary_name.c_str(),
1512 valobj);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001513 }
1514 }
1515 else
1516 return "<no function name>";
1517
1518 return ret_val;
1519
1520}
1521
Greg Clayton5144f382010-10-07 17:14:24 +00001522bool
1523ScriptInterpreterPython::BreakpointCallbackFunction
1524(
1525 void *baton,
1526 StoppointCallbackContext *context,
1527 user_id_t break_id,
1528 user_id_t break_loc_id
1529)
1530{
1531 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1532 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001533
1534 if (!context)
1535 return true;
1536
Greg Clayton567e7f32011-09-22 04:58:26 +00001537 Target *target = context->exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001538
1539 if (!target)
1540 return true;
1541
1542 Debugger &debugger = target->GetDebugger();
1543 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1544 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1545
1546 if (!script_interpreter)
1547 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001548
1549 if (python_function_name != NULL
1550 && python_function_name[0] != '\0')
1551 {
Greg Clayton567e7f32011-09-22 04:58:26 +00001552 const StackFrameSP stop_frame_sp (context->exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001553 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001554 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001555 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001556 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1557
1558 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001559 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001560 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001561 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001562 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001563 ret_val = g_swig_breakpoint_callback (python_function_name,
1564 python_interpreter->m_dictionary_name.c_str(),
1565 stop_frame_sp,
1566 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001567 }
1568 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001569 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001570 }
Greg Clayton5144f382010-10-07 17:14:24 +00001571 }
1572 // We currently always true so we stop in case anything goes wrong when
1573 // trying to call the script function
1574 return true;
1575}
Caroline Tice2ade6112010-11-10 19:18:14 +00001576
1577lldb::thread_result_t
1578ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1579{
1580 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1581
1582 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1583
1584 if (log)
1585 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1586
1587 char error_str[1024];
1588 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001589
Enrico Granatafa1f6172011-10-24 17:22:21 +00001590 Locker locker(script_interpreter,
1591 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1592 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1593
1594 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001595 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001596 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001597
Caroline Tice0aa2e552011-01-14 00:29:16 +00001598 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1599 PyRun_SimpleString (run_string.GetData());
1600 run_string.Clear ();
1601
1602 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1603 PyRun_SimpleString (run_string.GetData());
1604 run_string.Clear ();
1605
1606 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1607 PyRun_SimpleString (run_string.GetData());
1608 run_string.Clear ();
1609
1610 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1611 pty_slave_name);
1612 PyRun_SimpleString (run_string.GetData());
1613 run_string.Clear ();
1614
Johnny Chen8054ba32011-03-11 00:28:50 +00001615 // The following call drops into the embedded interpreter loop and stays there until the
1616 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001617
Caroline Ticece207c12011-03-11 00:21:55 +00001618 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001619 // 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 +00001620 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1621
1622 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1623 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1624 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1625 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1626 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1627 // hang (it's happened before).
1628
Caroline Tice9d352ce2011-03-07 23:24:28 +00001629 Py_BEGIN_ALLOW_THREADS
1630 PyGILState_STATE gstate = PyGILState_Ensure();
1631
Caroline Tice0aa2e552011-01-14 00:29:16 +00001632 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1633 PyRun_SimpleString (run_string.GetData());
1634 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001635
Caroline Tice9d352ce2011-03-07 23:24:28 +00001636 PyGILState_Release (gstate);
1637 Py_END_ALLOW_THREADS
1638
Caroline Tice0aa2e552011-01-14 00:29:16 +00001639 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1640 PyRun_SimpleString (run_string.GetData());
1641 run_string.Clear();
1642
1643 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1644 PyRun_SimpleString (run_string.GetData());
1645 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001646
Caroline Tice2ade6112010-11-10 19:18:14 +00001647 }
1648
1649 if (script_interpreter->m_embedded_thread_input_reader_sp)
1650 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1651
1652 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001653
1654 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001655
1656 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1657 if (log)
1658 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1659
1660
Johnny Chen8054ba32011-03-11 00:28:50 +00001661 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001662 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001663 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1664 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1665 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001666
Caroline Tice2ade6112010-11-10 19:18:14 +00001667 return NULL;
1668}
1669
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001670uint32_t
1671ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1672{
1673 if (!implementor)
1674 return 0;
1675
1676 if (!g_swig_calc_children)
1677 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001678
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001679 uint32_t ret_val = 0;
1680
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001681 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001682 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001683 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001684 }
1685
1686 return ret_val;
1687}
1688
Enrico Granata91544802011-09-06 19:20:51 +00001689lldb::ValueObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001690ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1691{
1692 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001693 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001694
Enrico Granata91544802011-09-06 19:20:51 +00001695 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1696 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001697
Enrico Granata91544802011-09-06 19:20:51 +00001698 void* child_ptr = NULL;
1699 lldb::SBValue* value_sb = NULL;
1700 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001701
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001702 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001703 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +00001704 child_ptr = g_swig_get_child_index (implementor,idx);
1705 if (child_ptr != NULL && child_ptr != Py_None)
1706 {
1707 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1708 if (value_sb == NULL)
1709 Py_XDECREF(child_ptr);
1710 else
1711 ret_val = value_sb->get_sp();
1712 }
1713 else
1714 {
1715 Py_XDECREF(child_ptr);
1716 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001717 }
1718
1719 return ret_val;
1720}
1721
1722int
1723ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1724{
1725 if (!implementor)
1726 return UINT32_MAX;
1727
1728 if (!g_swig_get_index_child)
1729 return UINT32_MAX;
1730
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001731 int ret_val = UINT32_MAX;
1732
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001733 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001734 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001735 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001736 }
1737
1738 return ret_val;
1739}
1740
Enrico Granata979e20d2011-07-29 19:53:35 +00001741void
1742ScriptInterpreterPython::UpdateSynthProviderInstance (void* implementor)
1743{
1744 if (!implementor)
1745 return;
1746
1747 if (!g_swig_update_provider)
1748 return;
1749
Enrico Granata979e20d2011-07-29 19:53:35 +00001750 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001751 Locker py_lock(this);
Enrico Granata979e20d2011-07-29 19:53:35 +00001752 g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001753 }
1754
1755 return;
1756}
1757
Enrico Granatac2a28252011-08-16 16:49:25 +00001758bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001759ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00001760 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00001761 lldb_private::Error& error)
1762{
1763 if (!pathname || !pathname[0])
1764 {
1765 error.SetErrorString("invalid pathname");
1766 return false;
1767 }
1768
1769 if (!g_swig_call_module_init)
1770 {
1771 error.SetErrorString("internal helper function missing");
1772 return false;
1773 }
1774
Enrico Granata59df36f2011-10-17 21:45:27 +00001775 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
Enrico Granatafa1f6172011-10-24 17:22:21 +00001776
Enrico Granata59df36f2011-10-17 21:45:27 +00001777 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001778 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00001779
1780 FileSpec target_file(pathname, true);
1781
1782 // TODO: would we want to reject any other value?
1783 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1784 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1785 {
1786 error.SetErrorString("invalid pathname");
1787 return false;
1788 }
1789
1790 const char* directory = target_file.GetDirectory().GetCString();
1791 std::string basename(target_file.GetFilename().GetCString());
1792
1793 // now make sure that Python has "directory" in the search path
1794 StreamString command_stream;
1795 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1796 directory,
1797 directory);
Enrico Granatafa1f6172011-10-24 17:22:21 +00001798 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData());
Enrico Granata59df36f2011-10-17 21:45:27 +00001799 if (!syspath_retval)
1800 {
1801 error.SetErrorString("Python sys.path handling failed");
1802 return false;
1803 }
1804
1805 // strip .py or .pyc extension
1806 ConstString extension = target_file.GetFileNameExtension();
1807 if (::strcmp(extension.GetCString(), "py") == 0)
1808 basename.resize(basename.length()-3);
1809 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1810 basename.resize(basename.length()-4);
1811
1812 // check if the module is already import-ed
1813 command_stream.Clear();
1814 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1815 int refcount = 0;
1816 // this call will fail if the module does not exist (because the parameter to it is not a string
1817 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00001818 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
1819 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0);
1820 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00001821 {
1822 error.SetErrorString("module already imported");
1823 return false;
1824 }
1825
1826 // now actually do the import
1827 command_stream.Clear();
1828 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafa1f6172011-10-24 17:22:21 +00001829 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL);
Enrico Granata59df36f2011-10-17 21:45:27 +00001830 if (!import_retval)
1831 {
1832 error.SetErrorString("Python import statement failed");
1833 return false;
1834 }
1835
1836 // call __lldb_module_init(debugger,dict)
1837 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001838 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001839 debugger_sp))
1840 {
1841 error.SetErrorString("calling __lldb_module_init failed");
1842 return false;
1843 }
1844 return true;
1845 }
1846}
1847
Enrico Granata6010ace2011-11-07 22:57:04 +00001848ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
1849 ScriptedCommandSynchronicity synchro) :
1850 m_debugger_sp(debugger_sp),
1851 m_synch_wanted(synchro),
1852 m_old_asynch(debugger_sp->GetAsyncExecution())
1853{
1854 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
1855 m_debugger_sp->SetAsyncExecution(false);
1856 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
1857 m_debugger_sp->SetAsyncExecution(true);
1858}
1859
1860ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
1861{
1862 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
1863 m_debugger_sp->SetAsyncExecution(m_old_asynch);
1864}
1865
Enrico Granata59df36f2011-10-17 21:45:27 +00001866bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001867ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1868 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00001869 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001870 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001871 Error& error)
1872{
1873 if (!impl_function)
1874 {
1875 error.SetErrorString("no function to execute");
1876 return false;
1877 }
1878
1879 if (!g_swig_call_command)
1880 {
1881 error.SetErrorString("no helper function to run scripted commands");
1882 return false;
1883 }
1884
Enrico Granatac2a28252011-08-16 16:49:25 +00001885 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
Enrico Granata6010ace2011-11-07 22:57:04 +00001886
1887 if (!debugger_sp.get())
1888 {
1889 error.SetErrorString("invalid Debugger pointer");
1890 return false;
1891 }
Enrico Granatac2a28252011-08-16 16:49:25 +00001892
1893 bool ret_val;
1894
1895 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00001896
Enrico Granatac2a28252011-08-16 16:49:25 +00001897 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001898 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00001899 SynchronicityHandler synch_handler(debugger_sp,
1900 synchronicity);
1901
Enrico Granatac2a28252011-08-16 16:49:25 +00001902 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001903 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00001904 debugger_sp,
1905 args,
1906 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001907 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001908 }
Enrico Granata6010ace2011-11-07 22:57:04 +00001909
Enrico Granatac2a28252011-08-16 16:49:25 +00001910 if (!ret_val)
1911 error.SetErrorString(err_msg.c_str());
1912 else
1913 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00001914
Enrico Granatac2a28252011-08-16 16:49:25 +00001915 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00001916}
1917
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001918// in Python, a special attribute __doc__ contains the docstring
1919// for an object (function, method, class, ...) if any is defined
1920// Otherwise, the attribute's value is None
1921std::string
1922ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1923{
1924 std::string command(item);
1925 command += ".__doc__";
1926
1927 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1928
1929 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001930 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001931 &result_ptr) && result_ptr)
1932 {
1933 return std::string(result_ptr);
1934 }
1935 else
1936 return std::string("");
1937}
Caroline Tice2ade6112010-11-10 19:18:14 +00001938
Caroline Tice0aa2e552011-01-14 00:29:16 +00001939void
Greg Claytone86cbb92011-03-22 01:14:58 +00001940ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00001941 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001942 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
1943 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
1944 SWIGPythonCalculateNumChildren python_swig_calc_children,
1945 SWIGPythonGetChildAtIndex python_swig_get_child_index,
1946 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
Enrico Granata979e20d2011-07-29 19:53:35 +00001947 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue,
Enrico Granatac2a28252011-08-16 16:49:25 +00001948 SWIGPythonUpdateSynthProviderInstance python_swig_update_provider,
Enrico Granata59df36f2011-10-17 21:45:27 +00001949 SWIGPythonCallCommand python_swig_call_command,
1950 SWIGPythonCallModuleInit python_swig_call_mod_init)
Greg Claytone86cbb92011-03-22 01:14:58 +00001951{
1952 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001953 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1954 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001955 g_swig_synthetic_script = python_swig_synthetic_script;
1956 g_swig_calc_children = python_swig_calc_children;
1957 g_swig_get_child_index = python_swig_get_child_index;
1958 g_swig_get_index_child = python_swig_get_index_child;
1959 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Enrico Granata979e20d2011-07-29 19:53:35 +00001960 g_swig_update_provider = python_swig_update_provider;
Enrico Granatac2a28252011-08-16 16:49:25 +00001961 g_swig_call_command = python_swig_call_command;
Enrico Granata59df36f2011-10-17 21:45:27 +00001962 g_swig_call_module_init = python_swig_call_mod_init;
Greg Claytone86cbb92011-03-22 01:14:58 +00001963}
1964
1965void
1966ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001967{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001968 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1969
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001970 // Python will muck with STDIN terminal state, so save off any current TTY
1971 // settings so we can restore them.
1972 TerminalState stdin_tty_state;
1973 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001974
Caroline Tice9d352ce2011-03-07 23:24:28 +00001975 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001976 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001977
Greg Claytone86cbb92011-03-22 01:14:58 +00001978 // Initialize SWIG after setting up python
1979 assert (g_swig_init_callback != NULL);
1980 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001981
1982 // Update the path python uses to search for modules to include the current directory.
1983
Caroline Ticed4d92832011-06-13 21:33:00 +00001984 PyRun_SimpleString ("import sys");
1985 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001986
1987 // Find the module that owns this code and use that path we get to
1988 // set the sys.path appropriately.
1989
1990 FileSpec file_spec;
1991 char python_dir_path[PATH_MAX];
1992 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1993 {
1994 std::string python_path("sys.path.insert(0,\"");
1995 size_t orig_len = python_path.length();
1996 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1997 {
1998 python_path.append (python_dir_path);
1999 python_path.append ("\")");
2000 PyRun_SimpleString (python_path.c_str());
2001 python_path.resize (orig_len);
2002 }
2003
2004 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
2005 {
2006 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2007 {
2008 python_path.append (python_dir_path);
2009 python_path.append ("\")");
2010 PyRun_SimpleString (python_path.c_str());
2011 python_path.resize (orig_len);
2012 }
2013 }
2014 }
2015
Jim Ingham4dfa5112011-08-22 19:10:09 +00002016 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00002017
Caroline Ticed4d92832011-06-13 21:33:00 +00002018 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00002019
Caroline Ticed4d92832011-06-13 21:33:00 +00002020 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
2021 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00002022 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00002023
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002024 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002025}
2026
Greg Claytone86cbb92011-03-22 01:14:58 +00002027//void
2028//ScriptInterpreterPython::Terminate ()
2029//{
2030// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
2031// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
2032// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
2033// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
2034// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
2035// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
2036// // within Py_Finalize, which results in a seg fault.
2037// //
2038// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
2039// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
2040// // process exits).
2041// //
2042//// Py_Finalize ();
2043//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00002044
2045#endif // #ifdef LLDB_DISABLE_PYTHON