blob: 2e950173b9143b7e6a7a324c490db1cace73f668 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ScriptInterpreterPython.cpp -----------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// In order to guarantee correct working with Python, Python.h *MUST* be
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +000011// the *FIRST* header file included here.
Greg Clayton3e4238d2011-11-04 03:34:56 +000012#ifdef LLDB_DISABLE_PYTHON
13
14// Python is disabled in this build
15
16#else
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +000017
18#if defined (__APPLE__)
19#include <Python/Python.h>
20#else
21#include <Python.h>
22#endif
Chris Lattner24943d22010-06-08 16:52:24 +000023
24#include "lldb/Interpreter/ScriptInterpreterPython.h"
25
Chris Lattner24943d22010-06-08 16:52:24 +000026#include <stdlib.h>
27#include <stdio.h>
28
29#include <string>
30
Enrico Granata91544802011-09-06 19:20:51 +000031#include "lldb/API/SBValue.h"
Greg Clayton987c7eb2011-09-17 08:33:22 +000032#include "lldb/Breakpoint/BreakpointLocation.h"
Greg Clayton63094e02010-06-23 01:19:29 +000033#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner24943d22010-06-08 16:52:24 +000034#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000035#include "lldb/Core/Timer.h"
36#include "lldb/Host/Host.h"
37#include "lldb/Interpreter/CommandInterpreter.h"
38#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton5144f382010-10-07 17:14:24 +000039#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040
Chris Lattner24943d22010-06-08 16:52:24 +000041using namespace lldb;
42using namespace lldb_private;
43
Greg Claytone86cbb92011-03-22 01:14:58 +000044
45static ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL;
46static ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL;
Enrico Granataf7a9b142011-07-15 02:26:42 +000047static ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL;
Enrico Granata9ae7cef2011-07-24 00:14:56 +000048static ScriptInterpreter::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = NULL;
49static ScriptInterpreter::SWIGPythonCalculateNumChildren g_swig_calc_children = NULL;
50static ScriptInterpreter::SWIGPythonGetChildAtIndex g_swig_get_child_index = NULL;
51static ScriptInterpreter::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = NULL;
52static ScriptInterpreter::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = NULL;
Enrico Granata979e20d2011-07-29 19:53:35 +000053static ScriptInterpreter::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = NULL;
Enrico Granatac2a28252011-08-16 16:49:25 +000054static ScriptInterpreter::SWIGPythonCallCommand g_swig_call_command = NULL;
Enrico Granata59df36f2011-10-17 21:45:27 +000055static ScriptInterpreter::SWIGPythonCallModuleInit g_swig_call_module_init = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +000056
57static int
58_check_and_flush (FILE *stream)
59{
60 int prev_fail = ferror (stream);
61 return fflush (stream) || prev_fail ? EOF : 0;
62}
63
Caroline Tice202f6b82011-01-17 21:55:19 +000064static Predicate<lldb::tid_t> &
65PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +000066{
Caroline Tice202f6b82011-01-17 21:55:19 +000067 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
68 return g_interpreter_is_running;
69}
70
Enrico Granatafa1f6172011-10-24 17:22:21 +000071bool
72ScriptInterpreterPython::Locker::CurrentThreadHasPythonLock ()
Caroline Tice202f6b82011-01-17 21:55:19 +000073{
74 TimeValue timeout;
75
76 timeout = TimeValue::Now(); // Don't wait any time.
77
78 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
79}
80
Enrico Granatafa1f6172011-10-24 17:22:21 +000081bool
82ScriptInterpreterPython::Locker::TryGetPythonLock (uint32_t seconds_to_wait)
Caroline Tice202f6b82011-01-17 21:55:19 +000083{
84
85 TimeValue timeout;
86
87 if (seconds_to_wait != UINT32_MAX)
88 {
89 timeout = TimeValue::Now();
90 timeout.OffsetWithSeconds (seconds_to_wait);
91 }
92
93 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
94 Host::GetCurrentThreadID(), &timeout, NULL);
95}
96
Enrico Granatafa1f6172011-10-24 17:22:21 +000097void
98ScriptInterpreterPython::Locker::ReleasePythonLock ()
Caroline Tice202f6b82011-01-17 21:55:19 +000099{
100 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000101}
102
Enrico Granatafa1f6172011-10-24 17:22:21 +0000103ScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *py_interpreter,
104 uint16_t on_entry,
105 uint16_t on_leave,
106 FILE* wait_msg_handle) :
107 m_need_session( (on_leave & TearDownSession) == TearDownSession ),
108 m_release_lock ( false ), // decide in constructor body
109 m_python_interpreter(py_interpreter),
110 m_tmp_fh(wait_msg_handle)
Enrico Granata91544802011-09-06 19:20:51 +0000111{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000112 if (m_python_interpreter && !m_tmp_fh)
113 m_tmp_fh = (m_python_interpreter->m_dbg_stdout ? m_python_interpreter->m_dbg_stdout : stdout);
114
115 if ( (on_entry & AcquireLock) == AcquireLock )
116 {
117 if (CurrentThreadHasPythonLock())
118 {
119 if ( (on_leave & FreeLock) == FreeLock )
120 m_release_lock = true;
121 }
122 else
123 {
124 DoAcquireLock();
125 if ( (on_leave & FreeLock) == FreeLock )
126 m_release_lock = true;
127 if ( (on_leave & FreeAcquiredLock) == FreeAcquiredLock )
128 m_release_lock = true;
129 }
130 }
131 if ( (on_entry & InitSession) == InitSession )
132 DoInitSession();
133}
134
135bool
136ScriptInterpreterPython::Locker::DoAcquireLock()
137{
Enrico Granata91544802011-09-06 19:20:51 +0000138 if (!CurrentThreadHasPythonLock())
139 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000140 while (!TryGetPythonLock (1))
141 if (m_tmp_fh)
142 fprintf (m_tmp_fh,
Enrico Granata91544802011-09-06 19:20:51 +0000143 "Python interpreter locked on another thread; waiting to acquire lock...\n");
Enrico Granata91544802011-09-06 19:20:51 +0000144 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000145 return true;
146}
147
148bool
149ScriptInterpreterPython::Locker::DoInitSession()
150{
151 if (!m_python_interpreter)
152 return false;
153 m_python_interpreter->EnterSession ();
154 return true;
155}
156
157bool
158ScriptInterpreterPython::Locker::DoFreeLock()
159{
160 ReleasePythonLock ();
161 return true;
162}
163
164bool
165ScriptInterpreterPython::Locker::DoTearDownSession()
166{
167 if (!m_python_interpreter)
168 return false;
169 m_python_interpreter->LeaveSession ();
170 return true;
Enrico Granata91544802011-09-06 19:20:51 +0000171}
172
173ScriptInterpreterPython::Locker::~Locker()
174{
175 if (m_need_session)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000176 DoTearDownSession();
Enrico Granata91544802011-09-06 19:20:51 +0000177 if (m_release_lock)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000178 DoFreeLock();
Enrico Granata91544802011-09-06 19:20:51 +0000179}
180
Greg Clayton63094e02010-06-23 01:19:29 +0000181ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000182 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000183 m_embedded_python_pty (),
184 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +0000185 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000186 m_new_sysout (NULL),
187 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000188 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000189 m_session_is_active (false),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000190 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000191{
192
Greg Clayton7c330d62011-01-27 01:01:10 +0000193 static int g_initialized = false;
194
195 if (!g_initialized)
196 {
197 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000198 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000199 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000200
201 Locker locker(this,
202 ScriptInterpreterPython::Locker::AcquireLock,
203 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Greg Clayton7c330d62011-01-27 01:01:10 +0000204
Caroline Tice0aa2e552011-01-14 00:29:16 +0000205 m_dictionary_name.append("_dict");
206 StreamString run_string;
207 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
208 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000209
Caroline Tice0aa2e552011-01-14 00:29:16 +0000210 run_string.Clear();
211 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
212 PyRun_SimpleString (run_string.GetData());
213
214 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
215 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
216 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
217 // call to Debugger::Terminate is made, the ref-count has the correct value.
218 //
219 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
220 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000221
Caroline Tice0aa2e552011-01-14 00:29:16 +0000222 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000223
Caroline Tice0aa2e552011-01-14 00:29:16 +0000224 run_string.Clear();
225 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
226 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000227
Caroline Tice0aa2e552011-01-14 00:29:16 +0000228 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000229
Caroline Tice0aa2e552011-01-14 00:29:16 +0000230 if (new_count > old_count)
231 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000232
Caroline Tice0aa2e552011-01-14 00:29:16 +0000233 run_string.Clear();
234 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
235 PyRun_SimpleString (run_string.GetData());
236
237 run_string.Clear();
Enrico Granata59df36f2011-10-17 21:45:27 +0000238 run_string.Printf ("run_one_line (%s, 'import os')", m_dictionary_name.c_str());
239 PyRun_SimpleString (run_string.GetData());
240
241 run_string.Clear();
Greg Clayton444e35b2011-10-19 18:09:39 +0000242 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000243 interpreter.GetDebugger().GetID());
244 PyRun_SimpleString (run_string.GetData());
245
Enrico Granata074e3b62011-08-17 19:07:52 +0000246 run_string.Clear();
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000247 run_string.Printf ("run_one_line (%s, 'import gnu_libstdcpp')", m_dictionary_name.c_str());
Enrico Granata074e3b62011-08-17 19:07:52 +0000248 PyRun_SimpleString (run_string.GetData());
249
Caroline Tice0aa2e552011-01-14 00:29:16 +0000250 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000251 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000252 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000253 }
Chris Lattner24943d22010-06-08 16:52:24 +0000254}
255
256ScriptInterpreterPython::~ScriptInterpreterPython ()
257{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000258 Debugger &debugger = GetCommandInterpreter().GetDebugger();
259
260 if (m_embedded_thread_input_reader_sp.get() != NULL)
261 {
262 m_embedded_thread_input_reader_sp->SetIsDone (true);
263 m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000264 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
265 m_embedded_thread_input_reader_sp.reset();
266 debugger.PopInputReader (reader_sp);
267 }
268
269 if (m_new_sysout)
270 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000271 Locker locker(this,
272 ScriptInterpreterPython::Locker::AcquireLock,
273 ScriptInterpreterPython::Locker::FreeLock);
274 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000275 }
Chris Lattner24943d22010-06-08 16:52:24 +0000276}
277
Caroline Tice0aa2e552011-01-14 00:29:16 +0000278void
279ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
280{
281 if (fh == NULL)
282 return;
283
284 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000285
Enrico Granatafa1f6172011-10-24 17:22:21 +0000286 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +0000287
288 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000289}
290
291void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000292ScriptInterpreterPython::SaveTerminalState (int fd)
293{
294 // Python mucks with the terminal state of STDIN. If we can possibly avoid
295 // this by setting the file handles up correctly prior to entering the
296 // interpreter we should. For now we save and restore the terminal state
297 // on the input file handle.
298 m_terminal_state.Save (fd, false);
299}
300
301void
302ScriptInterpreterPython::RestoreTerminalState ()
303{
304 // Python mucks with the terminal state of STDIN. If we can possibly avoid
305 // this by setting the file handles up correctly prior to entering the
306 // interpreter we should. For now we save and restore the terminal state
307 // on the input file handle.
308 m_terminal_state.Restore();
309}
310
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000311void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000312ScriptInterpreterPython::LeaveSession ()
313{
314 m_session_is_active = false;
315}
316
317void
318ScriptInterpreterPython::EnterSession ()
319{
320 // If we have already entered the session, without having officially 'left' it, then there is no need to
321 // 'enter' it again.
322
323 if (m_session_is_active)
324 return;
325
326 m_session_is_active = true;
327
Caroline Tice202f6b82011-01-17 21:55:19 +0000328 StreamString run_string;
329
Greg Clayton444e35b2011-10-19 18:09:39 +0000330 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice202f6b82011-01-17 21:55:19 +0000331 GetCommandInterpreter().GetDebugger().GetID());
332 PyRun_SimpleString (run_string.GetData());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000333 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +0000334
Caroline Tice0aa2e552011-01-14 00:29:16 +0000335
Greg Clayton444e35b2011-10-19 18:09:39 +0000336 run_string.Printf ("run_one_line (%s, 'lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)')",
Caroline Tice6af65cb2011-05-03 21:21:50 +0000337 m_dictionary_name.c_str(),
338 GetCommandInterpreter().GetDebugger().GetID());
339 PyRun_SimpleString (run_string.GetData());
340 run_string.Clear();
341
342
Greg Clayton567e7f32011-09-22 04:58:26 +0000343 ExecutionContext exe_ctx (m_interpreter.GetDebugger().GetSelectedExecutionContext());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000344
Greg Clayton567e7f32011-09-22 04:58:26 +0000345 if (exe_ctx.GetTargetPtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000346 run_string.Printf ("run_one_line (%s, 'lldb.target = lldb.debugger.GetSelectedTarget()')",
347 m_dictionary_name.c_str());
348 else
Greg Clayton177bc682012-01-27 00:13:27 +0000349 run_string.Printf ("run_one_line (%s, 'lldb.target = lldb.SBTarget()')", m_dictionary_name.c_str());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000350 PyRun_SimpleString (run_string.GetData());
351 run_string.Clear();
352
Greg Clayton567e7f32011-09-22 04:58:26 +0000353 if (exe_ctx.GetProcessPtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000354 run_string.Printf ("run_one_line (%s, 'lldb.process = lldb.target.GetProcess()')", m_dictionary_name.c_str());
355 else
Greg Clayton177bc682012-01-27 00:13:27 +0000356 run_string.Printf ("run_one_line (%s, 'lldb.process = lldb.SBProcess()')", m_dictionary_name.c_str());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000357 PyRun_SimpleString (run_string.GetData());
358 run_string.Clear();
359
Greg Clayton567e7f32011-09-22 04:58:26 +0000360 if (exe_ctx.GetThreadPtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000361 run_string.Printf ("run_one_line (%s, 'lldb.thread = lldb.process.GetSelectedThread ()')",
362 m_dictionary_name.c_str());
363 else
Greg Clayton177bc682012-01-27 00:13:27 +0000364 run_string.Printf ("run_one_line (%s, 'lldb.thread = lldb.SBThread()')", m_dictionary_name.c_str());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000365 PyRun_SimpleString (run_string.GetData());
366 run_string.Clear();
367
Greg Clayton567e7f32011-09-22 04:58:26 +0000368 if (exe_ctx.GetFramePtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000369 run_string.Printf ("run_one_line (%s, 'lldb.frame = lldb.thread.GetSelectedFrame ()')",
370 m_dictionary_name.c_str());
371 else
Greg Clayton177bc682012-01-27 00:13:27 +0000372 run_string.Printf ("run_one_line (%s, 'lldb.frame = lldb.SBFrame()')", m_dictionary_name.c_str());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000373 PyRun_SimpleString (run_string.GetData());
374 run_string.Clear();
375
Caroline Tice0aa2e552011-01-14 00:29:16 +0000376 PyObject *sysmod = PyImport_AddModule ("sys");
377 PyObject *sysdict = PyModule_GetDict (sysmod);
378
379 if ((m_new_sysout != NULL)
380 && (sysmod != NULL)
381 && (sysdict != NULL))
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +0000382 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000383
384 if (PyErr_Occurred())
385 PyErr_Clear ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000386}
387
388
Johnny Chen60dde642010-07-30 22:33:14 +0000389bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000390ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000391{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000392 if (!m_valid_session)
393 return false;
394
Caroline Tice4a461da2011-01-14 21:09:29 +0000395 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
396 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
397 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
398 // method to pass the command string directly down to Python.
399
Enrico Granatafa1f6172011-10-24 17:22:21 +0000400 Locker locker(this,
401 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
402 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000403
404 bool success = false;
405
Greg Clayton63094e02010-06-23 01:19:29 +0000406 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000407 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000408 // Find the correct script interpreter dictionary in the main module.
409 PyObject *main_mod = PyImport_AddModule ("__main__");
410 PyObject *script_interpreter_dict = NULL;
411 if (main_mod != NULL)
412 {
413 PyObject *main_dict = PyModule_GetDict (main_mod);
414 if ((main_dict != NULL)
415 && PyDict_Check (main_dict))
416 {
417 // Go through the main dictionary looking for the correct python script interpreter dictionary
418 PyObject *key, *value;
419 Py_ssize_t pos = 0;
420
421 while (PyDict_Next (main_dict, &pos, &key, &value))
422 {
423 // We have stolen references to the key and value objects in the dictionary; we need to increment
424 // them now so that Python's garbage collector doesn't collect them out from under us.
425 Py_INCREF (key);
426 Py_INCREF (value);
427 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
428 {
429 script_interpreter_dict = value;
430 break;
431 }
432 }
433 }
434
435 if (script_interpreter_dict != NULL)
436 {
437 PyObject *pfunc = NULL;
438 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
439 if (pmod != NULL)
440 {
441 PyObject *pmod_dict = PyModule_GetDict (pmod);
442 if ((pmod_dict != NULL)
443 && PyDict_Check (pmod_dict))
444 {
445 PyObject *key, *value;
446 Py_ssize_t pos = 0;
447
448 while (PyDict_Next (pmod_dict, &pos, &key, &value))
449 {
450 Py_INCREF (key);
451 Py_INCREF (value);
452 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
453 {
454 pfunc = value;
455 break;
456 }
457 }
458
459 PyObject *string_arg = PyString_FromString (command);
460 if (pfunc && string_arg && PyCallable_Check (pfunc))
461 {
462 PyObject *pargs = PyTuple_New (2);
463 if (pargs != NULL)
464 {
465 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
466 PyTuple_SetItem (pargs, 1, string_arg);
467 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
468 Py_DECREF (pargs);
469 if (pvalue != NULL)
470 {
471 Py_DECREF (pvalue);
472 success = true;
473 }
474 else if (PyErr_Occurred ())
475 {
476 PyErr_Print();
477 PyErr_Clear();
478 }
479 }
480 }
481 }
482 }
483 Py_INCREF (script_interpreter_dict);
484 }
485 }
Greg Clayton63094e02010-06-23 01:19:29 +0000486
Caroline Tice4a461da2011-01-14 21:09:29 +0000487 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000488 return true;
489
490 // The one-liner failed. Append the error message.
491 if (result)
492 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
493 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000494 }
Johnny Chen60dde642010-07-30 22:33:14 +0000495
496 if (result)
497 result->AppendError ("empty command passed to python\n");
498 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000499}
500
Chris Lattner24943d22010-06-08 16:52:24 +0000501size_t
502ScriptInterpreterPython::InputReaderCallback
503(
504 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000505 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000506 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000507 const char *bytes,
508 size_t bytes_len
509)
510{
Caroline Tice2ade6112010-11-10 19:18:14 +0000511 lldb::thread_t embedded_interpreter_thread;
512 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
513
Chris Lattner24943d22010-06-08 16:52:24 +0000514 if (baton == NULL)
515 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000516
517 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000518
Caroline Tice0aa2e552011-01-14 00:29:16 +0000519 if (script_interpreter->m_script_lang != eScriptLanguagePython)
520 return 0;
521
Caroline Tice892fadd2011-06-16 16:27:19 +0000522 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
523 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
524
Chris Lattner24943d22010-06-08 16:52:24 +0000525 switch (notification)
526 {
527 case eInputReaderActivate:
528 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000529 if (!batch_mode)
530 {
531 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
532 out_stream->Flush();
533 }
Greg Clayton58928562011-02-09 01:08:52 +0000534
Chris Lattner24943d22010-06-08 16:52:24 +0000535 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000536 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
537 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000538 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000539
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000540 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000541
Caroline Tice202f6b82011-01-17 21:55:19 +0000542 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000543 ScriptInterpreterPython::Locker locker(script_interpreter,
544 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
545 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000546 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000547
Caroline Tice2ade6112010-11-10 19:18:14 +0000548 char error_str[1024];
549 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
550 sizeof(error_str)))
551 {
552 if (log)
553 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
554 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
555 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
556 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
557 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000558 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000559 {
560 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000561 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000562 Error detach_error;
563 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
564 }
565 else
566 {
567 if (log)
568 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
569 reader.SetIsDone (true);
570 }
571 }
572 else
573 {
574 if (log)
575 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
576 reader.SetIsDone (true);
577 }
Chris Lattner24943d22010-06-08 16:52:24 +0000578 }
579 break;
580
581 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000582 // When another input reader is pushed, don't leave the session...
583 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000584 break;
585
586 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000587 {
Greg Claytona1cec242012-01-06 00:47:38 +0000588 // Don't try and acquire the interpreter lock here because code like
589 // this:
590 //
591 // (lldb) script
592 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
593 //
594 // This will cause the process to run. The interpreter lock is taken
595 // by the input reader for the "script" command. If we try and acquire
596 // the lock here, when the process runs it might deactivate this input
597 // reader (if STDIN is hooked up to the inferior process) and
598 // reactivate it when the process stops which will deadlock.
599 //ScriptInterpreterPython::Locker locker(script_interpreter,
600 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
601 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000602 }
Chris Lattner24943d22010-06-08 16:52:24 +0000603 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000604
Caroline Tice4a348082011-05-02 20:41:46 +0000605 case eInputReaderAsynchronousOutputWritten:
606 break;
607
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000608 case eInputReaderInterrupt:
609 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
610 break;
611
612 case eInputReaderEndOfFile:
613 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
614 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000615
616 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000617 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000618 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000619 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000620 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000621 bytes_len);
622 if (bytes && bytes_len)
623 {
624 if ((int) bytes[0] == 4)
625 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
626 else
627 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
628 }
629 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000630 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000631 else
632 {
633 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000634 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000635 bytes,
636 bytes_len);
637 reader.SetIsDone (true);
638 }
639
Chris Lattner24943d22010-06-08 16:52:24 +0000640 break;
641
642 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000643 script_interpreter->LeaveSession ();
644
Chris Lattner24943d22010-06-08 16:52:24 +0000645 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000646 if (log)
647 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000648
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000649 script_interpreter->RestoreTerminalState ();
650
Caroline Tice2ade6112010-11-10 19:18:14 +0000651 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000652 break;
653 }
654
655 return bytes_len;
656}
657
658
659void
Greg Clayton238c0a12010-09-18 01:14:36 +0000660ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000661{
662 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
663
Caroline Tice0aa2e552011-01-14 00:29:16 +0000664 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000665
666 // At the moment, the only time the debugger does not have an input file handle is when this is called
667 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
668 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
669 // do it.
670
Greg Clayton58928562011-02-09 01:08:52 +0000671 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000672 return;
673
Greg Clayton63094e02010-06-23 01:19:29 +0000674 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000675 if (reader_sp)
676 {
677 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
678 this, // baton
679 eInputReaderGranularityLine, // token size, to pass to callback function
680 NULL, // end token
681 NULL, // prompt
682 true)); // echo input
683
684 if (error.Success())
685 {
Greg Clayton63094e02010-06-23 01:19:29 +0000686 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000687 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000688 }
689 }
690}
691
692bool
693ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000694 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000695 void *ret_value)
696{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000697
Enrico Granatafa1f6172011-10-24 17:22:21 +0000698 Locker locker(this,
699 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
700 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000701
Chris Lattner24943d22010-06-08 16:52:24 +0000702 PyObject *py_return = NULL;
703 PyObject *mainmod = PyImport_AddModule ("__main__");
704 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000705 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000706 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000707 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000708 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000709 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000710
711 if (PyDict_Check (globals))
712 {
713 PyObject *key, *value;
714 Py_ssize_t pos = 0;
715
716 int i = 0;
717 while (PyDict_Next (globals, &pos, &key, &value))
718 {
719 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
720 // so that Python's garbage collector doesn't collect them out from under us.
721 Py_INCREF (key);
722 Py_INCREF (value);
723 char *c_str = PyString_AsString (key);
724 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
725 locals = value;
726 ++i;
727 }
728 }
Chris Lattner24943d22010-06-08 16:52:24 +0000729
Caroline Tice0aa2e552011-01-14 00:29:16 +0000730 if (locals == NULL)
731 {
732 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
733 should_decrement_locals = true;
734 }
735
736 if (locals == NULL)
737 {
738 locals = globals;
739 should_decrement_locals = false;
740 }
741
742 py_error = PyErr_Occurred();
743 if (py_error != NULL)
744 PyErr_Clear();
745
Chris Lattner24943d22010-06-08 16:52:24 +0000746 if (in_string != NULL)
747 {
748 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
749 if (py_return == NULL)
750 {
751 py_error = PyErr_Occurred ();
752 if (py_error != NULL)
753 PyErr_Clear ();
754
755 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
756 }
757
Caroline Tice0aa2e552011-01-14 00:29:16 +0000758 if (locals != NULL
759 && should_decrement_locals)
760 Py_DECREF (locals);
761
Chris Lattner24943d22010-06-08 16:52:24 +0000762 if (py_return != NULL)
763 {
764 switch (return_type)
765 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000766 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000767 {
768 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000769 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000770 break;
771 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000772 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000773 {
774 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000775 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000776 break;
777 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000778 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000779 {
780 const char format[2] = "b";
781 success = PyArg_Parse (py_return, format, (bool *) ret_value);
782 break;
783 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000784 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000785 {
786 const char format[2] = "h";
787 success = PyArg_Parse (py_return, format, (short *) ret_value);
788 break;
789 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000790 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000791 {
792 const char format[2] = "H";
793 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
794 break;
795 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000796 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000797 {
798 const char format[2] = "i";
799 success = PyArg_Parse (py_return, format, (int *) ret_value);
800 break;
801 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000802 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000803 {
804 const char format[2] = "I";
805 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
806 break;
807 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000808 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000809 {
810 const char format[2] = "l";
811 success = PyArg_Parse (py_return, format, (long *) ret_value);
812 break;
813 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000814 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000815 {
816 const char format[2] = "k";
817 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
818 break;
819 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000820 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000821 {
822 const char format[2] = "L";
823 success = PyArg_Parse (py_return, format, (long long *) ret_value);
824 break;
825 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000826 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000827 {
828 const char format[2] = "K";
829 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
830 break;
831 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000832 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000833 {
834 const char format[2] = "f";
835 success = PyArg_Parse (py_return, format, (float *) ret_value);
836 break;
837 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000838 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000839 {
840 const char format[2] = "d";
841 success = PyArg_Parse (py_return, format, (double *) ret_value);
842 break;
843 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000844 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000845 {
846 const char format[2] = "c";
847 success = PyArg_Parse (py_return, format, (char *) ret_value);
848 break;
849 }
850 default:
851 {}
852 }
853 Py_DECREF (py_return);
854 if (success)
855 ret_success = true;
856 else
857 ret_success = false;
858 }
859 }
860
861 py_error = PyErr_Occurred();
862 if (py_error != NULL)
863 {
864 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
865 PyErr_Print ();
866 PyErr_Clear();
867 ret_success = false;
868 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000869
Chris Lattner24943d22010-06-08 16:52:24 +0000870 return ret_success;
871}
872
873bool
874ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
875{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000876
877
878 Locker locker(this,
879 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
880 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000881
Chris Lattner24943d22010-06-08 16:52:24 +0000882 bool success = false;
883 PyObject *py_return = NULL;
884 PyObject *mainmod = PyImport_AddModule ("__main__");
885 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000886 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000887 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000888 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000889
Caroline Tice0aa2e552011-01-14 00:29:16 +0000890 if (PyDict_Check (globals))
891 {
892 PyObject *key, *value;
893 Py_ssize_t pos = 0;
894
895 while (PyDict_Next (globals, &pos, &key, &value))
896 {
897 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
898 // so that Python's garbage collector doesn't collect them out from under us.
899 Py_INCREF (key);
900 Py_INCREF (value);
901 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
902 locals = value;
903 }
904 }
905
906 if (locals == NULL)
907 {
908 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
909 should_decrement_locals = true;
910 }
911
912 if (locals == NULL)
913 {
914 locals = globals;
915 should_decrement_locals = false;
916 }
917
918 py_error = PyErr_Occurred();
919 if (py_error != NULL)
920 PyErr_Clear();
921
Chris Lattner24943d22010-06-08 16:52:24 +0000922 if (in_string != NULL)
923 {
924 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
925 if (compiled_node)
926 {
927 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
928 if (compiled_code)
929 {
930 py_return = PyEval_EvalCode (compiled_code, globals, locals);
931 if (py_return != NULL)
932 {
933 success = true;
934 Py_DECREF (py_return);
935 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000936 if (locals && should_decrement_locals)
937 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000938 }
939 }
940 }
941
942 py_error = PyErr_Occurred ();
943 if (py_error != NULL)
944 {
945 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
946 PyErr_Print ();
947 PyErr_Clear();
948 success = false;
949 }
950
951 return success;
952}
953
954static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
955
956size_t
957ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
958(
959 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000960 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000961 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000962 const char *bytes,
963 size_t bytes_len
964)
965{
Caroline Tice892fadd2011-06-16 16:27:19 +0000966 static StringList commands_in_progress;
967
968 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
969 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
970
Chris Lattner24943d22010-06-08 16:52:24 +0000971 switch (notification)
972 {
973 case eInputReaderActivate:
974 {
975 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +0000976 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +0000977 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000978 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000979 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +0000980 out_stream->Printf ("%s", reader.GetPrompt());
981 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +0000982 }
983 }
984 break;
985
986 case eInputReaderDeactivate:
987 break;
988
989 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +0000990 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000991 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000992 out_stream->Printf ("%s", reader.GetPrompt());
993 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +0000994 }
Chris Lattner24943d22010-06-08 16:52:24 +0000995 break;
996
Caroline Tice4a348082011-05-02 20:41:46 +0000997 case eInputReaderAsynchronousOutputWritten:
998 break;
999
Chris Lattner24943d22010-06-08 16:52:24 +00001000 case eInputReaderGotToken:
1001 {
1002 std::string temp_string (bytes, bytes_len);
1003 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001004 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001005 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001006 out_stream->Printf ("%s", reader.GetPrompt());
1007 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001008 }
Chris Lattner24943d22010-06-08 16:52:24 +00001009 }
1010 break;
1011
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001012 case eInputReaderEndOfFile:
1013 case eInputReaderInterrupt:
1014 // Control-c (SIGINT) & control-d both mean finish & exit.
1015 reader.SetIsDone(true);
1016
1017 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1018 if (notification == eInputReaderInterrupt)
1019 commands_in_progress.Clear();
1020
1021 // Fall through here...
1022
Chris Lattner24943d22010-06-08 16:52:24 +00001023 case eInputReaderDone:
1024 {
1025 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1026 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1027 data_ap->user_source.AppendList (commands_in_progress);
1028 if (data_ap.get())
1029 {
Greg Clayton63094e02010-06-23 01:19:29 +00001030 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001031 if (interpreter)
1032 {
1033 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1034 data_ap->script_source))
1035 {
1036 if (data_ap->script_source.GetSize() == 1)
1037 {
1038 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1039 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1040 }
1041 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001042 else if (!batch_mode)
1043 {
1044 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1045 out_stream->Flush();
1046 }
Chris Lattner24943d22010-06-08 16:52:24 +00001047 }
1048 else
1049 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001050 if (!batch_mode)
1051 {
1052 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1053 out_stream->Flush();
1054 }
Chris Lattner24943d22010-06-08 16:52:24 +00001055 }
1056 }
1057 }
1058 break;
1059
1060 }
1061
1062 return bytes_len;
1063}
1064
1065void
Greg Clayton238c0a12010-09-18 01:14:36 +00001066ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001067 CommandReturnObject &result)
1068{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001069 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1070
Greg Clayton63094e02010-06-23 01:19:29 +00001071 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001072
1073 if (reader_sp)
1074 {
1075 Error err = reader_sp->Initialize (
1076 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1077 bp_options, // baton
1078 eInputReaderGranularityLine, // token size, for feeding data to callback function
1079 "DONE", // end token
1080 "> ", // prompt
1081 true); // echo input
1082
1083 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001084 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001085 else
1086 {
1087 result.AppendError (err.AsCString());
1088 result.SetStatus (eReturnStatusFailed);
1089 }
1090 }
1091 else
1092 {
1093 result.AppendError("out of memory");
1094 result.SetStatus (eReturnStatusFailed);
1095 }
1096}
1097
Johnny Chen3e0571b2010-09-11 00:23:59 +00001098// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001099void
Greg Clayton238c0a12010-09-18 01:14:36 +00001100ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001101 const char *oneliner)
1102{
1103 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1104
1105 // It's necessary to set both user_source and script_source to the oneliner.
1106 // The former is used to generate callback description (as in breakpoint command list)
1107 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001108
Johnny Chend1c2dca2010-09-10 18:21:10 +00001109 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001110
Caroline Tice5136f942010-09-27 21:35:15 +00001111 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1112 {
1113 if (data_ap->script_source.GetSize() == 1)
1114 {
1115 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1116 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1117 }
1118 }
1119
Johnny Chend1c2dca2010-09-10 18:21:10 +00001120 return;
1121}
1122
Chris Lattner24943d22010-06-08 16:52:24 +00001123bool
1124ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1125{
1126 // Convert StringList to one long, newline delimited, const char *.
1127 std::string function_def_string;
1128
1129 int num_lines = function_def.GetSize();
1130
1131 for (int i = 0; i < num_lines; ++i)
1132 {
1133 function_def_string.append (function_def.GetStringAtIndex(i));
1134 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1135 function_def_string.append ("\n");
1136
1137 }
1138
1139 return ExecuteMultipleLines (function_def_string.c_str());
1140}
1141
Enrico Granataf7a9b142011-07-15 02:26:42 +00001142// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1143// use this code to generate their functions
1144bool
1145ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1146{
1147 int num_lines = input.GetSize ();
1148 if (num_lines == 0)
1149 return false;
1150 StreamString sstr;
1151 StringList auto_generated_function;
1152 auto_generated_function.AppendString (signature.c_str());
1153 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1154 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1155 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1156 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1157 // global dictionary.
1158
1159 // Wrap everything up inside the function, increasing the indentation.
1160
1161 for (int i = 0; i < num_lines; ++i)
1162 {
1163 sstr.Clear ();
1164 sstr.Printf (" %s", input.GetStringAtIndex (i));
1165 auto_generated_function.AppendString (sstr.GetData());
1166 }
1167 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1168 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1169 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1170 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1171
1172 // Verify that the results are valid Python.
1173
1174 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1175 return false;
1176
1177 return true;
1178
1179}
1180
1181// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1182// given to generated functions, of course)
1183bool
1184ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output)
1185{
1186 static int num_created_functions = 0;
1187 user_input.RemoveBlankLines ();
1188 int num_lines = user_input.GetSize ();
1189 StreamString sstr;
1190
1191 // Check to see if we have any data; if not, just return.
1192 if (user_input.GetSize() == 0)
1193 return false;
1194
1195 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1196 // ValueObject as parameter to the function.
1197
1198 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1199 ++num_created_functions;
1200 std::string auto_generated_function_name = sstr.GetData();
1201
1202 sstr.Clear();
1203 StringList auto_generated_function;
1204
1205 // Create the function name & definition string.
1206
1207 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1208 auto_generated_function.AppendString (sstr.GetData());
1209
1210 // Pre-pend code for setting up the session dictionary.
1211
1212 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1213 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1214 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1215 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1216 // global dictionary.
1217
1218 // Wrap everything up inside the function, increasing the indentation.
1219
1220 for (int i = 0; i < num_lines; ++i)
1221 {
1222 sstr.Clear ();
1223 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1224 auto_generated_function.AppendString (sstr.GetData());
1225 }
1226
1227 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1228 // got written to the values in the global dictionary, not the session dictionary).
1229
1230 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1231 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1232 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1233 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1234
1235 // Verify that the results are valid Python.
1236
1237 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1238 return false;
1239
1240 // Store the name of the auto-generated function to be called.
1241
1242 output.AppendString (auto_generated_function_name.c_str());
1243 return true;
1244}
1245
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001246bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001247ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, StringList &output)
1248{
1249 static int num_created_functions = 0;
1250 user_input.RemoveBlankLines ();
1251 int num_lines = user_input.GetSize ();
1252 StreamString sstr;
1253
1254 // Check to see if we have any data; if not, just return.
1255 if (user_input.GetSize() == 0)
1256 return false;
1257
1258 // 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 +00001259 // required data as parameters to the function.
Enrico Granatac2a28252011-08-16 16:49:25 +00001260
1261 sstr.Printf ("lldb_autogen_python_cmd_alias_func_%d", num_created_functions);
1262 ++num_created_functions;
1263 std::string auto_generated_function_name = sstr.GetData();
1264
1265 sstr.Clear();
1266 StringList auto_generated_function;
1267
1268 // Create the function name & definition string.
1269
Enrico Granata271568f2011-09-09 01:41:30 +00001270 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001271 auto_generated_function.AppendString (sstr.GetData());
1272
1273 // Pre-pend code for setting up the session dictionary.
1274
1275 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1276 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1277 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1278 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1279 // global dictionary.
1280
1281 // Wrap everything up inside the function, increasing the indentation.
1282
1283 for (int i = 0; i < num_lines; ++i)
1284 {
1285 sstr.Clear ();
1286 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1287 auto_generated_function.AppendString (sstr.GetData());
1288 }
1289
1290 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1291 // got written to the values in the global dictionary, not the session dictionary).
1292
1293 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1294 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1295 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1296 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1297
1298 // Verify that the results are valid Python.
1299
1300 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1301 return false;
1302
1303 // Store the name of the auto-generated function to be called.
1304
1305 output.AppendString (auto_generated_function_name.c_str());
1306 return true;
1307}
1308
1309
1310bool
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001311ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output)
1312{
1313 static int num_created_classes = 0;
1314 user_input.RemoveBlankLines ();
1315 int num_lines = user_input.GetSize ();
1316 StreamString sstr;
1317
1318 // Check to see if we have any data; if not, just return.
1319 if (user_input.GetSize() == 0)
1320 return false;
1321
1322 // Wrap all user input into a Python class
1323
1324 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1325 ++num_created_classes;
1326 std::string auto_generated_class_name = sstr.GetData();
1327
1328 sstr.Clear();
1329 StringList auto_generated_class;
1330
1331 // Create the function name & definition string.
1332
1333 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1334 auto_generated_class.AppendString (sstr.GetData());
1335
1336 // Wrap everything up inside the class, increasing the indentation.
1337
1338 for (int i = 0; i < num_lines; ++i)
1339 {
1340 sstr.Clear ();
1341 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1342 auto_generated_class.AppendString (sstr.GetData());
1343 }
1344
1345
1346 // Verify that the results are valid Python.
1347 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1348 // (TODO: rename that method to ExportDefinitionToInterpreter)
1349 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1350 return false;
1351
1352 // Store the name of the auto-generated class
1353
1354 output.AppendString (auto_generated_class_name.c_str());
1355 return true;
1356}
1357
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001358void*
1359ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1360 lldb::ValueObjectSP valobj)
1361{
1362 if (class_name.empty())
1363 return NULL;
1364
1365 if (!valobj.get())
1366 return NULL;
1367
Enrico Granata979e20d2011-07-29 19:53:35 +00001368 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001369
1370 if (!target)
1371 return NULL;
1372
1373 Debugger &debugger = target->GetDebugger();
1374 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1375 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1376
1377 if (!script_interpreter)
1378 return NULL;
1379
1380 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001381
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001382 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001383 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001384 ret_val = g_swig_synthetic_script (class_name,
1385 python_interpreter->m_dictionary_name.c_str(),
1386 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001387 }
1388
1389 return ret_val;
1390}
1391
Enrico Granataf7a9b142011-07-15 02:26:42 +00001392bool
1393ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output)
1394{
1395 StringList input(oneliner);
1396 return GenerateTypeScriptFunction(input, output);
1397}
1398
Chris Lattner24943d22010-06-08 16:52:24 +00001399bool
1400ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1401{
1402 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001403 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001404 int num_lines = user_input.GetSize ();
1405 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001406
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001407 // Check to see if we have any data; if not, just return.
1408 if (user_input.GetSize() == 0)
1409 return false;
1410
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001411 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1412 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001413
Caroline Ticeb447e842010-09-21 19:25:28 +00001414
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001415 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1416 ++num_created_functions;
1417 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001418
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001419 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001420 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001421
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001422 // Create the function name & definition string.
1423
Caroline Tice0aa2e552011-01-14 00:29:16 +00001424 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001425 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001426
1427 // Pre-pend code for setting up the session dictionary.
1428
1429 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1430 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1431 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1432 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1433 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001434
1435 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001436
1437 for (int i = 0; i < num_lines; ++i)
1438 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001439 sstr.Clear ();
1440 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1441 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001442 }
Chris Lattner24943d22010-06-08 16:52:24 +00001443
Caroline Tice0aa2e552011-01-14 00:29:16 +00001444 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1445 // got written to the values in the global dictionary, not the session dictionary).
1446
1447 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1448 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1449 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1450 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1451
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001452 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001453
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001454 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001455 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001456 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001457 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001458
1459 // Store the name of the auto-generated function to be called.
1460
1461 callback_data.AppendString (auto_generated_function_name.c_str());
1462 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001463}
1464
Enrico Granataf7a9b142011-07-15 02:26:42 +00001465std::string
1466ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1467 lldb::ValueObjectSP valobj)
1468{
1469
1470 if (!python_function_name || !(*python_function_name))
1471 return "<no function>";
1472
1473 if (!valobj.get())
1474 return "<no object>";
1475
Enrico Granata979e20d2011-07-29 19:53:35 +00001476 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001477
1478 if (!target)
1479 return "<no target>";
1480
1481 Debugger &debugger = target->GetDebugger();
1482 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1483 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1484
1485 if (!script_interpreter)
1486 return "<no python>";
1487
1488 std::string ret_val;
1489
1490 if (python_function_name
1491 && *python_function_name)
1492 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001493 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001494 Locker py_lock(python_interpreter);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001495 ret_val = g_swig_typescript_callback (python_function_name,
1496 python_interpreter->m_dictionary_name.c_str(),
1497 valobj);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001498 }
1499 }
1500 else
1501 return "<no function name>";
1502
1503 return ret_val;
1504
1505}
1506
Greg Clayton5144f382010-10-07 17:14:24 +00001507bool
1508ScriptInterpreterPython::BreakpointCallbackFunction
1509(
1510 void *baton,
1511 StoppointCallbackContext *context,
1512 user_id_t break_id,
1513 user_id_t break_loc_id
1514)
1515{
1516 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1517 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001518
1519 if (!context)
1520 return true;
1521
Greg Clayton567e7f32011-09-22 04:58:26 +00001522 Target *target = context->exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001523
1524 if (!target)
1525 return true;
1526
1527 Debugger &debugger = target->GetDebugger();
1528 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1529 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1530
1531 if (!script_interpreter)
1532 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001533
1534 if (python_function_name != NULL
1535 && python_function_name[0] != '\0')
1536 {
Greg Clayton567e7f32011-09-22 04:58:26 +00001537 const StackFrameSP stop_frame_sp (context->exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001538 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001539 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001540 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001541 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1542
1543 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001544 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001545 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001546 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001547 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001548 ret_val = g_swig_breakpoint_callback (python_function_name,
1549 python_interpreter->m_dictionary_name.c_str(),
1550 stop_frame_sp,
1551 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001552 }
1553 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001554 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001555 }
Greg Clayton5144f382010-10-07 17:14:24 +00001556 }
1557 // We currently always true so we stop in case anything goes wrong when
1558 // trying to call the script function
1559 return true;
1560}
Caroline Tice2ade6112010-11-10 19:18:14 +00001561
1562lldb::thread_result_t
1563ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1564{
1565 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1566
1567 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1568
1569 if (log)
1570 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1571
1572 char error_str[1024];
1573 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001574
Enrico Granatafa1f6172011-10-24 17:22:21 +00001575 Locker locker(script_interpreter,
1576 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1577 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1578
1579 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001580 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001581 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001582
Caroline Tice0aa2e552011-01-14 00:29:16 +00001583 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1584 PyRun_SimpleString (run_string.GetData());
1585 run_string.Clear ();
1586
1587 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1588 PyRun_SimpleString (run_string.GetData());
1589 run_string.Clear ();
1590
1591 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1592 PyRun_SimpleString (run_string.GetData());
1593 run_string.Clear ();
1594
1595 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1596 pty_slave_name);
1597 PyRun_SimpleString (run_string.GetData());
1598 run_string.Clear ();
1599
Johnny Chen8054ba32011-03-11 00:28:50 +00001600 // The following call drops into the embedded interpreter loop and stays there until the
1601 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001602
Caroline Ticece207c12011-03-11 00:21:55 +00001603 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001604 // 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 +00001605 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1606
1607 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1608 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1609 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1610 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1611 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1612 // hang (it's happened before).
1613
Caroline Tice9d352ce2011-03-07 23:24:28 +00001614 Py_BEGIN_ALLOW_THREADS
1615 PyGILState_STATE gstate = PyGILState_Ensure();
1616
Caroline Tice0aa2e552011-01-14 00:29:16 +00001617 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1618 PyRun_SimpleString (run_string.GetData());
1619 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001620
Caroline Tice9d352ce2011-03-07 23:24:28 +00001621 PyGILState_Release (gstate);
1622 Py_END_ALLOW_THREADS
1623
Caroline Tice0aa2e552011-01-14 00:29:16 +00001624 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1625 PyRun_SimpleString (run_string.GetData());
1626 run_string.Clear();
1627
1628 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1629 PyRun_SimpleString (run_string.GetData());
1630 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001631
Caroline Tice2ade6112010-11-10 19:18:14 +00001632 }
1633
1634 if (script_interpreter->m_embedded_thread_input_reader_sp)
1635 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1636
1637 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001638
Caroline Tice2ade6112010-11-10 19:18:14 +00001639 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,
Enrico Granata6010ace2011-11-07 22:57:04 +00001743 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00001744 lldb_private::Error& error)
1745{
1746 if (!pathname || !pathname[0])
1747 {
1748 error.SetErrorString("invalid pathname");
1749 return false;
1750 }
1751
1752 if (!g_swig_call_module_init)
1753 {
1754 error.SetErrorString("internal helper function missing");
1755 return false;
1756 }
1757
Enrico Granata59df36f2011-10-17 21:45:27 +00001758 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
Enrico Granatafa1f6172011-10-24 17:22:21 +00001759
Enrico Granata59df36f2011-10-17 21:45:27 +00001760 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001761 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00001762
1763 FileSpec target_file(pathname, true);
1764
1765 // TODO: would we want to reject any other value?
1766 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1767 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1768 {
1769 error.SetErrorString("invalid pathname");
1770 return false;
1771 }
1772
1773 const char* directory = target_file.GetDirectory().GetCString();
1774 std::string basename(target_file.GetFilename().GetCString());
1775
1776 // now make sure that Python has "directory" in the search path
1777 StreamString command_stream;
1778 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1779 directory,
1780 directory);
Enrico Granatafa1f6172011-10-24 17:22:21 +00001781 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData());
Enrico Granata59df36f2011-10-17 21:45:27 +00001782 if (!syspath_retval)
1783 {
1784 error.SetErrorString("Python sys.path handling failed");
1785 return false;
1786 }
1787
1788 // strip .py or .pyc extension
1789 ConstString extension = target_file.GetFileNameExtension();
1790 if (::strcmp(extension.GetCString(), "py") == 0)
1791 basename.resize(basename.length()-3);
1792 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1793 basename.resize(basename.length()-4);
1794
1795 // check if the module is already import-ed
1796 command_stream.Clear();
1797 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1798 int refcount = 0;
1799 // this call will fail if the module does not exist (because the parameter to it is not a string
1800 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00001801 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
1802 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0);
1803 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00001804 {
1805 error.SetErrorString("module already imported");
1806 return false;
1807 }
1808
1809 // now actually do the import
1810 command_stream.Clear();
1811 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafa1f6172011-10-24 17:22:21 +00001812 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL);
Enrico Granata59df36f2011-10-17 21:45:27 +00001813 if (!import_retval)
1814 {
1815 error.SetErrorString("Python import statement failed");
1816 return false;
1817 }
1818
1819 // call __lldb_module_init(debugger,dict)
1820 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001821 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001822 debugger_sp))
1823 {
1824 error.SetErrorString("calling __lldb_module_init failed");
1825 return false;
1826 }
1827 return true;
1828 }
1829}
1830
Enrico Granata6010ace2011-11-07 22:57:04 +00001831ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
1832 ScriptedCommandSynchronicity synchro) :
1833 m_debugger_sp(debugger_sp),
1834 m_synch_wanted(synchro),
1835 m_old_asynch(debugger_sp->GetAsyncExecution())
1836{
1837 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
1838 m_debugger_sp->SetAsyncExecution(false);
1839 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
1840 m_debugger_sp->SetAsyncExecution(true);
1841}
1842
1843ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
1844{
1845 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
1846 m_debugger_sp->SetAsyncExecution(m_old_asynch);
1847}
1848
Enrico Granata59df36f2011-10-17 21:45:27 +00001849bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001850ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1851 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00001852 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001853 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001854 Error& error)
1855{
1856 if (!impl_function)
1857 {
1858 error.SetErrorString("no function to execute");
1859 return false;
1860 }
1861
1862 if (!g_swig_call_command)
1863 {
1864 error.SetErrorString("no helper function to run scripted commands");
1865 return false;
1866 }
1867
Enrico Granatac2a28252011-08-16 16:49:25 +00001868 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
Enrico Granata6010ace2011-11-07 22:57:04 +00001869
1870 if (!debugger_sp.get())
1871 {
1872 error.SetErrorString("invalid Debugger pointer");
1873 return false;
1874 }
Enrico Granatac2a28252011-08-16 16:49:25 +00001875
1876 bool ret_val;
1877
1878 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00001879
Enrico Granatac2a28252011-08-16 16:49:25 +00001880 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001881 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00001882 SynchronicityHandler synch_handler(debugger_sp,
1883 synchronicity);
1884
Enrico Granatac2a28252011-08-16 16:49:25 +00001885 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001886 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00001887 debugger_sp,
1888 args,
1889 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001890 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001891 }
Enrico Granata6010ace2011-11-07 22:57:04 +00001892
Enrico Granatac2a28252011-08-16 16:49:25 +00001893 if (!ret_val)
1894 error.SetErrorString(err_msg.c_str());
1895 else
1896 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00001897
Enrico Granatac2a28252011-08-16 16:49:25 +00001898 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00001899}
1900
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001901// in Python, a special attribute __doc__ contains the docstring
1902// for an object (function, method, class, ...) if any is defined
1903// Otherwise, the attribute's value is None
1904std::string
1905ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1906{
1907 std::string command(item);
1908 command += ".__doc__";
1909
1910 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1911
1912 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001913 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001914 &result_ptr) && result_ptr)
1915 {
1916 return std::string(result_ptr);
1917 }
1918 else
1919 return std::string("");
1920}
Caroline Tice2ade6112010-11-10 19:18:14 +00001921
Caroline Tice0aa2e552011-01-14 00:29:16 +00001922void
Greg Claytone86cbb92011-03-22 01:14:58 +00001923ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00001924 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001925 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
1926 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
1927 SWIGPythonCalculateNumChildren python_swig_calc_children,
1928 SWIGPythonGetChildAtIndex python_swig_get_child_index,
1929 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
Enrico Granata979e20d2011-07-29 19:53:35 +00001930 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue,
Enrico Granatac2a28252011-08-16 16:49:25 +00001931 SWIGPythonUpdateSynthProviderInstance python_swig_update_provider,
Enrico Granata59df36f2011-10-17 21:45:27 +00001932 SWIGPythonCallCommand python_swig_call_command,
1933 SWIGPythonCallModuleInit python_swig_call_mod_init)
Greg Claytone86cbb92011-03-22 01:14:58 +00001934{
1935 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001936 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1937 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001938 g_swig_synthetic_script = python_swig_synthetic_script;
1939 g_swig_calc_children = python_swig_calc_children;
1940 g_swig_get_child_index = python_swig_get_child_index;
1941 g_swig_get_index_child = python_swig_get_index_child;
1942 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Enrico Granata979e20d2011-07-29 19:53:35 +00001943 g_swig_update_provider = python_swig_update_provider;
Enrico Granatac2a28252011-08-16 16:49:25 +00001944 g_swig_call_command = python_swig_call_command;
Enrico Granata59df36f2011-10-17 21:45:27 +00001945 g_swig_call_module_init = python_swig_call_mod_init;
Greg Claytone86cbb92011-03-22 01:14:58 +00001946}
1947
1948void
1949ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001950{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001951 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1952
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001953 // Python will muck with STDIN terminal state, so save off any current TTY
1954 // settings so we can restore them.
1955 TerminalState stdin_tty_state;
1956 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001957
Caroline Tice9d352ce2011-03-07 23:24:28 +00001958 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001959 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001960
Greg Claytone86cbb92011-03-22 01:14:58 +00001961 // Initialize SWIG after setting up python
1962 assert (g_swig_init_callback != NULL);
1963 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001964
1965 // Update the path python uses to search for modules to include the current directory.
1966
Caroline Ticed4d92832011-06-13 21:33:00 +00001967 PyRun_SimpleString ("import sys");
1968 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001969
1970 // Find the module that owns this code and use that path we get to
1971 // set the sys.path appropriately.
1972
1973 FileSpec file_spec;
1974 char python_dir_path[PATH_MAX];
1975 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1976 {
1977 std::string python_path("sys.path.insert(0,\"");
1978 size_t orig_len = python_path.length();
1979 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1980 {
1981 python_path.append (python_dir_path);
1982 python_path.append ("\")");
1983 PyRun_SimpleString (python_path.c_str());
1984 python_path.resize (orig_len);
1985 }
1986
1987 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1988 {
1989 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1990 {
1991 python_path.append (python_dir_path);
1992 python_path.append ("\")");
1993 PyRun_SimpleString (python_path.c_str());
1994 python_path.resize (orig_len);
1995 }
1996 }
1997 }
1998
Jim Ingham4dfa5112011-08-22 19:10:09 +00001999 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00002000
Caroline Ticed4d92832011-06-13 21:33:00 +00002001 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00002002
Caroline Ticed4d92832011-06-13 21:33:00 +00002003 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
2004 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00002005 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00002006
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002007 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002008}
2009
Greg Claytone86cbb92011-03-22 01:14:58 +00002010//void
2011//ScriptInterpreterPython::Terminate ()
2012//{
2013// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
2014// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
2015// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
2016// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
2017// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
2018// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
2019// // within Py_Finalize, which results in a seg fault.
2020// //
2021// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
2022// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
2023// // process exits).
2024// //
2025//// Py_Finalize ();
2026//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00002027
2028#endif // #ifdef LLDB_DISABLE_PYTHON