blob: 246e3bd7b9a55f69eb844d85b9460a3b347099a7 [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
Enrico Granata1328b142012-02-29 03:28:49 +000057// these are the Pythonic implementations of the required callbacks
58// these are scripting-language specific, which is why they belong here
59// we still need to use function pointers to them instead of relying
60// on linkage-time resolution because the SWIG stuff and this file
61// get built at different times
62extern "C" bool
63LLDBSwigPythonBreakpointCallbackFunction
64(
65 const char *python_function_name,
66 const char *session_dictionary_name,
67 const lldb::StackFrameSP& sb_frame,
68 const lldb::BreakpointLocationSP& sb_bp_loc
69 );
70
71extern "C" bool
72LLDBSwigPythonCallTypeScript
73(
74 const char *python_function_name,
75 void *session_dictionary,
76 const lldb::ValueObjectSP& valobj_sp,
77 void** pyfunct_wrapper,
78 std::string& retval
79 );
80
81extern "C" void*
82LLDBSwigPythonCreateSyntheticProvider
83(
84 const std::string python_class_name,
85 const char *session_dictionary_name,
86 const lldb::ValueObjectSP& valobj_sp
87 );
88
89
90extern "C" uint32_t LLDBSwigPython_CalculateNumChildren (void *implementor);
91extern "C" void* LLDBSwigPython_GetChildAtIndex (void *implementor, uint32_t idx);
92extern "C" int LLDBSwigPython_GetIndexOfChildWithName (void *implementor, const char* child_name);
93extern "C" void* LLDBSWIGPython_CastPyObjectToSBValue (void* data);
94extern "C" void LLDBSwigPython_UpdateSynthProviderInstance (void* implementor);
95
96extern "C" bool LLDBSwigPythonCallCommand
97(
98 const char *python_function_name,
99 const char *session_dictionary_name,
100 lldb::DebuggerSP& debugger,
101 const char* args,
102 std::string& err_msg,
103 lldb_private::CommandReturnObject& cmd_retobj
104 );
105
106extern "C" bool LLDBSwigPythonCallModuleInit
107(
108 const std::string python_module_name,
109 const char *session_dictionary_name,
110 lldb::DebuggerSP& debugger
111 );
112
Chris Lattner24943d22010-06-08 16:52:24 +0000113static int
114_check_and_flush (FILE *stream)
115{
116 int prev_fail = ferror (stream);
117 return fflush (stream) || prev_fail ? EOF : 0;
118}
119
Caroline Tice202f6b82011-01-17 21:55:19 +0000120static Predicate<lldb::tid_t> &
121PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +0000122{
Caroline Tice202f6b82011-01-17 21:55:19 +0000123 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
124 return g_interpreter_is_running;
125}
126
Enrico Granatafa1f6172011-10-24 17:22:21 +0000127bool
128ScriptInterpreterPython::Locker::CurrentThreadHasPythonLock ()
Caroline Tice202f6b82011-01-17 21:55:19 +0000129{
130 TimeValue timeout;
131
132 timeout = TimeValue::Now(); // Don't wait any time.
133
134 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
135}
136
Enrico Granatafa1f6172011-10-24 17:22:21 +0000137bool
138ScriptInterpreterPython::Locker::TryGetPythonLock (uint32_t seconds_to_wait)
Caroline Tice202f6b82011-01-17 21:55:19 +0000139{
140
141 TimeValue timeout;
142
143 if (seconds_to_wait != UINT32_MAX)
144 {
145 timeout = TimeValue::Now();
146 timeout.OffsetWithSeconds (seconds_to_wait);
147 }
148
149 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
150 Host::GetCurrentThreadID(), &timeout, NULL);
151}
152
Enrico Granatafa1f6172011-10-24 17:22:21 +0000153void
154ScriptInterpreterPython::Locker::ReleasePythonLock ()
Caroline Tice202f6b82011-01-17 21:55:19 +0000155{
156 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000157}
158
Enrico Granatafa1f6172011-10-24 17:22:21 +0000159ScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *py_interpreter,
160 uint16_t on_entry,
161 uint16_t on_leave,
162 FILE* wait_msg_handle) :
163 m_need_session( (on_leave & TearDownSession) == TearDownSession ),
164 m_release_lock ( false ), // decide in constructor body
165 m_python_interpreter(py_interpreter),
166 m_tmp_fh(wait_msg_handle)
Enrico Granata91544802011-09-06 19:20:51 +0000167{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000168 if (m_python_interpreter && !m_tmp_fh)
169 m_tmp_fh = (m_python_interpreter->m_dbg_stdout ? m_python_interpreter->m_dbg_stdout : stdout);
170
171 if ( (on_entry & AcquireLock) == AcquireLock )
172 {
173 if (CurrentThreadHasPythonLock())
174 {
175 if ( (on_leave & FreeLock) == FreeLock )
176 m_release_lock = true;
177 }
178 else
179 {
180 DoAcquireLock();
181 if ( (on_leave & FreeLock) == FreeLock )
182 m_release_lock = true;
183 if ( (on_leave & FreeAcquiredLock) == FreeAcquiredLock )
184 m_release_lock = true;
185 }
186 }
187 if ( (on_entry & InitSession) == InitSession )
188 DoInitSession();
189}
190
191bool
192ScriptInterpreterPython::Locker::DoAcquireLock()
193{
Enrico Granata91544802011-09-06 19:20:51 +0000194 if (!CurrentThreadHasPythonLock())
195 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000196 while (!TryGetPythonLock (1))
197 if (m_tmp_fh)
198 fprintf (m_tmp_fh,
Enrico Granata91544802011-09-06 19:20:51 +0000199 "Python interpreter locked on another thread; waiting to acquire lock...\n");
Enrico Granata91544802011-09-06 19:20:51 +0000200 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000201 return true;
202}
203
204bool
205ScriptInterpreterPython::Locker::DoInitSession()
206{
207 if (!m_python_interpreter)
208 return false;
209 m_python_interpreter->EnterSession ();
210 return true;
211}
212
213bool
214ScriptInterpreterPython::Locker::DoFreeLock()
215{
216 ReleasePythonLock ();
217 return true;
218}
219
220bool
221ScriptInterpreterPython::Locker::DoTearDownSession()
222{
223 if (!m_python_interpreter)
224 return false;
225 m_python_interpreter->LeaveSession ();
226 return true;
Enrico Granata91544802011-09-06 19:20:51 +0000227}
228
229ScriptInterpreterPython::Locker::~Locker()
230{
231 if (m_need_session)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000232 DoTearDownSession();
Enrico Granata91544802011-09-06 19:20:51 +0000233 if (m_release_lock)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000234 DoFreeLock();
Enrico Granata91544802011-09-06 19:20:51 +0000235}
236
Greg Clayton63094e02010-06-23 01:19:29 +0000237ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000238 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000239 m_embedded_python_pty (),
240 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +0000241 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000242 m_new_sysout (NULL),
243 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000244 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000245 m_session_is_active (false),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000246 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000247{
248
Greg Clayton7c330d62011-01-27 01:01:10 +0000249 static int g_initialized = false;
250
251 if (!g_initialized)
252 {
253 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000254 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000255 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000256
257 Locker locker(this,
258 ScriptInterpreterPython::Locker::AcquireLock,
259 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Greg Clayton7c330d62011-01-27 01:01:10 +0000260
Caroline Tice0aa2e552011-01-14 00:29:16 +0000261 m_dictionary_name.append("_dict");
262 StreamString run_string;
263 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
264 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000265
Caroline Tice0aa2e552011-01-14 00:29:16 +0000266 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000267
268 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
269 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
270 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
271 // call to Debugger::Terminate is made, the ref-count has the correct value.
272 //
273 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
274 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000275
Caroline Tice0aa2e552011-01-14 00:29:16 +0000276 int old_count = Debugger::TestDebuggerRefCount();
Greg Claytonb302dff2012-02-01 08:09:32 +0000277
Chris Lattner24943d22010-06-08 16:52:24 +0000278
Greg Claytonb302dff2012-02-01 08:09:32 +0000279 run_string.Printf ("run_one_line (%s, 'import copy, os, re, sys, uuid, lldb, gnu_libstdcpp, objc')", m_dictionary_name.c_str());
Caroline Tice0aa2e552011-01-14 00:29:16 +0000280 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000281
Enrico Granata8f84cfb2012-02-23 23:10:03 +0000282 // WARNING: temporary code that loads Cocoa formatters - this should be done on a per-platform basis rather than loading the whole set
283 // and letting the individual formatter classes exploit APIs to check whether they can/cannot do their task
284 run_string.Clear();
Enrico Granata1328b142012-02-29 03:28:49 +0000285 run_string.Printf ("run_one_line (%s, 'import CFString, CFArray, CFDictionary, NSData, NSMachPort, NSSet, NSNotification, NSException, CFBag, CFBinaryHeap, NSURL, NSBundle, NSNumber, NSDate')", m_dictionary_name.c_str());
Enrico Granata8f84cfb2012-02-23 23:10:03 +0000286 PyRun_SimpleString (run_string.GetData());
Greg Claytonb302dff2012-02-01 08:09:32 +0000287
Caroline Tice0aa2e552011-01-14 00:29:16 +0000288 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000289
Caroline Tice0aa2e552011-01-14 00:29:16 +0000290 if (new_count > old_count)
291 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000292
Caroline Tice0aa2e552011-01-14 00:29:16 +0000293 run_string.Clear();
Greg Clayton444e35b2011-10-19 18:09:39 +0000294 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000295 interpreter.GetDebugger().GetID());
296 PyRun_SimpleString (run_string.GetData());
297
298 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000299 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000300 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000301 }
Chris Lattner24943d22010-06-08 16:52:24 +0000302}
303
304ScriptInterpreterPython::~ScriptInterpreterPython ()
305{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000306 Debugger &debugger = GetCommandInterpreter().GetDebugger();
307
308 if (m_embedded_thread_input_reader_sp.get() != NULL)
309 {
310 m_embedded_thread_input_reader_sp->SetIsDone (true);
311 m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000312 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
313 m_embedded_thread_input_reader_sp.reset();
314 debugger.PopInputReader (reader_sp);
315 }
316
317 if (m_new_sysout)
318 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000319 Locker locker(this,
320 ScriptInterpreterPython::Locker::AcquireLock,
321 ScriptInterpreterPython::Locker::FreeLock);
322 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000323 }
Chris Lattner24943d22010-06-08 16:52:24 +0000324}
325
Caroline Tice0aa2e552011-01-14 00:29:16 +0000326void
327ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
328{
329 if (fh == NULL)
330 return;
331
332 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000333
Enrico Granatafa1f6172011-10-24 17:22:21 +0000334 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +0000335
336 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000337}
338
339void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000340ScriptInterpreterPython::SaveTerminalState (int fd)
341{
342 // Python mucks with the terminal state of STDIN. If we can possibly avoid
343 // this by setting the file handles up correctly prior to entering the
344 // interpreter we should. For now we save and restore the terminal state
345 // on the input file handle.
346 m_terminal_state.Save (fd, false);
347}
348
349void
350ScriptInterpreterPython::RestoreTerminalState ()
351{
352 // Python mucks with the terminal state of STDIN. If we can possibly avoid
353 // this by setting the file handles up correctly prior to entering the
354 // interpreter we should. For now we save and restore the terminal state
355 // on the input file handle.
356 m_terminal_state.Restore();
357}
358
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000359void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000360ScriptInterpreterPython::LeaveSession ()
361{
Johnny Chen41641f92012-02-29 01:52:13 +0000362 PyObject *sysmod = PyImport_AddModule ("sys");
363 PyObject *sysdict = PyModule_GetDict (sysmod);
364
365 if (m_new_sysout && sysmod && sysdict)
366 {
367 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_old_sysout);
368 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_old_sysout);
369 }
370
Caroline Tice0aa2e552011-01-14 00:29:16 +0000371 m_session_is_active = false;
372}
373
374void
375ScriptInterpreterPython::EnterSession ()
376{
377 // If we have already entered the session, without having officially 'left' it, then there is no need to
378 // 'enter' it again.
379
380 if (m_session_is_active)
381 return;
382
383 m_session_is_active = true;
384
Caroline Tice202f6b82011-01-17 21:55:19 +0000385 StreamString run_string;
386
Greg Clayton2fecc452012-01-28 02:11:02 +0000387 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %llu", m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
388 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)", GetCommandInterpreter().GetDebugger().GetID());
389 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
390 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
391 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
392 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
393 // Make sure STDIN is closed since when we run this as an embedded
394 // interpreter we don't want someone to call "line = sys.stdin.readline()"
395 // and lock up. We don't have multiple windows and when the interpreter is
396 // embedded we don't know we should be feeding input to the embedded
397 // interpreter or to the python sys.stdin. We also don't want to let python
398 // play with the real stdin from this process, so we need to close it...
Greg Clayton3eeaf6e2012-02-03 01:30:30 +0000399 //run_string.PutCString ("; sys.stdin.close()");
Greg Clayton2fecc452012-01-28 02:11:02 +0000400 run_string.PutCString ("')");
Caroline Tice0aa2e552011-01-14 00:29:16 +0000401
Caroline Tice6af65cb2011-05-03 21:21:50 +0000402 PyRun_SimpleString (run_string.GetData());
403 run_string.Clear();
Johnny Chen41641f92012-02-29 01:52:13 +0000404
Caroline Tice0aa2e552011-01-14 00:29:16 +0000405 PyObject *sysmod = PyImport_AddModule ("sys");
406 PyObject *sysdict = PyModule_GetDict (sysmod);
Johnny Chen41641f92012-02-29 01:52:13 +0000407
Greg Clayton2fecc452012-01-28 02:11:02 +0000408 if (m_new_sysout && sysmod && sysdict)
409 {
Johnny Chen41641f92012-02-29 01:52:13 +0000410 m_old_sysout = PyDict_GetItemString(sysdict, "stdout");
411 m_old_syserr = PyDict_GetItemString(sysdict, "stderr");
Greg Clayton2fecc452012-01-28 02:11:02 +0000412 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
413 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
414 }
Johnny Chen41641f92012-02-29 01:52:13 +0000415
Caroline Tice0aa2e552011-01-14 00:29:16 +0000416 if (PyErr_Occurred())
417 PyErr_Clear ();
Greg Clayton2fecc452012-01-28 02:11:02 +0000418}
Caroline Tice0aa2e552011-01-14 00:29:16 +0000419
Johnny Chen60dde642010-07-30 22:33:14 +0000420bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000421ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000422{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000423 if (!m_valid_session)
424 return false;
425
Caroline Tice4a461da2011-01-14 21:09:29 +0000426 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
427 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
428 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
429 // method to pass the command string directly down to Python.
430
Enrico Granatafa1f6172011-10-24 17:22:21 +0000431 Locker locker(this,
432 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
433 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000434
435 bool success = false;
436
Greg Clayton63094e02010-06-23 01:19:29 +0000437 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000438 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000439 // Find the correct script interpreter dictionary in the main module.
440 PyObject *main_mod = PyImport_AddModule ("__main__");
441 PyObject *script_interpreter_dict = NULL;
442 if (main_mod != NULL)
443 {
444 PyObject *main_dict = PyModule_GetDict (main_mod);
445 if ((main_dict != NULL)
446 && PyDict_Check (main_dict))
447 {
448 // Go through the main dictionary looking for the correct python script interpreter dictionary
449 PyObject *key, *value;
450 Py_ssize_t pos = 0;
451
452 while (PyDict_Next (main_dict, &pos, &key, &value))
453 {
454 // We have stolen references to the key and value objects in the dictionary; we need to increment
455 // them now so that Python's garbage collector doesn't collect them out from under us.
456 Py_INCREF (key);
457 Py_INCREF (value);
458 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
459 {
460 script_interpreter_dict = value;
461 break;
462 }
463 }
464 }
465
466 if (script_interpreter_dict != NULL)
467 {
468 PyObject *pfunc = NULL;
469 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
470 if (pmod != NULL)
471 {
472 PyObject *pmod_dict = PyModule_GetDict (pmod);
473 if ((pmod_dict != NULL)
474 && PyDict_Check (pmod_dict))
475 {
476 PyObject *key, *value;
477 Py_ssize_t pos = 0;
478
479 while (PyDict_Next (pmod_dict, &pos, &key, &value))
480 {
481 Py_INCREF (key);
482 Py_INCREF (value);
483 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
484 {
485 pfunc = value;
486 break;
487 }
488 }
489
490 PyObject *string_arg = PyString_FromString (command);
491 if (pfunc && string_arg && PyCallable_Check (pfunc))
492 {
493 PyObject *pargs = PyTuple_New (2);
494 if (pargs != NULL)
495 {
496 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
497 PyTuple_SetItem (pargs, 1, string_arg);
498 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
499 Py_DECREF (pargs);
500 if (pvalue != NULL)
501 {
502 Py_DECREF (pvalue);
503 success = true;
504 }
505 else if (PyErr_Occurred ())
506 {
507 PyErr_Print();
508 PyErr_Clear();
509 }
510 }
511 }
512 }
513 }
514 Py_INCREF (script_interpreter_dict);
515 }
516 }
Greg Clayton63094e02010-06-23 01:19:29 +0000517
Caroline Tice4a461da2011-01-14 21:09:29 +0000518 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000519 return true;
520
521 // The one-liner failed. Append the error message.
522 if (result)
523 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
524 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000525 }
Johnny Chen60dde642010-07-30 22:33:14 +0000526
527 if (result)
528 result->AppendError ("empty command passed to python\n");
529 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000530}
531
Chris Lattner24943d22010-06-08 16:52:24 +0000532size_t
533ScriptInterpreterPython::InputReaderCallback
534(
535 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000536 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000537 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000538 const char *bytes,
539 size_t bytes_len
540)
541{
Caroline Tice2ade6112010-11-10 19:18:14 +0000542 lldb::thread_t embedded_interpreter_thread;
543 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
544
Chris Lattner24943d22010-06-08 16:52:24 +0000545 if (baton == NULL)
546 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000547
548 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000549
Caroline Tice0aa2e552011-01-14 00:29:16 +0000550 if (script_interpreter->m_script_lang != eScriptLanguagePython)
551 return 0;
552
Caroline Tice892fadd2011-06-16 16:27:19 +0000553 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
554 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
555
Chris Lattner24943d22010-06-08 16:52:24 +0000556 switch (notification)
557 {
558 case eInputReaderActivate:
559 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000560 if (!batch_mode)
561 {
562 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
563 out_stream->Flush();
564 }
Greg Clayton58928562011-02-09 01:08:52 +0000565
Chris Lattner24943d22010-06-08 16:52:24 +0000566 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000567 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
568 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000569 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000570
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000571 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000572
Caroline Tice202f6b82011-01-17 21:55:19 +0000573 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000574 ScriptInterpreterPython::Locker locker(script_interpreter,
575 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
576 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000577 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000578
Caroline Tice2ade6112010-11-10 19:18:14 +0000579 char error_str[1024];
580 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
581 sizeof(error_str)))
582 {
583 if (log)
584 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
585 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
586 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
587 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
588 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000589 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000590 {
591 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000592 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000593 Error detach_error;
594 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
595 }
596 else
597 {
598 if (log)
599 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
600 reader.SetIsDone (true);
601 }
602 }
603 else
604 {
605 if (log)
606 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
607 reader.SetIsDone (true);
608 }
Chris Lattner24943d22010-06-08 16:52:24 +0000609 }
610 break;
611
612 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000613 // When another input reader is pushed, don't leave the session...
614 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000615 break;
616
617 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000618 {
Greg Claytona1cec242012-01-06 00:47:38 +0000619 // Don't try and acquire the interpreter lock here because code like
620 // this:
621 //
622 // (lldb) script
623 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
624 //
625 // This will cause the process to run. The interpreter lock is taken
626 // by the input reader for the "script" command. If we try and acquire
627 // the lock here, when the process runs it might deactivate this input
628 // reader (if STDIN is hooked up to the inferior process) and
629 // reactivate it when the process stops which will deadlock.
630 //ScriptInterpreterPython::Locker locker(script_interpreter,
631 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
632 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000633 }
Chris Lattner24943d22010-06-08 16:52:24 +0000634 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000635
Caroline Tice4a348082011-05-02 20:41:46 +0000636 case eInputReaderAsynchronousOutputWritten:
637 break;
638
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000639 case eInputReaderInterrupt:
640 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
641 break;
642
643 case eInputReaderEndOfFile:
644 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
645 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000646
647 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000648 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000649 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000650 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000651 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000652 bytes_len);
653 if (bytes && bytes_len)
654 {
655 if ((int) bytes[0] == 4)
656 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
657 else
658 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
659 }
660 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000661 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000662 else
663 {
664 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000665 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000666 bytes,
667 bytes_len);
668 reader.SetIsDone (true);
669 }
670
Chris Lattner24943d22010-06-08 16:52:24 +0000671 break;
672
673 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000674 script_interpreter->LeaveSession ();
675
Chris Lattner24943d22010-06-08 16:52:24 +0000676 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000677 if (log)
678 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000679
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000680 script_interpreter->RestoreTerminalState ();
681
Caroline Tice2ade6112010-11-10 19:18:14 +0000682 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000683 break;
684 }
685
686 return bytes_len;
687}
688
689
690void
Greg Clayton238c0a12010-09-18 01:14:36 +0000691ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000692{
693 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
694
Caroline Tice0aa2e552011-01-14 00:29:16 +0000695 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000696
697 // At the moment, the only time the debugger does not have an input file handle is when this is called
698 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
699 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
700 // do it.
701
Greg Clayton58928562011-02-09 01:08:52 +0000702 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000703 return;
704
Greg Clayton63094e02010-06-23 01:19:29 +0000705 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000706 if (reader_sp)
707 {
708 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
709 this, // baton
710 eInputReaderGranularityLine, // token size, to pass to callback function
711 NULL, // end token
712 NULL, // prompt
713 true)); // echo input
714
715 if (error.Success())
716 {
Greg Clayton63094e02010-06-23 01:19:29 +0000717 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000718 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000719 }
720 }
721}
722
723bool
724ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000725 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000726 void *ret_value)
727{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000728
Enrico Granatafa1f6172011-10-24 17:22:21 +0000729 Locker locker(this,
730 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
731 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000732
Chris Lattner24943d22010-06-08 16:52:24 +0000733 PyObject *py_return = NULL;
734 PyObject *mainmod = PyImport_AddModule ("__main__");
735 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000736 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000737 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000738 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000739 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000740 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000741
742 if (PyDict_Check (globals))
743 {
744 PyObject *key, *value;
745 Py_ssize_t pos = 0;
746
747 int i = 0;
748 while (PyDict_Next (globals, &pos, &key, &value))
749 {
750 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
751 // so that Python's garbage collector doesn't collect them out from under us.
752 Py_INCREF (key);
753 Py_INCREF (value);
754 char *c_str = PyString_AsString (key);
755 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
756 locals = value;
757 ++i;
758 }
759 }
Chris Lattner24943d22010-06-08 16:52:24 +0000760
Caroline Tice0aa2e552011-01-14 00:29:16 +0000761 if (locals == NULL)
762 {
763 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
764 should_decrement_locals = true;
765 }
766
767 if (locals == NULL)
768 {
769 locals = globals;
770 should_decrement_locals = false;
771 }
772
773 py_error = PyErr_Occurred();
774 if (py_error != NULL)
775 PyErr_Clear();
776
Chris Lattner24943d22010-06-08 16:52:24 +0000777 if (in_string != NULL)
778 {
779 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
780 if (py_return == NULL)
781 {
782 py_error = PyErr_Occurred ();
783 if (py_error != NULL)
784 PyErr_Clear ();
785
786 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
787 }
788
Caroline Tice0aa2e552011-01-14 00:29:16 +0000789 if (locals != NULL
790 && should_decrement_locals)
791 Py_DECREF (locals);
792
Chris Lattner24943d22010-06-08 16:52:24 +0000793 if (py_return != NULL)
794 {
795 switch (return_type)
796 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000797 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000798 {
799 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000800 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000801 break;
802 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000803 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000804 {
805 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000806 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000807 break;
808 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000809 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000810 {
811 const char format[2] = "b";
812 success = PyArg_Parse (py_return, format, (bool *) ret_value);
813 break;
814 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000815 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000816 {
817 const char format[2] = "h";
818 success = PyArg_Parse (py_return, format, (short *) ret_value);
819 break;
820 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000821 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000822 {
823 const char format[2] = "H";
824 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
825 break;
826 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000827 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000828 {
829 const char format[2] = "i";
830 success = PyArg_Parse (py_return, format, (int *) ret_value);
831 break;
832 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000833 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000834 {
835 const char format[2] = "I";
836 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
837 break;
838 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000839 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000840 {
841 const char format[2] = "l";
842 success = PyArg_Parse (py_return, format, (long *) ret_value);
843 break;
844 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000845 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000846 {
847 const char format[2] = "k";
848 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
849 break;
850 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000851 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000852 {
853 const char format[2] = "L";
854 success = PyArg_Parse (py_return, format, (long long *) ret_value);
855 break;
856 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000857 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000858 {
859 const char format[2] = "K";
860 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
861 break;
862 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000863 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000864 {
865 const char format[2] = "f";
866 success = PyArg_Parse (py_return, format, (float *) ret_value);
867 break;
868 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000869 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000870 {
871 const char format[2] = "d";
872 success = PyArg_Parse (py_return, format, (double *) ret_value);
873 break;
874 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000875 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000876 {
877 const char format[2] = "c";
878 success = PyArg_Parse (py_return, format, (char *) ret_value);
879 break;
880 }
881 default:
882 {}
883 }
884 Py_DECREF (py_return);
885 if (success)
886 ret_success = true;
887 else
888 ret_success = false;
889 }
890 }
891
892 py_error = PyErr_Occurred();
893 if (py_error != NULL)
894 {
895 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
896 PyErr_Print ();
897 PyErr_Clear();
898 ret_success = false;
899 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000900
Chris Lattner24943d22010-06-08 16:52:24 +0000901 return ret_success;
902}
903
904bool
905ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
906{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000907
908
909 Locker locker(this,
910 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
911 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000912
Chris Lattner24943d22010-06-08 16:52:24 +0000913 bool success = false;
914 PyObject *py_return = NULL;
915 PyObject *mainmod = PyImport_AddModule ("__main__");
916 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000917 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000918 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000919 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000920
Caroline Tice0aa2e552011-01-14 00:29:16 +0000921 if (PyDict_Check (globals))
922 {
923 PyObject *key, *value;
924 Py_ssize_t pos = 0;
925
926 while (PyDict_Next (globals, &pos, &key, &value))
927 {
928 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
929 // so that Python's garbage collector doesn't collect them out from under us.
930 Py_INCREF (key);
931 Py_INCREF (value);
932 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
933 locals = value;
934 }
935 }
936
937 if (locals == NULL)
938 {
939 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
940 should_decrement_locals = true;
941 }
942
943 if (locals == NULL)
944 {
945 locals = globals;
946 should_decrement_locals = false;
947 }
948
949 py_error = PyErr_Occurred();
950 if (py_error != NULL)
951 PyErr_Clear();
952
Chris Lattner24943d22010-06-08 16:52:24 +0000953 if (in_string != NULL)
954 {
955 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
956 if (compiled_node)
957 {
958 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
959 if (compiled_code)
960 {
961 py_return = PyEval_EvalCode (compiled_code, globals, locals);
962 if (py_return != NULL)
963 {
964 success = true;
965 Py_DECREF (py_return);
966 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000967 if (locals && should_decrement_locals)
968 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000969 }
970 }
971 }
972
973 py_error = PyErr_Occurred ();
974 if (py_error != NULL)
975 {
976 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
977 PyErr_Print ();
978 PyErr_Clear();
979 success = false;
980 }
981
982 return success;
983}
984
985static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
986
987size_t
988ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
989(
990 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000991 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000992 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000993 const char *bytes,
994 size_t bytes_len
995)
996{
Caroline Tice892fadd2011-06-16 16:27:19 +0000997 static StringList commands_in_progress;
998
999 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1000 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1001
Chris Lattner24943d22010-06-08 16:52:24 +00001002 switch (notification)
1003 {
1004 case eInputReaderActivate:
1005 {
1006 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +00001007 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +00001008 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001009 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001010 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +00001011 out_stream->Printf ("%s", reader.GetPrompt());
1012 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001013 }
1014 }
1015 break;
1016
1017 case eInputReaderDeactivate:
1018 break;
1019
1020 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001021 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001022 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001023 out_stream->Printf ("%s", reader.GetPrompt());
1024 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001025 }
Chris Lattner24943d22010-06-08 16:52:24 +00001026 break;
1027
Caroline Tice4a348082011-05-02 20:41:46 +00001028 case eInputReaderAsynchronousOutputWritten:
1029 break;
1030
Chris Lattner24943d22010-06-08 16:52:24 +00001031 case eInputReaderGotToken:
1032 {
1033 std::string temp_string (bytes, bytes_len);
1034 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001035 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001036 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001037 out_stream->Printf ("%s", reader.GetPrompt());
1038 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001039 }
Chris Lattner24943d22010-06-08 16:52:24 +00001040 }
1041 break;
1042
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001043 case eInputReaderEndOfFile:
1044 case eInputReaderInterrupt:
1045 // Control-c (SIGINT) & control-d both mean finish & exit.
1046 reader.SetIsDone(true);
1047
1048 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1049 if (notification == eInputReaderInterrupt)
1050 commands_in_progress.Clear();
1051
1052 // Fall through here...
1053
Chris Lattner24943d22010-06-08 16:52:24 +00001054 case eInputReaderDone:
1055 {
1056 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1057 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1058 data_ap->user_source.AppendList (commands_in_progress);
1059 if (data_ap.get())
1060 {
Greg Clayton63094e02010-06-23 01:19:29 +00001061 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001062 if (interpreter)
1063 {
1064 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1065 data_ap->script_source))
1066 {
1067 if (data_ap->script_source.GetSize() == 1)
1068 {
1069 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1070 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1071 }
1072 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001073 else if (!batch_mode)
1074 {
1075 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1076 out_stream->Flush();
1077 }
Chris Lattner24943d22010-06-08 16:52:24 +00001078 }
1079 else
1080 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001081 if (!batch_mode)
1082 {
1083 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1084 out_stream->Flush();
1085 }
Chris Lattner24943d22010-06-08 16:52:24 +00001086 }
1087 }
1088 }
1089 break;
1090
1091 }
1092
1093 return bytes_len;
1094}
1095
1096void
Greg Clayton238c0a12010-09-18 01:14:36 +00001097ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001098 CommandReturnObject &result)
1099{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001100 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1101
Greg Clayton63094e02010-06-23 01:19:29 +00001102 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001103
1104 if (reader_sp)
1105 {
1106 Error err = reader_sp->Initialize (
1107 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1108 bp_options, // baton
1109 eInputReaderGranularityLine, // token size, for feeding data to callback function
1110 "DONE", // end token
1111 "> ", // prompt
1112 true); // echo input
1113
1114 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001115 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001116 else
1117 {
1118 result.AppendError (err.AsCString());
1119 result.SetStatus (eReturnStatusFailed);
1120 }
1121 }
1122 else
1123 {
1124 result.AppendError("out of memory");
1125 result.SetStatus (eReturnStatusFailed);
1126 }
1127}
1128
Johnny Chen3e0571b2010-09-11 00:23:59 +00001129// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001130void
Greg Clayton238c0a12010-09-18 01:14:36 +00001131ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001132 const char *oneliner)
1133{
1134 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1135
1136 // It's necessary to set both user_source and script_source to the oneliner.
1137 // The former is used to generate callback description (as in breakpoint command list)
1138 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001139
Johnny Chend1c2dca2010-09-10 18:21:10 +00001140 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001141
Caroline Tice5136f942010-09-27 21:35:15 +00001142 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1143 {
1144 if (data_ap->script_source.GetSize() == 1)
1145 {
1146 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1147 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1148 }
1149 }
1150
Johnny Chend1c2dca2010-09-10 18:21:10 +00001151 return;
1152}
1153
Chris Lattner24943d22010-06-08 16:52:24 +00001154bool
1155ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1156{
1157 // Convert StringList to one long, newline delimited, const char *.
1158 std::string function_def_string;
1159
1160 int num_lines = function_def.GetSize();
1161
1162 for (int i = 0; i < num_lines; ++i)
1163 {
1164 function_def_string.append (function_def.GetStringAtIndex(i));
1165 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1166 function_def_string.append ("\n");
1167
1168 }
1169
1170 return ExecuteMultipleLines (function_def_string.c_str());
1171}
1172
Enrico Granataf7a9b142011-07-15 02:26:42 +00001173// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1174// use this code to generate their functions
1175bool
1176ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1177{
1178 int num_lines = input.GetSize ();
1179 if (num_lines == 0)
1180 return false;
1181 StreamString sstr;
1182 StringList auto_generated_function;
1183 auto_generated_function.AppendString (signature.c_str());
1184 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1185 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1186 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1187 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1188 // global dictionary.
1189
1190 // Wrap everything up inside the function, increasing the indentation.
1191
1192 for (int i = 0; i < num_lines; ++i)
1193 {
1194 sstr.Clear ();
1195 sstr.Printf (" %s", input.GetStringAtIndex (i));
1196 auto_generated_function.AppendString (sstr.GetData());
1197 }
1198 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1199 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1200 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1201 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1202
1203 // Verify that the results are valid Python.
1204
1205 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1206 return false;
1207
1208 return true;
1209
1210}
1211
1212// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1213// given to generated functions, of course)
1214bool
Enrico Granata16376ed2012-02-15 02:34:21 +00001215ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001216{
1217 static int num_created_functions = 0;
1218 user_input.RemoveBlankLines ();
1219 int num_lines = user_input.GetSize ();
1220 StreamString sstr;
1221
1222 // Check to see if we have any data; if not, just return.
1223 if (user_input.GetSize() == 0)
1224 return false;
1225
1226 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1227 // ValueObject as parameter to the function.
1228
Enrico Granata16376ed2012-02-15 02:34:21 +00001229 if (!name_token)
1230 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1231 else
1232 sstr.Printf ("lldb_gen_python_type_print_func_%p", name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001233 ++num_created_functions;
1234 std::string auto_generated_function_name = sstr.GetData();
1235
1236 sstr.Clear();
1237 StringList auto_generated_function;
1238
1239 // Create the function name & definition string.
1240
1241 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1242 auto_generated_function.AppendString (sstr.GetData());
1243
1244 // Pre-pend code for setting up the session dictionary.
1245
1246 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1247 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1248 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1249 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1250 // global dictionary.
1251
1252 // Wrap everything up inside the function, increasing the indentation.
1253
1254 for (int i = 0; i < num_lines; ++i)
1255 {
1256 sstr.Clear ();
1257 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1258 auto_generated_function.AppendString (sstr.GetData());
1259 }
1260
1261 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1262 // got written to the values in the global dictionary, not the session dictionary).
1263
1264 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1265 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1266 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1267 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1268
1269 // Verify that the results are valid Python.
1270
1271 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1272 return false;
1273
1274 // Store the name of the auto-generated function to be called.
1275
1276 output.AppendString (auto_generated_function_name.c_str());
1277 return true;
1278}
1279
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001280bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001281ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, StringList &output)
1282{
1283 static int num_created_functions = 0;
1284 user_input.RemoveBlankLines ();
1285 int num_lines = user_input.GetSize ();
1286 StreamString sstr;
1287
1288 // Check to see if we have any data; if not, just return.
1289 if (user_input.GetSize() == 0)
1290 return false;
1291
1292 // 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 +00001293 // required data as parameters to the function.
Enrico Granatac2a28252011-08-16 16:49:25 +00001294
1295 sstr.Printf ("lldb_autogen_python_cmd_alias_func_%d", num_created_functions);
1296 ++num_created_functions;
1297 std::string auto_generated_function_name = sstr.GetData();
1298
1299 sstr.Clear();
1300 StringList auto_generated_function;
1301
1302 // Create the function name & definition string.
1303
Enrico Granata271568f2011-09-09 01:41:30 +00001304 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001305 auto_generated_function.AppendString (sstr.GetData());
1306
1307 // Pre-pend code for setting up the session dictionary.
1308
1309 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1310 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1311 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1312 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1313 // global dictionary.
1314
1315 // Wrap everything up inside the function, increasing the indentation.
1316
1317 for (int i = 0; i < num_lines; ++i)
1318 {
1319 sstr.Clear ();
1320 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1321 auto_generated_function.AppendString (sstr.GetData());
1322 }
1323
1324 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1325 // got written to the values in the global dictionary, not the session dictionary).
1326
1327 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1328 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1329 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1330 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1331
1332 // Verify that the results are valid Python.
1333
1334 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1335 return false;
1336
1337 // Store the name of the auto-generated function to be called.
1338
1339 output.AppendString (auto_generated_function_name.c_str());
1340 return true;
1341}
1342
1343
1344bool
Enrico Granata16376ed2012-02-15 02:34:21 +00001345ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output, void* name_token)
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001346{
1347 static int num_created_classes = 0;
1348 user_input.RemoveBlankLines ();
1349 int num_lines = user_input.GetSize ();
1350 StreamString sstr;
1351
1352 // Check to see if we have any data; if not, just return.
1353 if (user_input.GetSize() == 0)
1354 return false;
1355
1356 // Wrap all user input into a Python class
1357
Enrico Granata16376ed2012-02-15 02:34:21 +00001358 if (!name_token)
1359 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1360 else
1361 sstr.Printf ("lldb_gen_python_type_synth_class_%p", name_token);
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001362 ++num_created_classes;
1363 std::string auto_generated_class_name = sstr.GetData();
1364
1365 sstr.Clear();
1366 StringList auto_generated_class;
1367
1368 // Create the function name & definition string.
1369
1370 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1371 auto_generated_class.AppendString (sstr.GetData());
1372
1373 // Wrap everything up inside the class, increasing the indentation.
1374
1375 for (int i = 0; i < num_lines; ++i)
1376 {
1377 sstr.Clear ();
1378 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1379 auto_generated_class.AppendString (sstr.GetData());
1380 }
1381
1382
1383 // Verify that the results are valid Python.
1384 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1385 // (TODO: rename that method to ExportDefinitionToInterpreter)
1386 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1387 return false;
1388
1389 // Store the name of the auto-generated class
1390
1391 output.AppendString (auto_generated_class_name.c_str());
1392 return true;
1393}
1394
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001395void*
1396ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1397 lldb::ValueObjectSP valobj)
1398{
1399 if (class_name.empty())
1400 return NULL;
1401
1402 if (!valobj.get())
1403 return NULL;
1404
Greg Claytonb4d7fc02012-02-17 07:49:44 +00001405 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1406 Target *target = exe_ctx.GetTargetPtr();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001407
1408 if (!target)
1409 return NULL;
1410
1411 Debugger &debugger = target->GetDebugger();
1412 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1413 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1414
1415 if (!script_interpreter)
1416 return NULL;
1417
1418 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001419
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001420 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001421 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001422 ret_val = g_swig_synthetic_script (class_name,
1423 python_interpreter->m_dictionary_name.c_str(),
1424 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001425 }
1426
1427 return ret_val;
1428}
1429
Enrico Granataf7a9b142011-07-15 02:26:42 +00001430bool
Enrico Granata16376ed2012-02-15 02:34:21 +00001431ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001432{
Enrico Granata16376ed2012-02-15 02:34:21 +00001433 StringList input;
1434 input.SplitIntoLines(oneliner, strlen(oneliner));
1435 return GenerateTypeScriptFunction(input, output, name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001436}
1437
Chris Lattner24943d22010-06-08 16:52:24 +00001438bool
Enrico Granata16376ed2012-02-15 02:34:21 +00001439ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, StringList &output, void* name_token)
1440{
1441 StringList input;
1442 input.SplitIntoLines(oneliner, strlen(oneliner));
1443 return GenerateTypeSynthClass(input, output, name_token);
1444}
1445
1446
1447bool
Chris Lattner24943d22010-06-08 16:52:24 +00001448ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1449{
1450 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001451 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001452 int num_lines = user_input.GetSize ();
1453 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001454
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001455 // Check to see if we have any data; if not, just return.
1456 if (user_input.GetSize() == 0)
1457 return false;
1458
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001459 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1460 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001461
Caroline Ticeb447e842010-09-21 19:25:28 +00001462
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001463 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1464 ++num_created_functions;
1465 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001466
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001467 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001468 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001469
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001470 // Create the function name & definition string.
1471
Caroline Tice0aa2e552011-01-14 00:29:16 +00001472 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001473 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001474
1475 // Pre-pend code for setting up the session dictionary.
1476
1477 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1478 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1479 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1480 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1481 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001482
1483 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001484
1485 for (int i = 0; i < num_lines; ++i)
1486 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001487 sstr.Clear ();
1488 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1489 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001490 }
Chris Lattner24943d22010-06-08 16:52:24 +00001491
Caroline Tice0aa2e552011-01-14 00:29:16 +00001492 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1493 // got written to the values in the global dictionary, not the session dictionary).
1494
1495 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1496 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1497 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1498 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1499
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001500 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001501
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001502 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001503 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001504 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001505 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001506
1507 // Store the name of the auto-generated function to be called.
1508
1509 callback_data.AppendString (auto_generated_function_name.c_str());
1510 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001511}
1512
Enrico Granata1328b142012-02-29 03:28:49 +00001513static PyObject*
1514FindSessionDictionary(const char* dict_name)
1515{
1516 static std::map<ConstString,PyObject*> g_dict_map;
1517
1518 ConstString dict(dict_name);
1519
1520 std::map<ConstString,PyObject*>::iterator iter = g_dict_map.find(dict);
1521
1522 if (iter != g_dict_map.end())
1523 return iter->second;
1524
1525 PyObject *main_mod = PyImport_AddModule ("__main__");
1526 if (main_mod != NULL)
1527 {
1528 PyObject *main_dict = PyModule_GetDict (main_mod);
1529 if ((main_dict != NULL)
1530 && PyDict_Check (main_dict))
1531 {
1532 // Go through the main dictionary looking for the correct python script interpreter dictionary
1533 PyObject *key, *value;
1534 Py_ssize_t pos = 0;
1535
1536 while (PyDict_Next (main_dict, &pos, &key, &value))
1537 {
1538 // We have stolen references to the key and value objects in the dictionary; we need to increment
1539 // them now so that Python's garbage collector doesn't collect them out from under us.
1540 Py_INCREF (key);
1541 Py_INCREF (value);
1542 if (strcmp (PyString_AsString (key), dict_name) == 0)
1543 {
1544 g_dict_map[dict] = value;
1545 return value;
1546 }
1547 }
1548 }
1549 }
1550 return NULL;
1551}
1552
1553bool
1554ScriptInterpreterPython::GetScriptedSummary (const char *python_function_name,
1555 lldb::ValueObjectSP valobj,
1556 lldb::ScriptInterpreterObjectSP& callee_wrapper_sp,
1557 std::string& retval)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001558{
1559
Enrico Granata1328b142012-02-29 03:28:49 +00001560 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001561
1562 if (!valobj.get())
Enrico Granata1328b142012-02-29 03:28:49 +00001563 {
1564 retval.assign("<no object>");
1565 return false;
1566 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001567
Enrico Granata1328b142012-02-29 03:28:49 +00001568 void* old_callee = (callee_wrapper_sp ? callee_wrapper_sp->GetObject() : NULL);
1569 void* new_callee = old_callee;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001570
Enrico Granata1328b142012-02-29 03:28:49 +00001571 bool ret_val;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001572 if (python_function_name
1573 && *python_function_name)
1574 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001575 {
Enrico Granata1328b142012-02-29 03:28:49 +00001576 Locker py_lock(this);
1577 {
1578 Timer scoped_timer ("g_swig_typescript_callback","g_swig_typescript_callback");
1579 ret_val = g_swig_typescript_callback (python_function_name,
1580 FindSessionDictionary(m_dictionary_name.c_str()),
1581 valobj,
1582 &new_callee,
1583 retval);
1584 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001585 }
1586 }
1587 else
Enrico Granata1328b142012-02-29 03:28:49 +00001588 {
1589 retval.assign("<no function name>");
1590 return false;
1591 }
1592
1593 if (new_callee && old_callee != new_callee)
1594 callee_wrapper_sp = MakeScriptObject(new_callee);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001595
1596 return ret_val;
1597
1598}
1599
Greg Clayton5144f382010-10-07 17:14:24 +00001600bool
1601ScriptInterpreterPython::BreakpointCallbackFunction
1602(
1603 void *baton,
1604 StoppointCallbackContext *context,
1605 user_id_t break_id,
1606 user_id_t break_loc_id
1607)
1608{
1609 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1610 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001611
1612 if (!context)
1613 return true;
1614
Greg Claytonf4124de2012-02-21 00:09:25 +00001615 ExecutionContext exe_ctx (context->exe_ctx_ref);
1616 Target *target = exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001617
1618 if (!target)
1619 return true;
1620
1621 Debugger &debugger = target->GetDebugger();
1622 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1623 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1624
1625 if (!script_interpreter)
1626 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001627
1628 if (python_function_name != NULL
1629 && python_function_name[0] != '\0')
1630 {
Greg Claytonf4124de2012-02-21 00:09:25 +00001631 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001632 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001633 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001634 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001635 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1636
1637 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001638 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001639 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001640 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001641 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001642 ret_val = g_swig_breakpoint_callback (python_function_name,
1643 python_interpreter->m_dictionary_name.c_str(),
1644 stop_frame_sp,
1645 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001646 }
1647 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001648 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001649 }
Greg Clayton5144f382010-10-07 17:14:24 +00001650 }
1651 // We currently always true so we stop in case anything goes wrong when
1652 // trying to call the script function
1653 return true;
1654}
Caroline Tice2ade6112010-11-10 19:18:14 +00001655
1656lldb::thread_result_t
1657ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1658{
1659 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1660
1661 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1662
1663 if (log)
1664 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1665
1666 char error_str[1024];
1667 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001668
Enrico Granatafa1f6172011-10-24 17:22:21 +00001669 Locker locker(script_interpreter,
1670 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1671 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1672
1673 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001674 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001675 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001676
Caroline Tice0aa2e552011-01-14 00:29:16 +00001677 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1678 PyRun_SimpleString (run_string.GetData());
1679 run_string.Clear ();
1680
1681 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1682 PyRun_SimpleString (run_string.GetData());
1683 run_string.Clear ();
1684
1685 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1686 PyRun_SimpleString (run_string.GetData());
1687 run_string.Clear ();
1688
1689 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1690 pty_slave_name);
1691 PyRun_SimpleString (run_string.GetData());
1692 run_string.Clear ();
1693
Johnny Chen8054ba32011-03-11 00:28:50 +00001694 // The following call drops into the embedded interpreter loop and stays there until the
1695 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001696
Caroline Ticece207c12011-03-11 00:21:55 +00001697 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001698 // 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 +00001699 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1700
1701 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1702 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1703 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1704 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1705 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1706 // hang (it's happened before).
1707
Caroline Tice9d352ce2011-03-07 23:24:28 +00001708 Py_BEGIN_ALLOW_THREADS
1709 PyGILState_STATE gstate = PyGILState_Ensure();
1710
Caroline Tice0aa2e552011-01-14 00:29:16 +00001711 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1712 PyRun_SimpleString (run_string.GetData());
1713 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001714
Caroline Tice9d352ce2011-03-07 23:24:28 +00001715 PyGILState_Release (gstate);
1716 Py_END_ALLOW_THREADS
1717
Caroline Tice0aa2e552011-01-14 00:29:16 +00001718 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1719 PyRun_SimpleString (run_string.GetData());
1720 run_string.Clear();
1721
1722 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1723 PyRun_SimpleString (run_string.GetData());
1724 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001725
Caroline Tice2ade6112010-11-10 19:18:14 +00001726 }
1727
1728 if (script_interpreter->m_embedded_thread_input_reader_sp)
1729 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1730
1731 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001732
Caroline Tice2ade6112010-11-10 19:18:14 +00001733 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1734 if (log)
1735 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1736
1737
Johnny Chen8054ba32011-03-11 00:28:50 +00001738 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001739 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001740 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1741 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1742 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001743
Caroline Tice2ade6112010-11-10 19:18:14 +00001744 return NULL;
1745}
1746
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001747uint32_t
1748ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1749{
1750 if (!implementor)
1751 return 0;
1752
1753 if (!g_swig_calc_children)
1754 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001755
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001756 uint32_t ret_val = 0;
1757
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001758 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001759 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001760 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001761 }
1762
1763 return ret_val;
1764}
1765
Enrico Granata91544802011-09-06 19:20:51 +00001766lldb::ValueObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001767ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1768{
1769 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001770 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001771
Enrico Granata91544802011-09-06 19:20:51 +00001772 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1773 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001774
Enrico Granata91544802011-09-06 19:20:51 +00001775 void* child_ptr = NULL;
1776 lldb::SBValue* value_sb = NULL;
1777 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001778
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001779 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001780 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +00001781 child_ptr = g_swig_get_child_index (implementor,idx);
1782 if (child_ptr != NULL && child_ptr != Py_None)
1783 {
1784 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1785 if (value_sb == NULL)
1786 Py_XDECREF(child_ptr);
1787 else
1788 ret_val = value_sb->get_sp();
1789 }
1790 else
1791 {
1792 Py_XDECREF(child_ptr);
1793 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001794 }
1795
1796 return ret_val;
1797}
1798
1799int
1800ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1801{
1802 if (!implementor)
1803 return UINT32_MAX;
1804
1805 if (!g_swig_get_index_child)
1806 return UINT32_MAX;
1807
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001808 int ret_val = UINT32_MAX;
1809
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001810 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001811 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001812 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001813 }
1814
1815 return ret_val;
1816}
1817
Enrico Granata979e20d2011-07-29 19:53:35 +00001818void
1819ScriptInterpreterPython::UpdateSynthProviderInstance (void* implementor)
1820{
1821 if (!implementor)
1822 return;
1823
1824 if (!g_swig_update_provider)
1825 return;
1826
Enrico Granata979e20d2011-07-29 19:53:35 +00001827 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001828 Locker py_lock(this);
Enrico Granata979e20d2011-07-29 19:53:35 +00001829 g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001830 }
1831
1832 return;
1833}
1834
Enrico Granatac2a28252011-08-16 16:49:25 +00001835bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001836ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00001837 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00001838 lldb_private::Error& error)
1839{
1840 if (!pathname || !pathname[0])
1841 {
1842 error.SetErrorString("invalid pathname");
1843 return false;
1844 }
1845
1846 if (!g_swig_call_module_init)
1847 {
1848 error.SetErrorString("internal helper function missing");
1849 return false;
1850 }
1851
Greg Clayton13d24fb2012-01-29 20:56:30 +00001852 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granatafa1f6172011-10-24 17:22:21 +00001853
Enrico Granata59df36f2011-10-17 21:45:27 +00001854 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001855 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00001856
1857 FileSpec target_file(pathname, true);
1858
1859 // TODO: would we want to reject any other value?
1860 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1861 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1862 {
1863 error.SetErrorString("invalid pathname");
1864 return false;
1865 }
1866
1867 const char* directory = target_file.GetDirectory().GetCString();
1868 std::string basename(target_file.GetFilename().GetCString());
1869
1870 // now make sure that Python has "directory" in the search path
1871 StreamString command_stream;
1872 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1873 directory,
1874 directory);
Enrico Granatafa1f6172011-10-24 17:22:21 +00001875 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData());
Enrico Granata59df36f2011-10-17 21:45:27 +00001876 if (!syspath_retval)
1877 {
1878 error.SetErrorString("Python sys.path handling failed");
1879 return false;
1880 }
1881
1882 // strip .py or .pyc extension
1883 ConstString extension = target_file.GetFileNameExtension();
1884 if (::strcmp(extension.GetCString(), "py") == 0)
1885 basename.resize(basename.length()-3);
1886 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1887 basename.resize(basename.length()-4);
1888
1889 // check if the module is already import-ed
1890 command_stream.Clear();
1891 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1892 int refcount = 0;
1893 // this call will fail if the module does not exist (because the parameter to it is not a string
1894 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00001895 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
1896 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0);
1897 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00001898 {
1899 error.SetErrorString("module already imported");
1900 return false;
1901 }
1902
1903 // now actually do the import
1904 command_stream.Clear();
1905 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafa1f6172011-10-24 17:22:21 +00001906 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL);
Enrico Granata59df36f2011-10-17 21:45:27 +00001907 if (!import_retval)
1908 {
1909 error.SetErrorString("Python import statement failed");
1910 return false;
1911 }
1912
Enrico Granata16376ed2012-02-15 02:34:21 +00001913 // call __lldb_init_module(debugger,dict)
Enrico Granata59df36f2011-10-17 21:45:27 +00001914 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001915 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001916 debugger_sp))
1917 {
Enrico Granata16376ed2012-02-15 02:34:21 +00001918 error.SetErrorString("calling __lldb_init_module failed");
Enrico Granata59df36f2011-10-17 21:45:27 +00001919 return false;
1920 }
1921 return true;
1922 }
1923}
1924
Enrico Granata1328b142012-02-29 03:28:49 +00001925lldb::ScriptInterpreterObjectSP
1926ScriptInterpreterPython::MakeScriptObject (void* object)
1927{
1928 return lldb::ScriptInterpreterObjectSP(new ScriptInterpreterPythonObject(object));
1929}
1930
Enrico Granata6010ace2011-11-07 22:57:04 +00001931ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
1932 ScriptedCommandSynchronicity synchro) :
1933 m_debugger_sp(debugger_sp),
1934 m_synch_wanted(synchro),
1935 m_old_asynch(debugger_sp->GetAsyncExecution())
1936{
1937 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
1938 m_debugger_sp->SetAsyncExecution(false);
1939 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
1940 m_debugger_sp->SetAsyncExecution(true);
1941}
1942
1943ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
1944{
1945 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
1946 m_debugger_sp->SetAsyncExecution(m_old_asynch);
1947}
1948
Enrico Granata59df36f2011-10-17 21:45:27 +00001949bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001950ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1951 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00001952 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001953 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001954 Error& error)
1955{
1956 if (!impl_function)
1957 {
1958 error.SetErrorString("no function to execute");
1959 return false;
1960 }
1961
1962 if (!g_swig_call_command)
1963 {
1964 error.SetErrorString("no helper function to run scripted commands");
1965 return false;
1966 }
1967
Greg Clayton13d24fb2012-01-29 20:56:30 +00001968 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata6010ace2011-11-07 22:57:04 +00001969
1970 if (!debugger_sp.get())
1971 {
1972 error.SetErrorString("invalid Debugger pointer");
1973 return false;
1974 }
Enrico Granatac2a28252011-08-16 16:49:25 +00001975
1976 bool ret_val;
1977
1978 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00001979
Enrico Granatac2a28252011-08-16 16:49:25 +00001980 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001981 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00001982 SynchronicityHandler synch_handler(debugger_sp,
1983 synchronicity);
1984
Enrico Granatac2a28252011-08-16 16:49:25 +00001985 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001986 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00001987 debugger_sp,
1988 args,
1989 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001990 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001991 }
Enrico Granata6010ace2011-11-07 22:57:04 +00001992
Enrico Granatac2a28252011-08-16 16:49:25 +00001993 if (!ret_val)
1994 error.SetErrorString(err_msg.c_str());
1995 else
1996 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00001997
Enrico Granatac2a28252011-08-16 16:49:25 +00001998 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00001999}
2000
Enrico Granatae5e34cb2011-08-17 01:30:04 +00002001// in Python, a special attribute __doc__ contains the docstring
2002// for an object (function, method, class, ...) if any is defined
2003// Otherwise, the attribute's value is None
2004std::string
2005ScriptInterpreterPython::GetDocumentationForItem(const char* item)
2006{
2007 std::string command(item);
2008 command += ".__doc__";
2009
2010 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
2011
2012 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00002013 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00002014 &result_ptr) && result_ptr)
2015 {
2016 return std::string(result_ptr);
2017 }
2018 else
2019 return std::string("");
2020}
Caroline Tice2ade6112010-11-10 19:18:14 +00002021
Caroline Tice0aa2e552011-01-14 00:29:16 +00002022void
Enrico Granata1328b142012-02-29 03:28:49 +00002023ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback)
Greg Claytone86cbb92011-03-22 01:14:58 +00002024{
2025 g_swig_init_callback = python_swig_init_callback;
Enrico Granata1328b142012-02-29 03:28:49 +00002026 g_swig_breakpoint_callback = LLDBSwigPythonBreakpointCallbackFunction;
2027 g_swig_typescript_callback = LLDBSwigPythonCallTypeScript;
2028 g_swig_synthetic_script = LLDBSwigPythonCreateSyntheticProvider;
2029 g_swig_calc_children = LLDBSwigPython_CalculateNumChildren;
2030 g_swig_get_child_index = LLDBSwigPython_GetChildAtIndex;
2031 g_swig_get_index_child = LLDBSwigPython_GetIndexOfChildWithName;
2032 g_swig_cast_to_sbvalue = LLDBSWIGPython_CastPyObjectToSBValue;
2033 g_swig_update_provider = LLDBSwigPython_UpdateSynthProviderInstance;
2034 g_swig_call_command = LLDBSwigPythonCallCommand;
2035 g_swig_call_module_init = LLDBSwigPythonCallModuleInit;
Greg Claytone86cbb92011-03-22 01:14:58 +00002036}
2037
2038void
2039ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00002040{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002041 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
2042
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002043 // Python will muck with STDIN terminal state, so save off any current TTY
2044 // settings so we can restore them.
2045 TerminalState stdin_tty_state;
2046 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002047
Caroline Tice9d352ce2011-03-07 23:24:28 +00002048 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00002049 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002050
Greg Claytone86cbb92011-03-22 01:14:58 +00002051 // Initialize SWIG after setting up python
2052 assert (g_swig_init_callback != NULL);
2053 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002054
2055 // Update the path python uses to search for modules to include the current directory.
2056
Caroline Ticed4d92832011-06-13 21:33:00 +00002057 PyRun_SimpleString ("import sys");
2058 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00002059
2060 // Find the module that owns this code and use that path we get to
2061 // set the sys.path appropriately.
2062
2063 FileSpec file_spec;
2064 char python_dir_path[PATH_MAX];
2065 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
2066 {
2067 std::string python_path("sys.path.insert(0,\"");
2068 size_t orig_len = python_path.length();
2069 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2070 {
2071 python_path.append (python_dir_path);
2072 python_path.append ("\")");
2073 PyRun_SimpleString (python_path.c_str());
2074 python_path.resize (orig_len);
2075 }
2076
2077 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
2078 {
2079 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2080 {
2081 python_path.append (python_dir_path);
2082 python_path.append ("\")");
2083 PyRun_SimpleString (python_path.c_str());
2084 python_path.resize (orig_len);
2085 }
2086 }
2087 }
2088
Jim Ingham4dfa5112011-08-22 19:10:09 +00002089 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00002090
Caroline Ticed4d92832011-06-13 21:33:00 +00002091 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00002092
Caroline Ticed4d92832011-06-13 21:33:00 +00002093 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
2094 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00002095 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00002096
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002097 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002098}
2099
Greg Claytone86cbb92011-03-22 01:14:58 +00002100//void
2101//ScriptInterpreterPython::Terminate ()
2102//{
2103// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
2104// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
2105// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
2106// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
2107// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
2108// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
2109// // within Py_Finalize, which results in a seg fault.
2110// //
2111// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
2112// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
2113// // process exits).
2114// //
2115//// Py_Finalize ();
2116//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00002117
2118#endif // #ifdef LLDB_DISABLE_PYTHON