blob: ee356900e85b0fc2c0df016ef3bcc04c19f15559 [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.
12
13#if defined (__APPLE__)
14#include <Python/Python.h>
15#else
16#include <Python.h>
17#endif
Chris Lattner24943d22010-06-08 16:52:24 +000018
19#include "lldb/Interpreter/ScriptInterpreterPython.h"
20
Chris Lattner24943d22010-06-08 16:52:24 +000021#include <stdlib.h>
22#include <stdio.h>
23
24#include <string>
25
Enrico Granata91544802011-09-06 19:20:51 +000026#include "lldb/API/SBValue.h"
Greg Clayton987c7eb2011-09-17 08:33:22 +000027#include "lldb/Breakpoint/BreakpointLocation.h"
Greg Clayton63094e02010-06-23 01:19:29 +000028#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner24943d22010-06-08 16:52:24 +000029#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030#include "lldb/Core/Timer.h"
31#include "lldb/Host/Host.h"
32#include "lldb/Interpreter/CommandInterpreter.h"
33#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton5144f382010-10-07 17:14:24 +000034#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000035
Chris Lattner24943d22010-06-08 16:52:24 +000036using namespace lldb;
37using namespace lldb_private;
38
Greg Claytone86cbb92011-03-22 01:14:58 +000039
40static ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL;
41static ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL;
Enrico Granataf7a9b142011-07-15 02:26:42 +000042static ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL;
Enrico Granata9ae7cef2011-07-24 00:14:56 +000043static ScriptInterpreter::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = NULL;
44static ScriptInterpreter::SWIGPythonCalculateNumChildren g_swig_calc_children = NULL;
45static ScriptInterpreter::SWIGPythonGetChildAtIndex g_swig_get_child_index = NULL;
46static ScriptInterpreter::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = NULL;
47static ScriptInterpreter::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = NULL;
Enrico Granata979e20d2011-07-29 19:53:35 +000048static ScriptInterpreter::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = NULL;
Enrico Granatac2a28252011-08-16 16:49:25 +000049static ScriptInterpreter::SWIGPythonCallCommand g_swig_call_command = NULL;
Enrico Granata59df36f2011-10-17 21:45:27 +000050static ScriptInterpreter::SWIGPythonCallModuleInit g_swig_call_module_init = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +000051
52static int
53_check_and_flush (FILE *stream)
54{
55 int prev_fail = ferror (stream);
56 return fflush (stream) || prev_fail ? EOF : 0;
57}
58
Caroline Tice202f6b82011-01-17 21:55:19 +000059static Predicate<lldb::tid_t> &
60PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +000061{
Caroline Tice202f6b82011-01-17 21:55:19 +000062 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
63 return g_interpreter_is_running;
64}
65
Enrico Granatafa1f6172011-10-24 17:22:21 +000066bool
67ScriptInterpreterPython::Locker::CurrentThreadHasPythonLock ()
Caroline Tice202f6b82011-01-17 21:55:19 +000068{
69 TimeValue timeout;
70
71 timeout = TimeValue::Now(); // Don't wait any time.
72
73 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
74}
75
Enrico Granatafa1f6172011-10-24 17:22:21 +000076bool
77ScriptInterpreterPython::Locker::TryGetPythonLock (uint32_t seconds_to_wait)
Caroline Tice202f6b82011-01-17 21:55:19 +000078{
79
80 TimeValue timeout;
81
82 if (seconds_to_wait != UINT32_MAX)
83 {
84 timeout = TimeValue::Now();
85 timeout.OffsetWithSeconds (seconds_to_wait);
86 }
87
88 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
89 Host::GetCurrentThreadID(), &timeout, NULL);
90}
91
Enrico Granatafa1f6172011-10-24 17:22:21 +000092void
93ScriptInterpreterPython::Locker::ReleasePythonLock ()
Caroline Tice202f6b82011-01-17 21:55:19 +000094{
95 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +000096}
97
Enrico Granatafa1f6172011-10-24 17:22:21 +000098ScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *py_interpreter,
99 uint16_t on_entry,
100 uint16_t on_leave,
101 FILE* wait_msg_handle) :
102 m_need_session( (on_leave & TearDownSession) == TearDownSession ),
103 m_release_lock ( false ), // decide in constructor body
104 m_python_interpreter(py_interpreter),
105 m_tmp_fh(wait_msg_handle)
Enrico Granata91544802011-09-06 19:20:51 +0000106{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000107 if (m_python_interpreter && !m_tmp_fh)
108 m_tmp_fh = (m_python_interpreter->m_dbg_stdout ? m_python_interpreter->m_dbg_stdout : stdout);
109
110 if ( (on_entry & AcquireLock) == AcquireLock )
111 {
112 if (CurrentThreadHasPythonLock())
113 {
114 if ( (on_leave & FreeLock) == FreeLock )
115 m_release_lock = true;
116 }
117 else
118 {
119 DoAcquireLock();
120 if ( (on_leave & FreeLock) == FreeLock )
121 m_release_lock = true;
122 if ( (on_leave & FreeAcquiredLock) == FreeAcquiredLock )
123 m_release_lock = true;
124 }
125 }
126 if ( (on_entry & InitSession) == InitSession )
127 DoInitSession();
128}
129
130bool
131ScriptInterpreterPython::Locker::DoAcquireLock()
132{
Enrico Granata91544802011-09-06 19:20:51 +0000133 if (!CurrentThreadHasPythonLock())
134 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000135 while (!TryGetPythonLock (1))
136 if (m_tmp_fh)
137 fprintf (m_tmp_fh,
Enrico Granata91544802011-09-06 19:20:51 +0000138 "Python interpreter locked on another thread; waiting to acquire lock...\n");
Enrico Granata91544802011-09-06 19:20:51 +0000139 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000140 return true;
141}
142
143bool
144ScriptInterpreterPython::Locker::DoInitSession()
145{
146 if (!m_python_interpreter)
147 return false;
148 m_python_interpreter->EnterSession ();
149 return true;
150}
151
152bool
153ScriptInterpreterPython::Locker::DoFreeLock()
154{
155 ReleasePythonLock ();
156 return true;
157}
158
159bool
160ScriptInterpreterPython::Locker::DoTearDownSession()
161{
162 if (!m_python_interpreter)
163 return false;
164 m_python_interpreter->LeaveSession ();
165 return true;
Enrico Granata91544802011-09-06 19:20:51 +0000166}
167
168ScriptInterpreterPython::Locker::~Locker()
169{
170 if (m_need_session)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000171 DoTearDownSession();
Enrico Granata91544802011-09-06 19:20:51 +0000172 if (m_release_lock)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000173 DoFreeLock();
Enrico Granata91544802011-09-06 19:20:51 +0000174}
175
Greg Clayton63094e02010-06-23 01:19:29 +0000176ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000177 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000178 m_embedded_python_pty (),
179 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +0000180 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000181 m_new_sysout (NULL),
182 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000183 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000184 m_session_is_active (false),
185 m_pty_slave_is_open (false),
186 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000187{
188
Greg Clayton7c330d62011-01-27 01:01:10 +0000189 static int g_initialized = false;
190
191 if (!g_initialized)
192 {
193 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000194 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000195 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000196
197 Locker locker(this,
198 ScriptInterpreterPython::Locker::AcquireLock,
199 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Greg Clayton7c330d62011-01-27 01:01:10 +0000200
Caroline Tice0aa2e552011-01-14 00:29:16 +0000201 m_dictionary_name.append("_dict");
202 StreamString run_string;
203 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
204 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000205
Caroline Tice0aa2e552011-01-14 00:29:16 +0000206 run_string.Clear();
207 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
208 PyRun_SimpleString (run_string.GetData());
209
210 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
211 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
212 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
213 // call to Debugger::Terminate is made, the ref-count has the correct value.
214 //
215 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
216 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000217
Caroline Tice0aa2e552011-01-14 00:29:16 +0000218 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000219
Caroline Tice0aa2e552011-01-14 00:29:16 +0000220 run_string.Clear();
221 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
222 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000223
Caroline Tice0aa2e552011-01-14 00:29:16 +0000224 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000225
Caroline Tice0aa2e552011-01-14 00:29:16 +0000226 if (new_count > old_count)
227 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000228
Caroline Tice0aa2e552011-01-14 00:29:16 +0000229 run_string.Clear();
230 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
231 PyRun_SimpleString (run_string.GetData());
232
233 run_string.Clear();
Enrico Granata59df36f2011-10-17 21:45:27 +0000234 run_string.Printf ("run_one_line (%s, 'import os')", m_dictionary_name.c_str());
235 PyRun_SimpleString (run_string.GetData());
236
237 run_string.Clear();
Greg Clayton444e35b2011-10-19 18:09:39 +0000238 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000239 interpreter.GetDebugger().GetID());
240 PyRun_SimpleString (run_string.GetData());
241
Enrico Granata074e3b62011-08-17 19:07:52 +0000242 run_string.Clear();
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000243 run_string.Printf ("run_one_line (%s, 'import gnu_libstdcpp')", m_dictionary_name.c_str());
Enrico Granata074e3b62011-08-17 19:07:52 +0000244 PyRun_SimpleString (run_string.GetData());
245
Caroline Tice0aa2e552011-01-14 00:29:16 +0000246 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000247 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000248 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000249 }
Chris Lattner24943d22010-06-08 16:52:24 +0000250}
251
252ScriptInterpreterPython::~ScriptInterpreterPython ()
253{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000254 Debugger &debugger = GetCommandInterpreter().GetDebugger();
255
256 if (m_embedded_thread_input_reader_sp.get() != NULL)
257 {
258 m_embedded_thread_input_reader_sp->SetIsDone (true);
259 m_embedded_python_pty.CloseSlaveFileDescriptor();
260 m_pty_slave_is_open = false;
261 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
262 m_embedded_thread_input_reader_sp.reset();
263 debugger.PopInputReader (reader_sp);
264 }
265
266 if (m_new_sysout)
267 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000268 Locker locker(this,
269 ScriptInterpreterPython::Locker::AcquireLock,
270 ScriptInterpreterPython::Locker::FreeLock);
271 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000272 }
Chris Lattner24943d22010-06-08 16:52:24 +0000273}
274
Caroline Tice0aa2e552011-01-14 00:29:16 +0000275void
276ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
277{
278 if (fh == NULL)
279 return;
280
281 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000282
Enrico Granatafa1f6172011-10-24 17:22:21 +0000283 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +0000284
285 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000286}
287
288void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000289ScriptInterpreterPython::SaveTerminalState (int fd)
290{
291 // Python mucks with the terminal state of STDIN. If we can possibly avoid
292 // this by setting the file handles up correctly prior to entering the
293 // interpreter we should. For now we save and restore the terminal state
294 // on the input file handle.
295 m_terminal_state.Save (fd, false);
296}
297
298void
299ScriptInterpreterPython::RestoreTerminalState ()
300{
301 // Python mucks with the terminal state of STDIN. If we can possibly avoid
302 // this by setting the file handles up correctly prior to entering the
303 // interpreter we should. For now we save and restore the terminal state
304 // on the input file handle.
305 m_terminal_state.Restore();
306}
307
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000308void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000309ScriptInterpreterPython::LeaveSession ()
310{
311 m_session_is_active = false;
312}
313
314void
315ScriptInterpreterPython::EnterSession ()
316{
317 // If we have already entered the session, without having officially 'left' it, then there is no need to
318 // 'enter' it again.
319
320 if (m_session_is_active)
321 return;
322
323 m_session_is_active = true;
324
Caroline Tice202f6b82011-01-17 21:55:19 +0000325 StreamString run_string;
326
Greg Clayton444e35b2011-10-19 18:09:39 +0000327 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice202f6b82011-01-17 21:55:19 +0000328 GetCommandInterpreter().GetDebugger().GetID());
329 PyRun_SimpleString (run_string.GetData());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000330 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +0000331
Caroline Tice0aa2e552011-01-14 00:29:16 +0000332
Greg Clayton444e35b2011-10-19 18:09:39 +0000333 run_string.Printf ("run_one_line (%s, 'lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)')",
Caroline Tice6af65cb2011-05-03 21:21:50 +0000334 m_dictionary_name.c_str(),
335 GetCommandInterpreter().GetDebugger().GetID());
336 PyRun_SimpleString (run_string.GetData());
337 run_string.Clear();
338
339
Greg Clayton567e7f32011-09-22 04:58:26 +0000340 ExecutionContext exe_ctx (m_interpreter.GetDebugger().GetSelectedExecutionContext());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000341
Greg Clayton567e7f32011-09-22 04:58:26 +0000342 if (exe_ctx.GetTargetPtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000343 run_string.Printf ("run_one_line (%s, 'lldb.target = lldb.debugger.GetSelectedTarget()')",
344 m_dictionary_name.c_str());
345 else
346 run_string.Printf ("run_one_line (%s, 'lldb.target = None')", m_dictionary_name.c_str());
347 PyRun_SimpleString (run_string.GetData());
348 run_string.Clear();
349
Greg Clayton567e7f32011-09-22 04:58:26 +0000350 if (exe_ctx.GetProcessPtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000351 run_string.Printf ("run_one_line (%s, 'lldb.process = lldb.target.GetProcess()')", m_dictionary_name.c_str());
352 else
353 run_string.Printf ("run_one_line (%s, 'lldb.process = None')", m_dictionary_name.c_str());
354 PyRun_SimpleString (run_string.GetData());
355 run_string.Clear();
356
Greg Clayton567e7f32011-09-22 04:58:26 +0000357 if (exe_ctx.GetThreadPtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000358 run_string.Printf ("run_one_line (%s, 'lldb.thread = lldb.process.GetSelectedThread ()')",
359 m_dictionary_name.c_str());
360 else
361 run_string.Printf ("run_one_line (%s, 'lldb.thread = None')", m_dictionary_name.c_str());
362 PyRun_SimpleString (run_string.GetData());
363 run_string.Clear();
364
Greg Clayton567e7f32011-09-22 04:58:26 +0000365 if (exe_ctx.GetFramePtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000366 run_string.Printf ("run_one_line (%s, 'lldb.frame = lldb.thread.GetSelectedFrame ()')",
367 m_dictionary_name.c_str());
368 else
369 run_string.Printf ("run_one_line (%s, 'lldb.frame = None')", m_dictionary_name.c_str());
370 PyRun_SimpleString (run_string.GetData());
371 run_string.Clear();
372
Caroline Tice0aa2e552011-01-14 00:29:16 +0000373 PyObject *sysmod = PyImport_AddModule ("sys");
374 PyObject *sysdict = PyModule_GetDict (sysmod);
375
376 if ((m_new_sysout != NULL)
377 && (sysmod != NULL)
378 && (sysdict != NULL))
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +0000379 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000380
381 if (PyErr_Occurred())
382 PyErr_Clear ();
383
Caroline Tice0aa2e552011-01-14 00:29:16 +0000384 if (!m_pty_slave_is_open)
385 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000386 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000387 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
388 m_pty_slave_name.c_str());
389 PyRun_SimpleString (run_string.GetData());
390 m_pty_slave_is_open = true;
391
392 run_string.Clear();
393 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
394 PyRun_SimpleString (run_string.GetData());
395 }
396}
397
398
Johnny Chen60dde642010-07-30 22:33:14 +0000399bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000400ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000401{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000402 if (!m_valid_session)
403 return false;
404
Caroline Tice4a461da2011-01-14 21:09:29 +0000405 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
406 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
407 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
408 // method to pass the command string directly down to Python.
409
Enrico Granatafa1f6172011-10-24 17:22:21 +0000410 Locker locker(this,
411 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
412 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000413
414 bool success = false;
415
Greg Clayton63094e02010-06-23 01:19:29 +0000416 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000417 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000418 // Find the correct script interpreter dictionary in the main module.
419 PyObject *main_mod = PyImport_AddModule ("__main__");
420 PyObject *script_interpreter_dict = NULL;
421 if (main_mod != NULL)
422 {
423 PyObject *main_dict = PyModule_GetDict (main_mod);
424 if ((main_dict != NULL)
425 && PyDict_Check (main_dict))
426 {
427 // Go through the main dictionary looking for the correct python script interpreter dictionary
428 PyObject *key, *value;
429 Py_ssize_t pos = 0;
430
431 while (PyDict_Next (main_dict, &pos, &key, &value))
432 {
433 // We have stolen references to the key and value objects in the dictionary; we need to increment
434 // them now so that Python's garbage collector doesn't collect them out from under us.
435 Py_INCREF (key);
436 Py_INCREF (value);
437 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
438 {
439 script_interpreter_dict = value;
440 break;
441 }
442 }
443 }
444
445 if (script_interpreter_dict != NULL)
446 {
447 PyObject *pfunc = NULL;
448 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
449 if (pmod != NULL)
450 {
451 PyObject *pmod_dict = PyModule_GetDict (pmod);
452 if ((pmod_dict != NULL)
453 && PyDict_Check (pmod_dict))
454 {
455 PyObject *key, *value;
456 Py_ssize_t pos = 0;
457
458 while (PyDict_Next (pmod_dict, &pos, &key, &value))
459 {
460 Py_INCREF (key);
461 Py_INCREF (value);
462 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
463 {
464 pfunc = value;
465 break;
466 }
467 }
468
469 PyObject *string_arg = PyString_FromString (command);
470 if (pfunc && string_arg && PyCallable_Check (pfunc))
471 {
472 PyObject *pargs = PyTuple_New (2);
473 if (pargs != NULL)
474 {
475 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
476 PyTuple_SetItem (pargs, 1, string_arg);
477 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
478 Py_DECREF (pargs);
479 if (pvalue != NULL)
480 {
481 Py_DECREF (pvalue);
482 success = true;
483 }
484 else if (PyErr_Occurred ())
485 {
486 PyErr_Print();
487 PyErr_Clear();
488 }
489 }
490 }
491 }
492 }
493 Py_INCREF (script_interpreter_dict);
494 }
495 }
Greg Clayton63094e02010-06-23 01:19:29 +0000496
Caroline Tice4a461da2011-01-14 21:09:29 +0000497 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000498 return true;
499
500 // The one-liner failed. Append the error message.
501 if (result)
502 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
503 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000504 }
Johnny Chen60dde642010-07-30 22:33:14 +0000505
506 if (result)
507 result->AppendError ("empty command passed to python\n");
508 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000509}
510
Chris Lattner24943d22010-06-08 16:52:24 +0000511size_t
512ScriptInterpreterPython::InputReaderCallback
513(
514 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000515 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000516 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000517 const char *bytes,
518 size_t bytes_len
519)
520{
Caroline Tice2ade6112010-11-10 19:18:14 +0000521 lldb::thread_t embedded_interpreter_thread;
522 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
523
Chris Lattner24943d22010-06-08 16:52:24 +0000524 if (baton == NULL)
525 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000526
527 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000528
Caroline Tice0aa2e552011-01-14 00:29:16 +0000529 if (script_interpreter->m_script_lang != eScriptLanguagePython)
530 return 0;
531
Caroline Tice892fadd2011-06-16 16:27:19 +0000532 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
533 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
534
Chris Lattner24943d22010-06-08 16:52:24 +0000535 switch (notification)
536 {
537 case eInputReaderActivate:
538 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000539 if (!batch_mode)
540 {
541 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
542 out_stream->Flush();
543 }
Greg Clayton58928562011-02-09 01:08:52 +0000544
Chris Lattner24943d22010-06-08 16:52:24 +0000545 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000546 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
547 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000548 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000549
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000550 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000551
Caroline Tice202f6b82011-01-17 21:55:19 +0000552 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000553 ScriptInterpreterPython::Locker locker(script_interpreter,
554 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
555 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000556 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000557
Caroline Tice2ade6112010-11-10 19:18:14 +0000558 char error_str[1024];
559 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
560 sizeof(error_str)))
561 {
562 if (log)
563 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
564 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
565 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
566 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
567 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000568 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000569 {
570 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000571 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000572 Error detach_error;
573 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
574 }
575 else
576 {
577 if (log)
578 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
579 reader.SetIsDone (true);
580 }
581 }
582 else
583 {
584 if (log)
585 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
586 reader.SetIsDone (true);
587 }
Chris Lattner24943d22010-06-08 16:52:24 +0000588 }
589 break;
590
591 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000592 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000593 break;
594
595 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000596 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000597 ScriptInterpreterPython::Locker locker(script_interpreter,
598 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
599 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000600 }
Chris Lattner24943d22010-06-08 16:52:24 +0000601 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000602
Caroline Tice4a348082011-05-02 20:41:46 +0000603 case eInputReaderAsynchronousOutputWritten:
604 break;
605
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000606 case eInputReaderInterrupt:
607 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
608 break;
609
610 case eInputReaderEndOfFile:
611 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
612 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000613
614 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000615 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000616 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000617 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000618 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000619 bytes_len);
620 if (bytes && bytes_len)
621 {
622 if ((int) bytes[0] == 4)
623 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
624 else
625 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
626 }
627 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000628 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000629 else
630 {
631 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000632 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000633 bytes,
634 bytes_len);
635 reader.SetIsDone (true);
636 }
637
Chris Lattner24943d22010-06-08 16:52:24 +0000638 break;
639
640 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000641 script_interpreter->LeaveSession ();
642
Chris Lattner24943d22010-06-08 16:52:24 +0000643 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000644 if (log)
645 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000646
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000647 script_interpreter->RestoreTerminalState ();
648
Caroline Tice2ade6112010-11-10 19:18:14 +0000649 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000650 break;
651 }
652
653 return bytes_len;
654}
655
656
657void
Greg Clayton238c0a12010-09-18 01:14:36 +0000658ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000659{
660 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
661
Caroline Tice0aa2e552011-01-14 00:29:16 +0000662 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000663
664 // At the moment, the only time the debugger does not have an input file handle is when this is called
665 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
666 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
667 // do it.
668
Greg Clayton58928562011-02-09 01:08:52 +0000669 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000670 return;
671
Greg Clayton63094e02010-06-23 01:19:29 +0000672 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000673 if (reader_sp)
674 {
675 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
676 this, // baton
677 eInputReaderGranularityLine, // token size, to pass to callback function
678 NULL, // end token
679 NULL, // prompt
680 true)); // echo input
681
682 if (error.Success())
683 {
Greg Clayton63094e02010-06-23 01:19:29 +0000684 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000685 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000686 }
687 }
688}
689
690bool
691ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000692 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000693 void *ret_value)
694{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000695
Enrico Granatafa1f6172011-10-24 17:22:21 +0000696 Locker locker(this,
697 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
698 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000699
Chris Lattner24943d22010-06-08 16:52:24 +0000700 PyObject *py_return = NULL;
701 PyObject *mainmod = PyImport_AddModule ("__main__");
702 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000703 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000704 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000705 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000706 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000707 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000708
709 if (PyDict_Check (globals))
710 {
711 PyObject *key, *value;
712 Py_ssize_t pos = 0;
713
714 int i = 0;
715 while (PyDict_Next (globals, &pos, &key, &value))
716 {
717 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
718 // so that Python's garbage collector doesn't collect them out from under us.
719 Py_INCREF (key);
720 Py_INCREF (value);
721 char *c_str = PyString_AsString (key);
722 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
723 locals = value;
724 ++i;
725 }
726 }
Chris Lattner24943d22010-06-08 16:52:24 +0000727
Caroline Tice0aa2e552011-01-14 00:29:16 +0000728 if (locals == NULL)
729 {
730 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
731 should_decrement_locals = true;
732 }
733
734 if (locals == NULL)
735 {
736 locals = globals;
737 should_decrement_locals = false;
738 }
739
740 py_error = PyErr_Occurred();
741 if (py_error != NULL)
742 PyErr_Clear();
743
Chris Lattner24943d22010-06-08 16:52:24 +0000744 if (in_string != NULL)
745 {
746 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
747 if (py_return == NULL)
748 {
749 py_error = PyErr_Occurred ();
750 if (py_error != NULL)
751 PyErr_Clear ();
752
753 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
754 }
755
Caroline Tice0aa2e552011-01-14 00:29:16 +0000756 if (locals != NULL
757 && should_decrement_locals)
758 Py_DECREF (locals);
759
Chris Lattner24943d22010-06-08 16:52:24 +0000760 if (py_return != NULL)
761 {
762 switch (return_type)
763 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000764 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000765 {
766 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000767 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000768 break;
769 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000770 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000771 {
772 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000773 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000774 break;
775 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000776 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000777 {
778 const char format[2] = "b";
779 success = PyArg_Parse (py_return, format, (bool *) ret_value);
780 break;
781 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000782 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000783 {
784 const char format[2] = "h";
785 success = PyArg_Parse (py_return, format, (short *) ret_value);
786 break;
787 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000788 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000789 {
790 const char format[2] = "H";
791 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
792 break;
793 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000794 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000795 {
796 const char format[2] = "i";
797 success = PyArg_Parse (py_return, format, (int *) ret_value);
798 break;
799 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000800 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000801 {
802 const char format[2] = "I";
803 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
804 break;
805 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000806 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000807 {
808 const char format[2] = "l";
809 success = PyArg_Parse (py_return, format, (long *) ret_value);
810 break;
811 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000812 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000813 {
814 const char format[2] = "k";
815 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
816 break;
817 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000818 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000819 {
820 const char format[2] = "L";
821 success = PyArg_Parse (py_return, format, (long long *) ret_value);
822 break;
823 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000824 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000825 {
826 const char format[2] = "K";
827 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
828 break;
829 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000830 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000831 {
832 const char format[2] = "f";
833 success = PyArg_Parse (py_return, format, (float *) ret_value);
834 break;
835 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000836 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000837 {
838 const char format[2] = "d";
839 success = PyArg_Parse (py_return, format, (double *) ret_value);
840 break;
841 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000842 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000843 {
844 const char format[2] = "c";
845 success = PyArg_Parse (py_return, format, (char *) ret_value);
846 break;
847 }
848 default:
849 {}
850 }
851 Py_DECREF (py_return);
852 if (success)
853 ret_success = true;
854 else
855 ret_success = false;
856 }
857 }
858
859 py_error = PyErr_Occurred();
860 if (py_error != NULL)
861 {
862 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
863 PyErr_Print ();
864 PyErr_Clear();
865 ret_success = false;
866 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000867
Chris Lattner24943d22010-06-08 16:52:24 +0000868 return ret_success;
869}
870
871bool
872ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
873{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000874
875
876 Locker locker(this,
877 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
878 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000879
Chris Lattner24943d22010-06-08 16:52:24 +0000880 bool success = false;
881 PyObject *py_return = NULL;
882 PyObject *mainmod = PyImport_AddModule ("__main__");
883 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000884 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000885 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000886 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000887
Caroline Tice0aa2e552011-01-14 00:29:16 +0000888 if (PyDict_Check (globals))
889 {
890 PyObject *key, *value;
891 Py_ssize_t pos = 0;
892
893 while (PyDict_Next (globals, &pos, &key, &value))
894 {
895 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
896 // so that Python's garbage collector doesn't collect them out from under us.
897 Py_INCREF (key);
898 Py_INCREF (value);
899 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
900 locals = value;
901 }
902 }
903
904 if (locals == NULL)
905 {
906 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
907 should_decrement_locals = true;
908 }
909
910 if (locals == NULL)
911 {
912 locals = globals;
913 should_decrement_locals = false;
914 }
915
916 py_error = PyErr_Occurred();
917 if (py_error != NULL)
918 PyErr_Clear();
919
Chris Lattner24943d22010-06-08 16:52:24 +0000920 if (in_string != NULL)
921 {
922 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
923 if (compiled_node)
924 {
925 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
926 if (compiled_code)
927 {
928 py_return = PyEval_EvalCode (compiled_code, globals, locals);
929 if (py_return != NULL)
930 {
931 success = true;
932 Py_DECREF (py_return);
933 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000934 if (locals && should_decrement_locals)
935 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000936 }
937 }
938 }
939
940 py_error = PyErr_Occurred ();
941 if (py_error != NULL)
942 {
943 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
944 PyErr_Print ();
945 PyErr_Clear();
946 success = false;
947 }
948
949 return success;
950}
951
952static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
953
954size_t
955ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
956(
957 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000958 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000959 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000960 const char *bytes,
961 size_t bytes_len
962)
963{
Caroline Tice892fadd2011-06-16 16:27:19 +0000964 static StringList commands_in_progress;
965
966 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
967 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
968
Chris Lattner24943d22010-06-08 16:52:24 +0000969 switch (notification)
970 {
971 case eInputReaderActivate:
972 {
973 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +0000974 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +0000975 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000976 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000977 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +0000978 out_stream->Printf ("%s", reader.GetPrompt());
979 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +0000980 }
981 }
982 break;
983
984 case eInputReaderDeactivate:
985 break;
986
987 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +0000988 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000989 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000990 out_stream->Printf ("%s", reader.GetPrompt());
991 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +0000992 }
Chris Lattner24943d22010-06-08 16:52:24 +0000993 break;
994
Caroline Tice4a348082011-05-02 20:41:46 +0000995 case eInputReaderAsynchronousOutputWritten:
996 break;
997
Chris Lattner24943d22010-06-08 16:52:24 +0000998 case eInputReaderGotToken:
999 {
1000 std::string temp_string (bytes, bytes_len);
1001 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001002 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001003 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001004 out_stream->Printf ("%s", reader.GetPrompt());
1005 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001006 }
Chris Lattner24943d22010-06-08 16:52:24 +00001007 }
1008 break;
1009
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001010 case eInputReaderEndOfFile:
1011 case eInputReaderInterrupt:
1012 // Control-c (SIGINT) & control-d both mean finish & exit.
1013 reader.SetIsDone(true);
1014
1015 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1016 if (notification == eInputReaderInterrupt)
1017 commands_in_progress.Clear();
1018
1019 // Fall through here...
1020
Chris Lattner24943d22010-06-08 16:52:24 +00001021 case eInputReaderDone:
1022 {
1023 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1024 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1025 data_ap->user_source.AppendList (commands_in_progress);
1026 if (data_ap.get())
1027 {
Greg Clayton63094e02010-06-23 01:19:29 +00001028 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001029 if (interpreter)
1030 {
1031 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1032 data_ap->script_source))
1033 {
1034 if (data_ap->script_source.GetSize() == 1)
1035 {
1036 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1037 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1038 }
1039 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001040 else if (!batch_mode)
1041 {
1042 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1043 out_stream->Flush();
1044 }
Chris Lattner24943d22010-06-08 16:52:24 +00001045 }
1046 else
1047 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001048 if (!batch_mode)
1049 {
1050 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1051 out_stream->Flush();
1052 }
Chris Lattner24943d22010-06-08 16:52:24 +00001053 }
1054 }
1055 }
1056 break;
1057
1058 }
1059
1060 return bytes_len;
1061}
1062
1063void
Greg Clayton238c0a12010-09-18 01:14:36 +00001064ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001065 CommandReturnObject &result)
1066{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001067 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1068
Greg Clayton63094e02010-06-23 01:19:29 +00001069 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001070
1071 if (reader_sp)
1072 {
1073 Error err = reader_sp->Initialize (
1074 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1075 bp_options, // baton
1076 eInputReaderGranularityLine, // token size, for feeding data to callback function
1077 "DONE", // end token
1078 "> ", // prompt
1079 true); // echo input
1080
1081 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001082 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001083 else
1084 {
1085 result.AppendError (err.AsCString());
1086 result.SetStatus (eReturnStatusFailed);
1087 }
1088 }
1089 else
1090 {
1091 result.AppendError("out of memory");
1092 result.SetStatus (eReturnStatusFailed);
1093 }
1094}
1095
Johnny Chen3e0571b2010-09-11 00:23:59 +00001096// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001097void
Greg Clayton238c0a12010-09-18 01:14:36 +00001098ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001099 const char *oneliner)
1100{
1101 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1102
1103 // It's necessary to set both user_source and script_source to the oneliner.
1104 // The former is used to generate callback description (as in breakpoint command list)
1105 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001106
Johnny Chend1c2dca2010-09-10 18:21:10 +00001107 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001108
Caroline Tice5136f942010-09-27 21:35:15 +00001109 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1110 {
1111 if (data_ap->script_source.GetSize() == 1)
1112 {
1113 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1114 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1115 }
1116 }
1117
Johnny Chend1c2dca2010-09-10 18:21:10 +00001118 return;
1119}
1120
Chris Lattner24943d22010-06-08 16:52:24 +00001121bool
1122ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1123{
1124 // Convert StringList to one long, newline delimited, const char *.
1125 std::string function_def_string;
1126
1127 int num_lines = function_def.GetSize();
1128
1129 for (int i = 0; i < num_lines; ++i)
1130 {
1131 function_def_string.append (function_def.GetStringAtIndex(i));
1132 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1133 function_def_string.append ("\n");
1134
1135 }
1136
1137 return ExecuteMultipleLines (function_def_string.c_str());
1138}
1139
Enrico Granataf7a9b142011-07-15 02:26:42 +00001140// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1141// use this code to generate their functions
1142bool
1143ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1144{
1145 int num_lines = input.GetSize ();
1146 if (num_lines == 0)
1147 return false;
1148 StreamString sstr;
1149 StringList auto_generated_function;
1150 auto_generated_function.AppendString (signature.c_str());
1151 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1152 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1153 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1154 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1155 // global dictionary.
1156
1157 // Wrap everything up inside the function, increasing the indentation.
1158
1159 for (int i = 0; i < num_lines; ++i)
1160 {
1161 sstr.Clear ();
1162 sstr.Printf (" %s", input.GetStringAtIndex (i));
1163 auto_generated_function.AppendString (sstr.GetData());
1164 }
1165 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1166 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1167 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1168 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1169
1170 // Verify that the results are valid Python.
1171
1172 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1173 return false;
1174
1175 return true;
1176
1177}
1178
1179// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1180// given to generated functions, of course)
1181bool
1182ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output)
1183{
1184 static int num_created_functions = 0;
1185 user_input.RemoveBlankLines ();
1186 int num_lines = user_input.GetSize ();
1187 StreamString sstr;
1188
1189 // Check to see if we have any data; if not, just return.
1190 if (user_input.GetSize() == 0)
1191 return false;
1192
1193 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1194 // ValueObject as parameter to the function.
1195
1196 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1197 ++num_created_functions;
1198 std::string auto_generated_function_name = sstr.GetData();
1199
1200 sstr.Clear();
1201 StringList auto_generated_function;
1202
1203 // Create the function name & definition string.
1204
1205 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1206 auto_generated_function.AppendString (sstr.GetData());
1207
1208 // Pre-pend code for setting up the session dictionary.
1209
1210 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1211 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1212 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1213 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1214 // global dictionary.
1215
1216 // Wrap everything up inside the function, increasing the indentation.
1217
1218 for (int i = 0; i < num_lines; ++i)
1219 {
1220 sstr.Clear ();
1221 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1222 auto_generated_function.AppendString (sstr.GetData());
1223 }
1224
1225 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1226 // got written to the values in the global dictionary, not the session dictionary).
1227
1228 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1229 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1230 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1231 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1232
1233 // Verify that the results are valid Python.
1234
1235 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1236 return false;
1237
1238 // Store the name of the auto-generated function to be called.
1239
1240 output.AppendString (auto_generated_function_name.c_str());
1241 return true;
1242}
1243
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001244bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001245ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, StringList &output)
1246{
1247 static int num_created_functions = 0;
1248 user_input.RemoveBlankLines ();
1249 int num_lines = user_input.GetSize ();
1250 StreamString sstr;
1251
1252 // Check to see if we have any data; if not, just return.
1253 if (user_input.GetSize() == 0)
1254 return false;
1255
1256 // 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 +00001257 // required data as parameters to the function.
Enrico Granatac2a28252011-08-16 16:49:25 +00001258
1259 sstr.Printf ("lldb_autogen_python_cmd_alias_func_%d", num_created_functions);
1260 ++num_created_functions;
1261 std::string auto_generated_function_name = sstr.GetData();
1262
1263 sstr.Clear();
1264 StringList auto_generated_function;
1265
1266 // Create the function name & definition string.
1267
Enrico Granata271568f2011-09-09 01:41:30 +00001268 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001269 auto_generated_function.AppendString (sstr.GetData());
1270
1271 // Pre-pend code for setting up the session dictionary.
1272
1273 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1274 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1275 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1276 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1277 // global dictionary.
1278
1279 // Wrap everything up inside the function, increasing the indentation.
1280
1281 for (int i = 0; i < num_lines; ++i)
1282 {
1283 sstr.Clear ();
1284 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1285 auto_generated_function.AppendString (sstr.GetData());
1286 }
1287
1288 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1289 // got written to the values in the global dictionary, not the session dictionary).
1290
1291 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1292 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1293 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1294 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1295
1296 // Verify that the results are valid Python.
1297
1298 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1299 return false;
1300
1301 // Store the name of the auto-generated function to be called.
1302
1303 output.AppendString (auto_generated_function_name.c_str());
1304 return true;
1305}
1306
1307
1308bool
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001309ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output)
1310{
1311 static int num_created_classes = 0;
1312 user_input.RemoveBlankLines ();
1313 int num_lines = user_input.GetSize ();
1314 StreamString sstr;
1315
1316 // Check to see if we have any data; if not, just return.
1317 if (user_input.GetSize() == 0)
1318 return false;
1319
1320 // Wrap all user input into a Python class
1321
1322 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1323 ++num_created_classes;
1324 std::string auto_generated_class_name = sstr.GetData();
1325
1326 sstr.Clear();
1327 StringList auto_generated_class;
1328
1329 // Create the function name & definition string.
1330
1331 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1332 auto_generated_class.AppendString (sstr.GetData());
1333
1334 // Wrap everything up inside the class, increasing the indentation.
1335
1336 for (int i = 0; i < num_lines; ++i)
1337 {
1338 sstr.Clear ();
1339 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1340 auto_generated_class.AppendString (sstr.GetData());
1341 }
1342
1343
1344 // Verify that the results are valid Python.
1345 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1346 // (TODO: rename that method to ExportDefinitionToInterpreter)
1347 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1348 return false;
1349
1350 // Store the name of the auto-generated class
1351
1352 output.AppendString (auto_generated_class_name.c_str());
1353 return true;
1354}
1355
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001356void*
1357ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1358 lldb::ValueObjectSP valobj)
1359{
1360 if (class_name.empty())
1361 return NULL;
1362
1363 if (!valobj.get())
1364 return NULL;
1365
Enrico Granata979e20d2011-07-29 19:53:35 +00001366 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001367
1368 if (!target)
1369 return NULL;
1370
1371 Debugger &debugger = target->GetDebugger();
1372 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1373 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1374
1375 if (!script_interpreter)
1376 return NULL;
1377
1378 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001379
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001380 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001381 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001382 ret_val = g_swig_synthetic_script (class_name,
1383 python_interpreter->m_dictionary_name.c_str(),
1384 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001385 }
1386
1387 return ret_val;
1388}
1389
Enrico Granataf7a9b142011-07-15 02:26:42 +00001390bool
1391ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output)
1392{
1393 StringList input(oneliner);
1394 return GenerateTypeScriptFunction(input, output);
1395}
1396
Chris Lattner24943d22010-06-08 16:52:24 +00001397bool
1398ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1399{
1400 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001401 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001402 int num_lines = user_input.GetSize ();
1403 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001404
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001405 // Check to see if we have any data; if not, just return.
1406 if (user_input.GetSize() == 0)
1407 return false;
1408
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001409 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1410 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001411
Caroline Ticeb447e842010-09-21 19:25:28 +00001412
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001413 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1414 ++num_created_functions;
1415 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001416
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001417 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001418 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001419
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001420 // Create the function name & definition string.
1421
Caroline Tice0aa2e552011-01-14 00:29:16 +00001422 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001423 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001424
1425 // Pre-pend code for setting up the session dictionary.
1426
1427 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1428 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1429 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1430 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1431 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001432
1433 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001434
1435 for (int i = 0; i < num_lines; ++i)
1436 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001437 sstr.Clear ();
1438 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1439 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001440 }
Chris Lattner24943d22010-06-08 16:52:24 +00001441
Caroline Tice0aa2e552011-01-14 00:29:16 +00001442 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1443 // got written to the values in the global dictionary, not the session dictionary).
1444
1445 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1446 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1447 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1448 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1449
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001450 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001451
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001452 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001453 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001454 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001455 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001456
1457 // Store the name of the auto-generated function to be called.
1458
1459 callback_data.AppendString (auto_generated_function_name.c_str());
1460 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001461}
1462
Enrico Granataf7a9b142011-07-15 02:26:42 +00001463std::string
1464ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1465 lldb::ValueObjectSP valobj)
1466{
1467
1468 if (!python_function_name || !(*python_function_name))
1469 return "<no function>";
1470
1471 if (!valobj.get())
1472 return "<no object>";
1473
Enrico Granata979e20d2011-07-29 19:53:35 +00001474 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001475
1476 if (!target)
1477 return "<no target>";
1478
1479 Debugger &debugger = target->GetDebugger();
1480 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1481 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1482
1483 if (!script_interpreter)
1484 return "<no python>";
1485
1486 std::string ret_val;
1487
1488 if (python_function_name
1489 && *python_function_name)
1490 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001491 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001492 Locker py_lock(python_interpreter);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001493 ret_val = g_swig_typescript_callback (python_function_name,
1494 python_interpreter->m_dictionary_name.c_str(),
1495 valobj);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001496 }
1497 }
1498 else
1499 return "<no function name>";
1500
1501 return ret_val;
1502
1503}
1504
Greg Clayton5144f382010-10-07 17:14:24 +00001505bool
1506ScriptInterpreterPython::BreakpointCallbackFunction
1507(
1508 void *baton,
1509 StoppointCallbackContext *context,
1510 user_id_t break_id,
1511 user_id_t break_loc_id
1512)
1513{
1514 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1515 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001516
1517 if (!context)
1518 return true;
1519
Greg Clayton567e7f32011-09-22 04:58:26 +00001520 Target *target = context->exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001521
1522 if (!target)
1523 return true;
1524
1525 Debugger &debugger = target->GetDebugger();
1526 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1527 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1528
1529 if (!script_interpreter)
1530 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001531
1532 if (python_function_name != NULL
1533 && python_function_name[0] != '\0')
1534 {
Greg Clayton567e7f32011-09-22 04:58:26 +00001535 const StackFrameSP stop_frame_sp (context->exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001536 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001537 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001538 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001539 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1540
1541 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001542 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001543 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001544 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001545 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001546 ret_val = g_swig_breakpoint_callback (python_function_name,
1547 python_interpreter->m_dictionary_name.c_str(),
1548 stop_frame_sp,
1549 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001550 }
1551 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001552 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001553 }
Greg Clayton5144f382010-10-07 17:14:24 +00001554 }
1555 // We currently always true so we stop in case anything goes wrong when
1556 // trying to call the script function
1557 return true;
1558}
Caroline Tice2ade6112010-11-10 19:18:14 +00001559
1560lldb::thread_result_t
1561ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1562{
1563 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1564
1565 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1566
1567 if (log)
1568 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1569
1570 char error_str[1024];
1571 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001572
Enrico Granatafa1f6172011-10-24 17:22:21 +00001573 Locker locker(script_interpreter,
1574 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1575 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1576
1577 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001578 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001579 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001580
Caroline Tice0aa2e552011-01-14 00:29:16 +00001581 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1582 PyRun_SimpleString (run_string.GetData());
1583 run_string.Clear ();
1584
1585 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1586 PyRun_SimpleString (run_string.GetData());
1587 run_string.Clear ();
1588
1589 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1590 PyRun_SimpleString (run_string.GetData());
1591 run_string.Clear ();
1592
1593 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1594 pty_slave_name);
1595 PyRun_SimpleString (run_string.GetData());
1596 run_string.Clear ();
1597
Johnny Chen8054ba32011-03-11 00:28:50 +00001598 // The following call drops into the embedded interpreter loop and stays there until the
1599 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001600
Caroline Ticece207c12011-03-11 00:21:55 +00001601 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001602 // 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 +00001603 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1604
1605 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1606 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1607 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1608 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1609 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1610 // hang (it's happened before).
1611
Caroline Tice9d352ce2011-03-07 23:24:28 +00001612 Py_BEGIN_ALLOW_THREADS
1613 PyGILState_STATE gstate = PyGILState_Ensure();
1614
Caroline Tice0aa2e552011-01-14 00:29:16 +00001615 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1616 PyRun_SimpleString (run_string.GetData());
1617 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001618
Caroline Tice9d352ce2011-03-07 23:24:28 +00001619 PyGILState_Release (gstate);
1620 Py_END_ALLOW_THREADS
1621
Caroline Tice0aa2e552011-01-14 00:29:16 +00001622 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1623 PyRun_SimpleString (run_string.GetData());
1624 run_string.Clear();
1625
1626 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1627 PyRun_SimpleString (run_string.GetData());
1628 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001629
Caroline Tice2ade6112010-11-10 19:18:14 +00001630 }
1631
1632 if (script_interpreter->m_embedded_thread_input_reader_sp)
1633 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1634
1635 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001636
1637 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001638
1639 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1640 if (log)
1641 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1642
1643
Johnny Chen8054ba32011-03-11 00:28:50 +00001644 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001645 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001646 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1647 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1648 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001649
Caroline Tice2ade6112010-11-10 19:18:14 +00001650 return NULL;
1651}
1652
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001653uint32_t
1654ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1655{
1656 if (!implementor)
1657 return 0;
1658
1659 if (!g_swig_calc_children)
1660 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001661
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001662 uint32_t ret_val = 0;
1663
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001664 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001665 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001666 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001667 }
1668
1669 return ret_val;
1670}
1671
Enrico Granata91544802011-09-06 19:20:51 +00001672lldb::ValueObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001673ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1674{
1675 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001676 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001677
Enrico Granata91544802011-09-06 19:20:51 +00001678 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1679 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001680
Enrico Granata91544802011-09-06 19:20:51 +00001681 void* child_ptr = NULL;
1682 lldb::SBValue* value_sb = NULL;
1683 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001684
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001685 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001686 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +00001687 child_ptr = g_swig_get_child_index (implementor,idx);
1688 if (child_ptr != NULL && child_ptr != Py_None)
1689 {
1690 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1691 if (value_sb == NULL)
1692 Py_XDECREF(child_ptr);
1693 else
1694 ret_val = value_sb->get_sp();
1695 }
1696 else
1697 {
1698 Py_XDECREF(child_ptr);
1699 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001700 }
1701
1702 return ret_val;
1703}
1704
1705int
1706ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1707{
1708 if (!implementor)
1709 return UINT32_MAX;
1710
1711 if (!g_swig_get_index_child)
1712 return UINT32_MAX;
1713
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001714 int ret_val = UINT32_MAX;
1715
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001716 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001717 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001718 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001719 }
1720
1721 return ret_val;
1722}
1723
Enrico Granata979e20d2011-07-29 19:53:35 +00001724void
1725ScriptInterpreterPython::UpdateSynthProviderInstance (void* implementor)
1726{
1727 if (!implementor)
1728 return;
1729
1730 if (!g_swig_update_provider)
1731 return;
1732
Enrico Granata979e20d2011-07-29 19:53:35 +00001733 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001734 Locker py_lock(this);
Enrico Granata979e20d2011-07-29 19:53:35 +00001735 g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001736 }
1737
1738 return;
1739}
1740
Enrico Granatac2a28252011-08-16 16:49:25 +00001741bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001742ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
1743 lldb_private::Error& error)
1744{
1745 if (!pathname || !pathname[0])
1746 {
1747 error.SetErrorString("invalid pathname");
1748 return false;
1749 }
1750
1751 if (!g_swig_call_module_init)
1752 {
1753 error.SetErrorString("internal helper function missing");
1754 return false;
1755 }
1756
Enrico Granata59df36f2011-10-17 21:45:27 +00001757 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
Enrico Granatafa1f6172011-10-24 17:22:21 +00001758
Enrico Granata59df36f2011-10-17 21:45:27 +00001759 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001760 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00001761
1762 FileSpec target_file(pathname, true);
1763
1764 // TODO: would we want to reject any other value?
1765 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1766 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1767 {
1768 error.SetErrorString("invalid pathname");
1769 return false;
1770 }
1771
1772 const char* directory = target_file.GetDirectory().GetCString();
1773 std::string basename(target_file.GetFilename().GetCString());
1774
1775 // now make sure that Python has "directory" in the search path
1776 StreamString command_stream;
1777 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1778 directory,
1779 directory);
Enrico Granatafa1f6172011-10-24 17:22:21 +00001780 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData());
Enrico Granata59df36f2011-10-17 21:45:27 +00001781 if (!syspath_retval)
1782 {
1783 error.SetErrorString("Python sys.path handling failed");
1784 return false;
1785 }
1786
1787 // strip .py or .pyc extension
1788 ConstString extension = target_file.GetFileNameExtension();
1789 if (::strcmp(extension.GetCString(), "py") == 0)
1790 basename.resize(basename.length()-3);
1791 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1792 basename.resize(basename.length()-4);
1793
1794 // check if the module is already import-ed
1795 command_stream.Clear();
1796 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1797 int refcount = 0;
1798 // this call will fail if the module does not exist (because the parameter to it is not a string
1799 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granatafa1f6172011-10-24 17:22:21 +00001800 if (ExecuteOneLineWithReturn(command_stream.GetData(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001801 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0)
1802 {
1803 error.SetErrorString("module already imported");
1804 return false;
1805 }
1806
1807 // now actually do the import
1808 command_stream.Clear();
1809 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafa1f6172011-10-24 17:22:21 +00001810 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL);
Enrico Granata59df36f2011-10-17 21:45:27 +00001811 if (!import_retval)
1812 {
1813 error.SetErrorString("Python import statement failed");
1814 return false;
1815 }
1816
1817 // call __lldb_module_init(debugger,dict)
1818 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001819 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001820 debugger_sp))
1821 {
1822 error.SetErrorString("calling __lldb_module_init failed");
1823 return false;
1824 }
1825 return true;
1826 }
1827}
1828
1829bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001830ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1831 const char* args,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001832 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001833 Error& error)
1834{
1835 if (!impl_function)
1836 {
1837 error.SetErrorString("no function to execute");
1838 return false;
1839 }
1840
1841 if (!g_swig_call_command)
1842 {
1843 error.SetErrorString("no helper function to run scripted commands");
1844 return false;
1845 }
1846
Enrico Granatac2a28252011-08-16 16:49:25 +00001847 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
1848
1849 bool ret_val;
1850
1851 std::string err_msg;
1852
Enrico Granatac2a28252011-08-16 16:49:25 +00001853 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001854 Locker py_lock(this);
Enrico Granatac2a28252011-08-16 16:49:25 +00001855 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001856 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00001857 debugger_sp,
1858 args,
1859 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001860 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001861 }
1862
1863 if (!ret_val)
1864 error.SetErrorString(err_msg.c_str());
1865 else
1866 error.Clear();
Enrico Granata3370f0c2011-08-19 23:56:34 +00001867
Enrico Granatac2a28252011-08-16 16:49:25 +00001868 return ret_val;
1869
1870
1871 return true;
1872
1873}
1874
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001875// in Python, a special attribute __doc__ contains the docstring
1876// for an object (function, method, class, ...) if any is defined
1877// Otherwise, the attribute's value is None
1878std::string
1879ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1880{
1881 std::string command(item);
1882 command += ".__doc__";
1883
1884 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1885
1886 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001887 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001888 &result_ptr) && result_ptr)
1889 {
1890 return std::string(result_ptr);
1891 }
1892 else
1893 return std::string("");
1894}
Caroline Tice2ade6112010-11-10 19:18:14 +00001895
Caroline Tice0aa2e552011-01-14 00:29:16 +00001896void
Greg Claytone86cbb92011-03-22 01:14:58 +00001897ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00001898 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001899 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
1900 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
1901 SWIGPythonCalculateNumChildren python_swig_calc_children,
1902 SWIGPythonGetChildAtIndex python_swig_get_child_index,
1903 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
Enrico Granata979e20d2011-07-29 19:53:35 +00001904 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue,
Enrico Granatac2a28252011-08-16 16:49:25 +00001905 SWIGPythonUpdateSynthProviderInstance python_swig_update_provider,
Enrico Granata59df36f2011-10-17 21:45:27 +00001906 SWIGPythonCallCommand python_swig_call_command,
1907 SWIGPythonCallModuleInit python_swig_call_mod_init)
Greg Claytone86cbb92011-03-22 01:14:58 +00001908{
1909 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001910 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1911 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001912 g_swig_synthetic_script = python_swig_synthetic_script;
1913 g_swig_calc_children = python_swig_calc_children;
1914 g_swig_get_child_index = python_swig_get_child_index;
1915 g_swig_get_index_child = python_swig_get_index_child;
1916 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Enrico Granata979e20d2011-07-29 19:53:35 +00001917 g_swig_update_provider = python_swig_update_provider;
Enrico Granatac2a28252011-08-16 16:49:25 +00001918 g_swig_call_command = python_swig_call_command;
Enrico Granata59df36f2011-10-17 21:45:27 +00001919 g_swig_call_module_init = python_swig_call_mod_init;
Greg Claytone86cbb92011-03-22 01:14:58 +00001920}
1921
1922void
1923ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001924{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001925 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1926
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001927 // Python will muck with STDIN terminal state, so save off any current TTY
1928 // settings so we can restore them.
1929 TerminalState stdin_tty_state;
1930 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001931
Caroline Tice9d352ce2011-03-07 23:24:28 +00001932 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001933 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001934
Greg Claytone86cbb92011-03-22 01:14:58 +00001935 // Initialize SWIG after setting up python
1936 assert (g_swig_init_callback != NULL);
1937 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001938
1939 // Update the path python uses to search for modules to include the current directory.
1940
Caroline Ticed4d92832011-06-13 21:33:00 +00001941 PyRun_SimpleString ("import sys");
1942 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001943
1944 // Find the module that owns this code and use that path we get to
1945 // set the sys.path appropriately.
1946
1947 FileSpec file_spec;
1948 char python_dir_path[PATH_MAX];
1949 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1950 {
1951 std::string python_path("sys.path.insert(0,\"");
1952 size_t orig_len = python_path.length();
1953 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1954 {
1955 python_path.append (python_dir_path);
1956 python_path.append ("\")");
1957 PyRun_SimpleString (python_path.c_str());
1958 python_path.resize (orig_len);
1959 }
1960
1961 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1962 {
1963 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1964 {
1965 python_path.append (python_dir_path);
1966 python_path.append ("\")");
1967 PyRun_SimpleString (python_path.c_str());
1968 python_path.resize (orig_len);
1969 }
1970 }
1971 }
1972
Jim Ingham4dfa5112011-08-22 19:10:09 +00001973 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001974
Caroline Ticed4d92832011-06-13 21:33:00 +00001975 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001976
Caroline Ticed4d92832011-06-13 21:33:00 +00001977 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1978 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00001979 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001980
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001981 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001982}
1983
Greg Claytone86cbb92011-03-22 01:14:58 +00001984//void
1985//ScriptInterpreterPython::Terminate ()
1986//{
1987// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1988// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1989// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1990// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1991// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1992// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1993// // within Py_Finalize, which results in a seg fault.
1994// //
1995// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1996// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1997// // process exits).
1998// //
1999//// Py_Finalize ();
2000//}