blob: ccdf7486ca47c8effdcf5337268ee505b5b47047 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ScriptInterpreterPython.cpp -----------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// In order to guarantee correct working with Python, Python.h *MUST* be
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +000011// the *FIRST* header file included here.
Greg Clayton3e4238d2011-11-04 03:34:56 +000012#ifdef LLDB_DISABLE_PYTHON
13
14// Python is disabled in this build
15
16#else
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +000017
18#if defined (__APPLE__)
19#include <Python/Python.h>
20#else
21#include <Python.h>
22#endif
Chris Lattner24943d22010-06-08 16:52:24 +000023
24#include "lldb/Interpreter/ScriptInterpreterPython.h"
25
Chris Lattner24943d22010-06-08 16:52:24 +000026#include <stdlib.h>
27#include <stdio.h>
28
29#include <string>
30
Enrico Granata91544802011-09-06 19:20:51 +000031#include "lldb/API/SBValue.h"
Greg Clayton987c7eb2011-09-17 08:33:22 +000032#include "lldb/Breakpoint/BreakpointLocation.h"
Greg Clayton63094e02010-06-23 01:19:29 +000033#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner24943d22010-06-08 16:52:24 +000034#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000035#include "lldb/Core/Timer.h"
36#include "lldb/Host/Host.h"
37#include "lldb/Interpreter/CommandInterpreter.h"
38#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton5144f382010-10-07 17:14:24 +000039#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040
Chris Lattner24943d22010-06-08 16:52:24 +000041using namespace lldb;
42using namespace lldb_private;
43
Greg Claytone86cbb92011-03-22 01:14:58 +000044
45static ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL;
46static ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL;
Enrico Granataf7a9b142011-07-15 02:26:42 +000047static ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL;
Enrico Granata9ae7cef2011-07-24 00:14:56 +000048static ScriptInterpreter::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = NULL;
49static ScriptInterpreter::SWIGPythonCalculateNumChildren g_swig_calc_children = NULL;
50static ScriptInterpreter::SWIGPythonGetChildAtIndex g_swig_get_child_index = NULL;
51static ScriptInterpreter::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = NULL;
52static ScriptInterpreter::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = NULL;
Enrico Granata979e20d2011-07-29 19:53:35 +000053static ScriptInterpreter::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = NULL;
Enrico Granatac2a28252011-08-16 16:49:25 +000054static ScriptInterpreter::SWIGPythonCallCommand g_swig_call_command = NULL;
Enrico Granata59df36f2011-10-17 21:45:27 +000055static ScriptInterpreter::SWIGPythonCallModuleInit g_swig_call_module_init = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +000056
57static int
58_check_and_flush (FILE *stream)
59{
60 int prev_fail = ferror (stream);
61 return fflush (stream) || prev_fail ? EOF : 0;
62}
63
Caroline Tice202f6b82011-01-17 21:55:19 +000064static Predicate<lldb::tid_t> &
65PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +000066{
Caroline Tice202f6b82011-01-17 21:55:19 +000067 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
68 return g_interpreter_is_running;
69}
70
Enrico Granatafa1f6172011-10-24 17:22:21 +000071bool
72ScriptInterpreterPython::Locker::CurrentThreadHasPythonLock ()
Caroline Tice202f6b82011-01-17 21:55:19 +000073{
74 TimeValue timeout;
75
76 timeout = TimeValue::Now(); // Don't wait any time.
77
78 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
79}
80
Enrico Granatafa1f6172011-10-24 17:22:21 +000081bool
82ScriptInterpreterPython::Locker::TryGetPythonLock (uint32_t seconds_to_wait)
Caroline Tice202f6b82011-01-17 21:55:19 +000083{
84
85 TimeValue timeout;
86
87 if (seconds_to_wait != UINT32_MAX)
88 {
89 timeout = TimeValue::Now();
90 timeout.OffsetWithSeconds (seconds_to_wait);
91 }
92
93 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
94 Host::GetCurrentThreadID(), &timeout, NULL);
95}
96
Enrico Granatafa1f6172011-10-24 17:22:21 +000097void
98ScriptInterpreterPython::Locker::ReleasePythonLock ()
Caroline Tice202f6b82011-01-17 21:55:19 +000099{
100 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000101}
102
Enrico Granatafa1f6172011-10-24 17:22:21 +0000103ScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *py_interpreter,
104 uint16_t on_entry,
105 uint16_t on_leave,
106 FILE* wait_msg_handle) :
107 m_need_session( (on_leave & TearDownSession) == TearDownSession ),
108 m_release_lock ( false ), // decide in constructor body
109 m_python_interpreter(py_interpreter),
110 m_tmp_fh(wait_msg_handle)
Enrico Granata91544802011-09-06 19:20:51 +0000111{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000112 if (m_python_interpreter && !m_tmp_fh)
113 m_tmp_fh = (m_python_interpreter->m_dbg_stdout ? m_python_interpreter->m_dbg_stdout : stdout);
114
115 if ( (on_entry & AcquireLock) == AcquireLock )
116 {
117 if (CurrentThreadHasPythonLock())
118 {
119 if ( (on_leave & FreeLock) == FreeLock )
120 m_release_lock = true;
121 }
122 else
123 {
124 DoAcquireLock();
125 if ( (on_leave & FreeLock) == FreeLock )
126 m_release_lock = true;
127 if ( (on_leave & FreeAcquiredLock) == FreeAcquiredLock )
128 m_release_lock = true;
129 }
130 }
131 if ( (on_entry & InitSession) == InitSession )
132 DoInitSession();
133}
134
135bool
136ScriptInterpreterPython::Locker::DoAcquireLock()
137{
Enrico Granata91544802011-09-06 19:20:51 +0000138 if (!CurrentThreadHasPythonLock())
139 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000140 while (!TryGetPythonLock (1))
141 if (m_tmp_fh)
142 fprintf (m_tmp_fh,
Enrico Granata91544802011-09-06 19:20:51 +0000143 "Python interpreter locked on another thread; waiting to acquire lock...\n");
Enrico Granata91544802011-09-06 19:20:51 +0000144 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000145 return true;
146}
147
148bool
149ScriptInterpreterPython::Locker::DoInitSession()
150{
151 if (!m_python_interpreter)
152 return false;
153 m_python_interpreter->EnterSession ();
154 return true;
155}
156
157bool
158ScriptInterpreterPython::Locker::DoFreeLock()
159{
160 ReleasePythonLock ();
161 return true;
162}
163
164bool
165ScriptInterpreterPython::Locker::DoTearDownSession()
166{
167 if (!m_python_interpreter)
168 return false;
169 m_python_interpreter->LeaveSession ();
170 return true;
Enrico Granata91544802011-09-06 19:20:51 +0000171}
172
173ScriptInterpreterPython::Locker::~Locker()
174{
175 if (m_need_session)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000176 DoTearDownSession();
Enrico Granata91544802011-09-06 19:20:51 +0000177 if (m_release_lock)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000178 DoFreeLock();
Enrico Granata91544802011-09-06 19:20:51 +0000179}
180
Greg Clayton63094e02010-06-23 01:19:29 +0000181ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000182 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000183 m_embedded_python_pty (),
184 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +0000185 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000186 m_new_sysout (NULL),
187 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000188 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000189 m_session_is_active (false),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000190 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000191{
192
Greg Clayton7c330d62011-01-27 01:01:10 +0000193 static int g_initialized = false;
194
195 if (!g_initialized)
196 {
197 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000198 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000199 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000200
201 Locker locker(this,
202 ScriptInterpreterPython::Locker::AcquireLock,
203 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Greg Clayton7c330d62011-01-27 01:01:10 +0000204
Caroline Tice0aa2e552011-01-14 00:29:16 +0000205 m_dictionary_name.append("_dict");
206 StreamString run_string;
207 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
208 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000209
Caroline Tice0aa2e552011-01-14 00:29:16 +0000210 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000211
212 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
213 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
214 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
215 // call to Debugger::Terminate is made, the ref-count has the correct value.
216 //
217 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
218 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000219
Caroline Tice0aa2e552011-01-14 00:29:16 +0000220 int old_count = Debugger::TestDebuggerRefCount();
Greg Claytonb302dff2012-02-01 08:09:32 +0000221
Chris Lattner24943d22010-06-08 16:52:24 +0000222
Greg Claytonb302dff2012-02-01 08:09:32 +0000223 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 +0000224 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000225
Enrico Granata8f84cfb2012-02-23 23:10:03 +0000226 // WARNING: temporary code that loads Cocoa formatters - this should be done on a per-platform basis rather than loading the whole set
227 // and letting the individual formatter classes exploit APIs to check whether they can/cannot do their task
228 run_string.Clear();
229 run_string.Printf ("run_one_line (%s, 'import CFString, CFArray, CFDictionary, NSData, NSMachPort, NSSet, NSNotification, NSException, CFBag, CFBinaryHeap, NSURL, NSBundle, NSNumber')", m_dictionary_name.c_str());
230 PyRun_SimpleString (run_string.GetData());
Greg Claytonb302dff2012-02-01 08:09:32 +0000231
Caroline Tice0aa2e552011-01-14 00:29:16 +0000232 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000233
Caroline Tice0aa2e552011-01-14 00:29:16 +0000234 if (new_count > old_count)
235 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000236
Caroline Tice0aa2e552011-01-14 00:29:16 +0000237 run_string.Clear();
Greg Clayton444e35b2011-10-19 18:09:39 +0000238 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000239 interpreter.GetDebugger().GetID());
240 PyRun_SimpleString (run_string.GetData());
241
242 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000243 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000244 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000245 }
Chris Lattner24943d22010-06-08 16:52:24 +0000246}
247
248ScriptInterpreterPython::~ScriptInterpreterPython ()
249{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000250 Debugger &debugger = GetCommandInterpreter().GetDebugger();
251
252 if (m_embedded_thread_input_reader_sp.get() != NULL)
253 {
254 m_embedded_thread_input_reader_sp->SetIsDone (true);
255 m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000256 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
257 m_embedded_thread_input_reader_sp.reset();
258 debugger.PopInputReader (reader_sp);
259 }
260
261 if (m_new_sysout)
262 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000263 Locker locker(this,
264 ScriptInterpreterPython::Locker::AcquireLock,
265 ScriptInterpreterPython::Locker::FreeLock);
266 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000267 }
Chris Lattner24943d22010-06-08 16:52:24 +0000268}
269
Caroline Tice0aa2e552011-01-14 00:29:16 +0000270void
271ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
272{
273 if (fh == NULL)
274 return;
275
276 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000277
Enrico Granatafa1f6172011-10-24 17:22:21 +0000278 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +0000279
280 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000281}
282
283void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000284ScriptInterpreterPython::SaveTerminalState (int fd)
285{
286 // Python mucks with the terminal state of STDIN. If we can possibly avoid
287 // this by setting the file handles up correctly prior to entering the
288 // interpreter we should. For now we save and restore the terminal state
289 // on the input file handle.
290 m_terminal_state.Save (fd, false);
291}
292
293void
294ScriptInterpreterPython::RestoreTerminalState ()
295{
296 // Python mucks with the terminal state of STDIN. If we can possibly avoid
297 // this by setting the file handles up correctly prior to entering the
298 // interpreter we should. For now we save and restore the terminal state
299 // on the input file handle.
300 m_terminal_state.Restore();
301}
302
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000303void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000304ScriptInterpreterPython::LeaveSession ()
305{
Johnny Chen41641f92012-02-29 01:52:13 +0000306 PyObject *sysmod = PyImport_AddModule ("sys");
307 PyObject *sysdict = PyModule_GetDict (sysmod);
308
309 if (m_new_sysout && sysmod && sysdict)
310 {
311 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_old_sysout);
312 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_old_sysout);
313 }
314
Caroline Tice0aa2e552011-01-14 00:29:16 +0000315 m_session_is_active = false;
316}
317
318void
319ScriptInterpreterPython::EnterSession ()
320{
321 // If we have already entered the session, without having officially 'left' it, then there is no need to
322 // 'enter' it again.
323
324 if (m_session_is_active)
325 return;
326
327 m_session_is_active = true;
328
Caroline Tice202f6b82011-01-17 21:55:19 +0000329 StreamString run_string;
330
Greg Clayton2fecc452012-01-28 02:11:02 +0000331 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %llu", m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
332 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)", GetCommandInterpreter().GetDebugger().GetID());
333 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
334 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
335 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
336 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
337 // Make sure STDIN is closed since when we run this as an embedded
338 // interpreter we don't want someone to call "line = sys.stdin.readline()"
339 // and lock up. We don't have multiple windows and when the interpreter is
340 // embedded we don't know we should be feeding input to the embedded
341 // interpreter or to the python sys.stdin. We also don't want to let python
342 // play with the real stdin from this process, so we need to close it...
Greg Clayton3eeaf6e2012-02-03 01:30:30 +0000343 //run_string.PutCString ("; sys.stdin.close()");
Greg Clayton2fecc452012-01-28 02:11:02 +0000344 run_string.PutCString ("')");
Caroline Tice0aa2e552011-01-14 00:29:16 +0000345
Caroline Tice6af65cb2011-05-03 21:21:50 +0000346 PyRun_SimpleString (run_string.GetData());
347 run_string.Clear();
Johnny Chen41641f92012-02-29 01:52:13 +0000348
Caroline Tice0aa2e552011-01-14 00:29:16 +0000349 PyObject *sysmod = PyImport_AddModule ("sys");
350 PyObject *sysdict = PyModule_GetDict (sysmod);
Johnny Chen41641f92012-02-29 01:52:13 +0000351
Greg Clayton2fecc452012-01-28 02:11:02 +0000352 if (m_new_sysout && sysmod && sysdict)
353 {
Johnny Chen41641f92012-02-29 01:52:13 +0000354 m_old_sysout = PyDict_GetItemString(sysdict, "stdout");
355 m_old_syserr = PyDict_GetItemString(sysdict, "stderr");
Greg Clayton2fecc452012-01-28 02:11:02 +0000356 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
357 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
358 }
Johnny Chen41641f92012-02-29 01:52:13 +0000359
Caroline Tice0aa2e552011-01-14 00:29:16 +0000360 if (PyErr_Occurred())
361 PyErr_Clear ();
Greg Clayton2fecc452012-01-28 02:11:02 +0000362}
Caroline Tice0aa2e552011-01-14 00:29:16 +0000363
Johnny Chen60dde642010-07-30 22:33:14 +0000364bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000365ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000366{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000367 if (!m_valid_session)
368 return false;
369
Caroline Tice4a461da2011-01-14 21:09:29 +0000370 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
371 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
372 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
373 // method to pass the command string directly down to Python.
374
Enrico Granatafa1f6172011-10-24 17:22:21 +0000375 Locker locker(this,
376 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
377 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000378
379 bool success = false;
380
Greg Clayton63094e02010-06-23 01:19:29 +0000381 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000382 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000383 // Find the correct script interpreter dictionary in the main module.
384 PyObject *main_mod = PyImport_AddModule ("__main__");
385 PyObject *script_interpreter_dict = NULL;
386 if (main_mod != NULL)
387 {
388 PyObject *main_dict = PyModule_GetDict (main_mod);
389 if ((main_dict != NULL)
390 && PyDict_Check (main_dict))
391 {
392 // Go through the main dictionary looking for the correct python script interpreter dictionary
393 PyObject *key, *value;
394 Py_ssize_t pos = 0;
395
396 while (PyDict_Next (main_dict, &pos, &key, &value))
397 {
398 // We have stolen references to the key and value objects in the dictionary; we need to increment
399 // them now so that Python's garbage collector doesn't collect them out from under us.
400 Py_INCREF (key);
401 Py_INCREF (value);
402 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
403 {
404 script_interpreter_dict = value;
405 break;
406 }
407 }
408 }
409
410 if (script_interpreter_dict != NULL)
411 {
412 PyObject *pfunc = NULL;
413 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
414 if (pmod != NULL)
415 {
416 PyObject *pmod_dict = PyModule_GetDict (pmod);
417 if ((pmod_dict != NULL)
418 && PyDict_Check (pmod_dict))
419 {
420 PyObject *key, *value;
421 Py_ssize_t pos = 0;
422
423 while (PyDict_Next (pmod_dict, &pos, &key, &value))
424 {
425 Py_INCREF (key);
426 Py_INCREF (value);
427 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
428 {
429 pfunc = value;
430 break;
431 }
432 }
433
434 PyObject *string_arg = PyString_FromString (command);
435 if (pfunc && string_arg && PyCallable_Check (pfunc))
436 {
437 PyObject *pargs = PyTuple_New (2);
438 if (pargs != NULL)
439 {
440 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
441 PyTuple_SetItem (pargs, 1, string_arg);
442 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
443 Py_DECREF (pargs);
444 if (pvalue != NULL)
445 {
446 Py_DECREF (pvalue);
447 success = true;
448 }
449 else if (PyErr_Occurred ())
450 {
451 PyErr_Print();
452 PyErr_Clear();
453 }
454 }
455 }
456 }
457 }
458 Py_INCREF (script_interpreter_dict);
459 }
460 }
Greg Clayton63094e02010-06-23 01:19:29 +0000461
Caroline Tice4a461da2011-01-14 21:09:29 +0000462 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000463 return true;
464
465 // The one-liner failed. Append the error message.
466 if (result)
467 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
468 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000469 }
Johnny Chen60dde642010-07-30 22:33:14 +0000470
471 if (result)
472 result->AppendError ("empty command passed to python\n");
473 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000474}
475
Chris Lattner24943d22010-06-08 16:52:24 +0000476size_t
477ScriptInterpreterPython::InputReaderCallback
478(
479 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000480 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000481 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000482 const char *bytes,
483 size_t bytes_len
484)
485{
Caroline Tice2ade6112010-11-10 19:18:14 +0000486 lldb::thread_t embedded_interpreter_thread;
487 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
488
Chris Lattner24943d22010-06-08 16:52:24 +0000489 if (baton == NULL)
490 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000491
492 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000493
Caroline Tice0aa2e552011-01-14 00:29:16 +0000494 if (script_interpreter->m_script_lang != eScriptLanguagePython)
495 return 0;
496
Caroline Tice892fadd2011-06-16 16:27:19 +0000497 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
498 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
499
Chris Lattner24943d22010-06-08 16:52:24 +0000500 switch (notification)
501 {
502 case eInputReaderActivate:
503 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000504 if (!batch_mode)
505 {
506 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
507 out_stream->Flush();
508 }
Greg Clayton58928562011-02-09 01:08:52 +0000509
Chris Lattner24943d22010-06-08 16:52:24 +0000510 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000511 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
512 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000513 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000514
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000515 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000516
Caroline Tice202f6b82011-01-17 21:55:19 +0000517 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000518 ScriptInterpreterPython::Locker locker(script_interpreter,
519 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
520 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000521 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000522
Caroline Tice2ade6112010-11-10 19:18:14 +0000523 char error_str[1024];
524 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
525 sizeof(error_str)))
526 {
527 if (log)
528 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
529 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
530 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
531 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
532 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000533 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000534 {
535 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000536 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000537 Error detach_error;
538 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
539 }
540 else
541 {
542 if (log)
543 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
544 reader.SetIsDone (true);
545 }
546 }
547 else
548 {
549 if (log)
550 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
551 reader.SetIsDone (true);
552 }
Chris Lattner24943d22010-06-08 16:52:24 +0000553 }
554 break;
555
556 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000557 // When another input reader is pushed, don't leave the session...
558 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000559 break;
560
561 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000562 {
Greg Claytona1cec242012-01-06 00:47:38 +0000563 // Don't try and acquire the interpreter lock here because code like
564 // this:
565 //
566 // (lldb) script
567 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
568 //
569 // This will cause the process to run. The interpreter lock is taken
570 // by the input reader for the "script" command. If we try and acquire
571 // the lock here, when the process runs it might deactivate this input
572 // reader (if STDIN is hooked up to the inferior process) and
573 // reactivate it when the process stops which will deadlock.
574 //ScriptInterpreterPython::Locker locker(script_interpreter,
575 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
576 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000577 }
Chris Lattner24943d22010-06-08 16:52:24 +0000578 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000579
Caroline Tice4a348082011-05-02 20:41:46 +0000580 case eInputReaderAsynchronousOutputWritten:
581 break;
582
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000583 case eInputReaderInterrupt:
584 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
585 break;
586
587 case eInputReaderEndOfFile:
588 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
589 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000590
591 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000592 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000593 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000594 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000595 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000596 bytes_len);
597 if (bytes && bytes_len)
598 {
599 if ((int) bytes[0] == 4)
600 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
601 else
602 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
603 }
604 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000605 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000606 else
607 {
608 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000609 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000610 bytes,
611 bytes_len);
612 reader.SetIsDone (true);
613 }
614
Chris Lattner24943d22010-06-08 16:52:24 +0000615 break;
616
617 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000618 script_interpreter->LeaveSession ();
619
Chris Lattner24943d22010-06-08 16:52:24 +0000620 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000621 if (log)
622 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000623
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000624 script_interpreter->RestoreTerminalState ();
625
Caroline Tice2ade6112010-11-10 19:18:14 +0000626 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000627 break;
628 }
629
630 return bytes_len;
631}
632
633
634void
Greg Clayton238c0a12010-09-18 01:14:36 +0000635ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000636{
637 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
638
Caroline Tice0aa2e552011-01-14 00:29:16 +0000639 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000640
641 // At the moment, the only time the debugger does not have an input file handle is when this is called
642 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
643 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
644 // do it.
645
Greg Clayton58928562011-02-09 01:08:52 +0000646 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000647 return;
648
Greg Clayton63094e02010-06-23 01:19:29 +0000649 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000650 if (reader_sp)
651 {
652 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
653 this, // baton
654 eInputReaderGranularityLine, // token size, to pass to callback function
655 NULL, // end token
656 NULL, // prompt
657 true)); // echo input
658
659 if (error.Success())
660 {
Greg Clayton63094e02010-06-23 01:19:29 +0000661 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000662 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000663 }
664 }
665}
666
667bool
668ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000669 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000670 void *ret_value)
671{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000672
Enrico Granatafa1f6172011-10-24 17:22:21 +0000673 Locker locker(this,
674 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
675 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000676
Chris Lattner24943d22010-06-08 16:52:24 +0000677 PyObject *py_return = NULL;
678 PyObject *mainmod = PyImport_AddModule ("__main__");
679 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000680 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000681 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000682 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000683 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000684 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000685
686 if (PyDict_Check (globals))
687 {
688 PyObject *key, *value;
689 Py_ssize_t pos = 0;
690
691 int i = 0;
692 while (PyDict_Next (globals, &pos, &key, &value))
693 {
694 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
695 // so that Python's garbage collector doesn't collect them out from under us.
696 Py_INCREF (key);
697 Py_INCREF (value);
698 char *c_str = PyString_AsString (key);
699 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
700 locals = value;
701 ++i;
702 }
703 }
Chris Lattner24943d22010-06-08 16:52:24 +0000704
Caroline Tice0aa2e552011-01-14 00:29:16 +0000705 if (locals == NULL)
706 {
707 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
708 should_decrement_locals = true;
709 }
710
711 if (locals == NULL)
712 {
713 locals = globals;
714 should_decrement_locals = false;
715 }
716
717 py_error = PyErr_Occurred();
718 if (py_error != NULL)
719 PyErr_Clear();
720
Chris Lattner24943d22010-06-08 16:52:24 +0000721 if (in_string != NULL)
722 {
723 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
724 if (py_return == NULL)
725 {
726 py_error = PyErr_Occurred ();
727 if (py_error != NULL)
728 PyErr_Clear ();
729
730 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
731 }
732
Caroline Tice0aa2e552011-01-14 00:29:16 +0000733 if (locals != NULL
734 && should_decrement_locals)
735 Py_DECREF (locals);
736
Chris Lattner24943d22010-06-08 16:52:24 +0000737 if (py_return != NULL)
738 {
739 switch (return_type)
740 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000741 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000742 {
743 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000744 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000745 break;
746 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000747 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000748 {
749 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000750 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000751 break;
752 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000753 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000754 {
755 const char format[2] = "b";
756 success = PyArg_Parse (py_return, format, (bool *) ret_value);
757 break;
758 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000759 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000760 {
761 const char format[2] = "h";
762 success = PyArg_Parse (py_return, format, (short *) ret_value);
763 break;
764 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000765 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000766 {
767 const char format[2] = "H";
768 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
769 break;
770 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000771 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000772 {
773 const char format[2] = "i";
774 success = PyArg_Parse (py_return, format, (int *) ret_value);
775 break;
776 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000777 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000778 {
779 const char format[2] = "I";
780 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
781 break;
782 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000783 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000784 {
785 const char format[2] = "l";
786 success = PyArg_Parse (py_return, format, (long *) ret_value);
787 break;
788 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000789 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000790 {
791 const char format[2] = "k";
792 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
793 break;
794 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000795 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000796 {
797 const char format[2] = "L";
798 success = PyArg_Parse (py_return, format, (long long *) ret_value);
799 break;
800 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000801 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000802 {
803 const char format[2] = "K";
804 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
805 break;
806 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000807 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000808 {
809 const char format[2] = "f";
810 success = PyArg_Parse (py_return, format, (float *) ret_value);
811 break;
812 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000813 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000814 {
815 const char format[2] = "d";
816 success = PyArg_Parse (py_return, format, (double *) ret_value);
817 break;
818 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000819 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000820 {
821 const char format[2] = "c";
822 success = PyArg_Parse (py_return, format, (char *) ret_value);
823 break;
824 }
825 default:
826 {}
827 }
828 Py_DECREF (py_return);
829 if (success)
830 ret_success = true;
831 else
832 ret_success = false;
833 }
834 }
835
836 py_error = PyErr_Occurred();
837 if (py_error != NULL)
838 {
839 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
840 PyErr_Print ();
841 PyErr_Clear();
842 ret_success = false;
843 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000844
Chris Lattner24943d22010-06-08 16:52:24 +0000845 return ret_success;
846}
847
848bool
849ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
850{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000851
852
853 Locker locker(this,
854 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
855 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000856
Chris Lattner24943d22010-06-08 16:52:24 +0000857 bool success = false;
858 PyObject *py_return = NULL;
859 PyObject *mainmod = PyImport_AddModule ("__main__");
860 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000861 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000862 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000863 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000864
Caroline Tice0aa2e552011-01-14 00:29:16 +0000865 if (PyDict_Check (globals))
866 {
867 PyObject *key, *value;
868 Py_ssize_t pos = 0;
869
870 while (PyDict_Next (globals, &pos, &key, &value))
871 {
872 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
873 // so that Python's garbage collector doesn't collect them out from under us.
874 Py_INCREF (key);
875 Py_INCREF (value);
876 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
877 locals = value;
878 }
879 }
880
881 if (locals == NULL)
882 {
883 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
884 should_decrement_locals = true;
885 }
886
887 if (locals == NULL)
888 {
889 locals = globals;
890 should_decrement_locals = false;
891 }
892
893 py_error = PyErr_Occurred();
894 if (py_error != NULL)
895 PyErr_Clear();
896
Chris Lattner24943d22010-06-08 16:52:24 +0000897 if (in_string != NULL)
898 {
899 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
900 if (compiled_node)
901 {
902 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
903 if (compiled_code)
904 {
905 py_return = PyEval_EvalCode (compiled_code, globals, locals);
906 if (py_return != NULL)
907 {
908 success = true;
909 Py_DECREF (py_return);
910 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000911 if (locals && should_decrement_locals)
912 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000913 }
914 }
915 }
916
917 py_error = PyErr_Occurred ();
918 if (py_error != NULL)
919 {
920 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
921 PyErr_Print ();
922 PyErr_Clear();
923 success = false;
924 }
925
926 return success;
927}
928
929static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
930
931size_t
932ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
933(
934 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000935 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000936 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000937 const char *bytes,
938 size_t bytes_len
939)
940{
Caroline Tice892fadd2011-06-16 16:27:19 +0000941 static StringList commands_in_progress;
942
943 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
944 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
945
Chris Lattner24943d22010-06-08 16:52:24 +0000946 switch (notification)
947 {
948 case eInputReaderActivate:
949 {
950 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +0000951 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +0000952 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000953 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000954 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +0000955 out_stream->Printf ("%s", reader.GetPrompt());
956 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +0000957 }
958 }
959 break;
960
961 case eInputReaderDeactivate:
962 break;
963
964 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +0000965 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000966 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000967 out_stream->Printf ("%s", reader.GetPrompt());
968 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +0000969 }
Chris Lattner24943d22010-06-08 16:52:24 +0000970 break;
971
Caroline Tice4a348082011-05-02 20:41:46 +0000972 case eInputReaderAsynchronousOutputWritten:
973 break;
974
Chris Lattner24943d22010-06-08 16:52:24 +0000975 case eInputReaderGotToken:
976 {
977 std::string temp_string (bytes, bytes_len);
978 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +0000979 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000980 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000981 out_stream->Printf ("%s", reader.GetPrompt());
982 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +0000983 }
Chris Lattner24943d22010-06-08 16:52:24 +0000984 }
985 break;
986
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000987 case eInputReaderEndOfFile:
988 case eInputReaderInterrupt:
989 // Control-c (SIGINT) & control-d both mean finish & exit.
990 reader.SetIsDone(true);
991
992 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
993 if (notification == eInputReaderInterrupt)
994 commands_in_progress.Clear();
995
996 // Fall through here...
997
Chris Lattner24943d22010-06-08 16:52:24 +0000998 case eInputReaderDone:
999 {
1000 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1001 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1002 data_ap->user_source.AppendList (commands_in_progress);
1003 if (data_ap.get())
1004 {
Greg Clayton63094e02010-06-23 01:19:29 +00001005 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001006 if (interpreter)
1007 {
1008 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1009 data_ap->script_source))
1010 {
1011 if (data_ap->script_source.GetSize() == 1)
1012 {
1013 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1014 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1015 }
1016 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001017 else if (!batch_mode)
1018 {
1019 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1020 out_stream->Flush();
1021 }
Chris Lattner24943d22010-06-08 16:52:24 +00001022 }
1023 else
1024 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001025 if (!batch_mode)
1026 {
1027 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1028 out_stream->Flush();
1029 }
Chris Lattner24943d22010-06-08 16:52:24 +00001030 }
1031 }
1032 }
1033 break;
1034
1035 }
1036
1037 return bytes_len;
1038}
1039
1040void
Greg Clayton238c0a12010-09-18 01:14:36 +00001041ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001042 CommandReturnObject &result)
1043{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001044 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1045
Greg Clayton63094e02010-06-23 01:19:29 +00001046 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001047
1048 if (reader_sp)
1049 {
1050 Error err = reader_sp->Initialize (
1051 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1052 bp_options, // baton
1053 eInputReaderGranularityLine, // token size, for feeding data to callback function
1054 "DONE", // end token
1055 "> ", // prompt
1056 true); // echo input
1057
1058 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001059 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001060 else
1061 {
1062 result.AppendError (err.AsCString());
1063 result.SetStatus (eReturnStatusFailed);
1064 }
1065 }
1066 else
1067 {
1068 result.AppendError("out of memory");
1069 result.SetStatus (eReturnStatusFailed);
1070 }
1071}
1072
Johnny Chen3e0571b2010-09-11 00:23:59 +00001073// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001074void
Greg Clayton238c0a12010-09-18 01:14:36 +00001075ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001076 const char *oneliner)
1077{
1078 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1079
1080 // It's necessary to set both user_source and script_source to the oneliner.
1081 // The former is used to generate callback description (as in breakpoint command list)
1082 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001083
Johnny Chend1c2dca2010-09-10 18:21:10 +00001084 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001085
Caroline Tice5136f942010-09-27 21:35:15 +00001086 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1087 {
1088 if (data_ap->script_source.GetSize() == 1)
1089 {
1090 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1091 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1092 }
1093 }
1094
Johnny Chend1c2dca2010-09-10 18:21:10 +00001095 return;
1096}
1097
Chris Lattner24943d22010-06-08 16:52:24 +00001098bool
1099ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1100{
1101 // Convert StringList to one long, newline delimited, const char *.
1102 std::string function_def_string;
1103
1104 int num_lines = function_def.GetSize();
1105
1106 for (int i = 0; i < num_lines; ++i)
1107 {
1108 function_def_string.append (function_def.GetStringAtIndex(i));
1109 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1110 function_def_string.append ("\n");
1111
1112 }
1113
1114 return ExecuteMultipleLines (function_def_string.c_str());
1115}
1116
Enrico Granataf7a9b142011-07-15 02:26:42 +00001117// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1118// use this code to generate their functions
1119bool
1120ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1121{
1122 int num_lines = input.GetSize ();
1123 if (num_lines == 0)
1124 return false;
1125 StreamString sstr;
1126 StringList auto_generated_function;
1127 auto_generated_function.AppendString (signature.c_str());
1128 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1129 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1130 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1131 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1132 // global dictionary.
1133
1134 // Wrap everything up inside the function, increasing the indentation.
1135
1136 for (int i = 0; i < num_lines; ++i)
1137 {
1138 sstr.Clear ();
1139 sstr.Printf (" %s", input.GetStringAtIndex (i));
1140 auto_generated_function.AppendString (sstr.GetData());
1141 }
1142 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1143 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1144 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1145 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1146
1147 // Verify that the results are valid Python.
1148
1149 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1150 return false;
1151
1152 return true;
1153
1154}
1155
1156// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1157// given to generated functions, of course)
1158bool
Enrico Granata16376ed2012-02-15 02:34:21 +00001159ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001160{
1161 static int num_created_functions = 0;
1162 user_input.RemoveBlankLines ();
1163 int num_lines = user_input.GetSize ();
1164 StreamString sstr;
1165
1166 // Check to see if we have any data; if not, just return.
1167 if (user_input.GetSize() == 0)
1168 return false;
1169
1170 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1171 // ValueObject as parameter to the function.
1172
Enrico Granata16376ed2012-02-15 02:34:21 +00001173 if (!name_token)
1174 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1175 else
1176 sstr.Printf ("lldb_gen_python_type_print_func_%p", name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001177 ++num_created_functions;
1178 std::string auto_generated_function_name = sstr.GetData();
1179
1180 sstr.Clear();
1181 StringList auto_generated_function;
1182
1183 // Create the function name & definition string.
1184
1185 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1186 auto_generated_function.AppendString (sstr.GetData());
1187
1188 // Pre-pend code for setting up the session dictionary.
1189
1190 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1191 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1192 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1193 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1194 // global dictionary.
1195
1196 // Wrap everything up inside the function, increasing the indentation.
1197
1198 for (int i = 0; i < num_lines; ++i)
1199 {
1200 sstr.Clear ();
1201 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1202 auto_generated_function.AppendString (sstr.GetData());
1203 }
1204
1205 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1206 // got written to the values in the global dictionary, not the session dictionary).
1207
1208 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1209 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1210 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1211 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1212
1213 // Verify that the results are valid Python.
1214
1215 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1216 return false;
1217
1218 // Store the name of the auto-generated function to be called.
1219
1220 output.AppendString (auto_generated_function_name.c_str());
1221 return true;
1222}
1223
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001224bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001225ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, StringList &output)
1226{
1227 static int num_created_functions = 0;
1228 user_input.RemoveBlankLines ();
1229 int num_lines = user_input.GetSize ();
1230 StreamString sstr;
1231
1232 // Check to see if we have any data; if not, just return.
1233 if (user_input.GetSize() == 0)
1234 return false;
1235
1236 // 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 +00001237 // required data as parameters to the function.
Enrico Granatac2a28252011-08-16 16:49:25 +00001238
1239 sstr.Printf ("lldb_autogen_python_cmd_alias_func_%d", num_created_functions);
1240 ++num_created_functions;
1241 std::string auto_generated_function_name = sstr.GetData();
1242
1243 sstr.Clear();
1244 StringList auto_generated_function;
1245
1246 // Create the function name & definition string.
1247
Enrico Granata271568f2011-09-09 01:41:30 +00001248 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001249 auto_generated_function.AppendString (sstr.GetData());
1250
1251 // Pre-pend code for setting up the session dictionary.
1252
1253 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1254 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1255 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1256 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1257 // global dictionary.
1258
1259 // Wrap everything up inside the function, increasing the indentation.
1260
1261 for (int i = 0; i < num_lines; ++i)
1262 {
1263 sstr.Clear ();
1264 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1265 auto_generated_function.AppendString (sstr.GetData());
1266 }
1267
1268 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1269 // got written to the values in the global dictionary, not the session dictionary).
1270
1271 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1272 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1273 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1274 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1275
1276 // Verify that the results are valid Python.
1277
1278 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1279 return false;
1280
1281 // Store the name of the auto-generated function to be called.
1282
1283 output.AppendString (auto_generated_function_name.c_str());
1284 return true;
1285}
1286
1287
1288bool
Enrico Granata16376ed2012-02-15 02:34:21 +00001289ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output, void* name_token)
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001290{
1291 static int num_created_classes = 0;
1292 user_input.RemoveBlankLines ();
1293 int num_lines = user_input.GetSize ();
1294 StreamString sstr;
1295
1296 // Check to see if we have any data; if not, just return.
1297 if (user_input.GetSize() == 0)
1298 return false;
1299
1300 // Wrap all user input into a Python class
1301
Enrico Granata16376ed2012-02-15 02:34:21 +00001302 if (!name_token)
1303 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1304 else
1305 sstr.Printf ("lldb_gen_python_type_synth_class_%p", name_token);
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001306 ++num_created_classes;
1307 std::string auto_generated_class_name = sstr.GetData();
1308
1309 sstr.Clear();
1310 StringList auto_generated_class;
1311
1312 // Create the function name & definition string.
1313
1314 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1315 auto_generated_class.AppendString (sstr.GetData());
1316
1317 // Wrap everything up inside the class, increasing the indentation.
1318
1319 for (int i = 0; i < num_lines; ++i)
1320 {
1321 sstr.Clear ();
1322 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1323 auto_generated_class.AppendString (sstr.GetData());
1324 }
1325
1326
1327 // Verify that the results are valid Python.
1328 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1329 // (TODO: rename that method to ExportDefinitionToInterpreter)
1330 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1331 return false;
1332
1333 // Store the name of the auto-generated class
1334
1335 output.AppendString (auto_generated_class_name.c_str());
1336 return true;
1337}
1338
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001339void*
1340ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1341 lldb::ValueObjectSP valobj)
1342{
1343 if (class_name.empty())
1344 return NULL;
1345
1346 if (!valobj.get())
1347 return NULL;
1348
Greg Claytonb4d7fc02012-02-17 07:49:44 +00001349 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1350 Target *target = exe_ctx.GetTargetPtr();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001351
1352 if (!target)
1353 return NULL;
1354
1355 Debugger &debugger = target->GetDebugger();
1356 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1357 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1358
1359 if (!script_interpreter)
1360 return NULL;
1361
1362 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001363
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001364 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001365 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001366 ret_val = g_swig_synthetic_script (class_name,
1367 python_interpreter->m_dictionary_name.c_str(),
1368 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001369 }
1370
1371 return ret_val;
1372}
1373
Enrico Granataf7a9b142011-07-15 02:26:42 +00001374bool
Enrico Granata16376ed2012-02-15 02:34:21 +00001375ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001376{
Enrico Granata16376ed2012-02-15 02:34:21 +00001377 StringList input;
1378 input.SplitIntoLines(oneliner, strlen(oneliner));
1379 return GenerateTypeScriptFunction(input, output, name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001380}
1381
Chris Lattner24943d22010-06-08 16:52:24 +00001382bool
Enrico Granata16376ed2012-02-15 02:34:21 +00001383ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, StringList &output, void* name_token)
1384{
1385 StringList input;
1386 input.SplitIntoLines(oneliner, strlen(oneliner));
1387 return GenerateTypeSynthClass(input, output, name_token);
1388}
1389
1390
1391bool
Chris Lattner24943d22010-06-08 16:52:24 +00001392ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1393{
1394 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001395 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001396 int num_lines = user_input.GetSize ();
1397 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001398
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001399 // Check to see if we have any data; if not, just return.
1400 if (user_input.GetSize() == 0)
1401 return false;
1402
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001403 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1404 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001405
Caroline Ticeb447e842010-09-21 19:25:28 +00001406
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001407 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1408 ++num_created_functions;
1409 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001410
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001411 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001412 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001413
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001414 // Create the function name & definition string.
1415
Caroline Tice0aa2e552011-01-14 00:29:16 +00001416 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001417 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001418
1419 // Pre-pend code for setting up the session dictionary.
1420
1421 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1422 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1423 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1424 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1425 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001426
1427 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001428
1429 for (int i = 0; i < num_lines; ++i)
1430 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001431 sstr.Clear ();
1432 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1433 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001434 }
Chris Lattner24943d22010-06-08 16:52:24 +00001435
Caroline Tice0aa2e552011-01-14 00:29:16 +00001436 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1437 // got written to the values in the global dictionary, not the session dictionary).
1438
1439 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1440 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1441 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1442 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1443
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001444 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001445
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001446 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001447 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001448 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001449 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001450
1451 // Store the name of the auto-generated function to be called.
1452
1453 callback_data.AppendString (auto_generated_function_name.c_str());
1454 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001455}
1456
Enrico Granataf7a9b142011-07-15 02:26:42 +00001457std::string
1458ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1459 lldb::ValueObjectSP valobj)
1460{
1461
1462 if (!python_function_name || !(*python_function_name))
1463 return "<no function>";
1464
1465 if (!valobj.get())
1466 return "<no object>";
1467
Greg Claytonb4d7fc02012-02-17 07:49:44 +00001468 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1469 Target *target = exe_ctx.GetTargetPtr();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001470
1471 if (!target)
1472 return "<no target>";
1473
1474 Debugger &debugger = target->GetDebugger();
1475 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1476 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1477
1478 if (!script_interpreter)
1479 return "<no python>";
1480
1481 std::string ret_val;
1482
1483 if (python_function_name
1484 && *python_function_name)
1485 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001486 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001487 Locker py_lock(python_interpreter);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001488 ret_val = g_swig_typescript_callback (python_function_name,
1489 python_interpreter->m_dictionary_name.c_str(),
1490 valobj);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001491 }
1492 }
1493 else
1494 return "<no function name>";
1495
1496 return ret_val;
1497
1498}
1499
Greg Clayton5144f382010-10-07 17:14:24 +00001500bool
1501ScriptInterpreterPython::BreakpointCallbackFunction
1502(
1503 void *baton,
1504 StoppointCallbackContext *context,
1505 user_id_t break_id,
1506 user_id_t break_loc_id
1507)
1508{
1509 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1510 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001511
1512 if (!context)
1513 return true;
1514
Greg Claytonf4124de2012-02-21 00:09:25 +00001515 ExecutionContext exe_ctx (context->exe_ctx_ref);
1516 Target *target = exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001517
1518 if (!target)
1519 return true;
1520
1521 Debugger &debugger = target->GetDebugger();
1522 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1523 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1524
1525 if (!script_interpreter)
1526 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001527
1528 if (python_function_name != NULL
1529 && python_function_name[0] != '\0')
1530 {
Greg Claytonf4124de2012-02-21 00:09:25 +00001531 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001532 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001533 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001534 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001535 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1536
1537 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001538 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001539 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001540 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001541 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001542 ret_val = g_swig_breakpoint_callback (python_function_name,
1543 python_interpreter->m_dictionary_name.c_str(),
1544 stop_frame_sp,
1545 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001546 }
1547 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001548 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001549 }
Greg Clayton5144f382010-10-07 17:14:24 +00001550 }
1551 // We currently always true so we stop in case anything goes wrong when
1552 // trying to call the script function
1553 return true;
1554}
Caroline Tice2ade6112010-11-10 19:18:14 +00001555
1556lldb::thread_result_t
1557ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1558{
1559 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1560
1561 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1562
1563 if (log)
1564 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1565
1566 char error_str[1024];
1567 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001568
Enrico Granatafa1f6172011-10-24 17:22:21 +00001569 Locker locker(script_interpreter,
1570 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1571 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1572
1573 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001574 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001575 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001576
Caroline Tice0aa2e552011-01-14 00:29:16 +00001577 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1578 PyRun_SimpleString (run_string.GetData());
1579 run_string.Clear ();
1580
1581 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1582 PyRun_SimpleString (run_string.GetData());
1583 run_string.Clear ();
1584
1585 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1586 PyRun_SimpleString (run_string.GetData());
1587 run_string.Clear ();
1588
1589 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1590 pty_slave_name);
1591 PyRun_SimpleString (run_string.GetData());
1592 run_string.Clear ();
1593
Johnny Chen8054ba32011-03-11 00:28:50 +00001594 // The following call drops into the embedded interpreter loop and stays there until the
1595 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001596
Caroline Ticece207c12011-03-11 00:21:55 +00001597 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001598 // 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 +00001599 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1600
1601 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1602 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1603 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1604 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1605 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1606 // hang (it's happened before).
1607
Caroline Tice9d352ce2011-03-07 23:24:28 +00001608 Py_BEGIN_ALLOW_THREADS
1609 PyGILState_STATE gstate = PyGILState_Ensure();
1610
Caroline Tice0aa2e552011-01-14 00:29:16 +00001611 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1612 PyRun_SimpleString (run_string.GetData());
1613 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001614
Caroline Tice9d352ce2011-03-07 23:24:28 +00001615 PyGILState_Release (gstate);
1616 Py_END_ALLOW_THREADS
1617
Caroline Tice0aa2e552011-01-14 00:29:16 +00001618 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1619 PyRun_SimpleString (run_string.GetData());
1620 run_string.Clear();
1621
1622 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1623 PyRun_SimpleString (run_string.GetData());
1624 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001625
Caroline Tice2ade6112010-11-10 19:18:14 +00001626 }
1627
1628 if (script_interpreter->m_embedded_thread_input_reader_sp)
1629 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1630
1631 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001632
Caroline Tice2ade6112010-11-10 19:18:14 +00001633 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1634 if (log)
1635 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1636
1637
Johnny Chen8054ba32011-03-11 00:28:50 +00001638 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001639 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001640 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1641 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1642 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001643
Caroline Tice2ade6112010-11-10 19:18:14 +00001644 return NULL;
1645}
1646
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001647uint32_t
1648ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1649{
1650 if (!implementor)
1651 return 0;
1652
1653 if (!g_swig_calc_children)
1654 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001655
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001656 uint32_t ret_val = 0;
1657
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001658 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001659 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001660 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001661 }
1662
1663 return ret_val;
1664}
1665
Enrico Granata91544802011-09-06 19:20:51 +00001666lldb::ValueObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001667ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1668{
1669 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001670 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001671
Enrico Granata91544802011-09-06 19:20:51 +00001672 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1673 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001674
Enrico Granata91544802011-09-06 19:20:51 +00001675 void* child_ptr = NULL;
1676 lldb::SBValue* value_sb = NULL;
1677 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001678
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001679 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001680 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +00001681 child_ptr = g_swig_get_child_index (implementor,idx);
1682 if (child_ptr != NULL && child_ptr != Py_None)
1683 {
1684 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1685 if (value_sb == NULL)
1686 Py_XDECREF(child_ptr);
1687 else
1688 ret_val = value_sb->get_sp();
1689 }
1690 else
1691 {
1692 Py_XDECREF(child_ptr);
1693 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001694 }
1695
1696 return ret_val;
1697}
1698
1699int
1700ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1701{
1702 if (!implementor)
1703 return UINT32_MAX;
1704
1705 if (!g_swig_get_index_child)
1706 return UINT32_MAX;
1707
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001708 int ret_val = UINT32_MAX;
1709
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001710 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001711 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001712 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001713 }
1714
1715 return ret_val;
1716}
1717
Enrico Granata979e20d2011-07-29 19:53:35 +00001718void
1719ScriptInterpreterPython::UpdateSynthProviderInstance (void* implementor)
1720{
1721 if (!implementor)
1722 return;
1723
1724 if (!g_swig_update_provider)
1725 return;
1726
Enrico Granata979e20d2011-07-29 19:53:35 +00001727 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001728 Locker py_lock(this);
Enrico Granata979e20d2011-07-29 19:53:35 +00001729 g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001730 }
1731
1732 return;
1733}
1734
Enrico Granatac2a28252011-08-16 16:49:25 +00001735bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001736ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00001737 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00001738 lldb_private::Error& error)
1739{
1740 if (!pathname || !pathname[0])
1741 {
1742 error.SetErrorString("invalid pathname");
1743 return false;
1744 }
1745
1746 if (!g_swig_call_module_init)
1747 {
1748 error.SetErrorString("internal helper function missing");
1749 return false;
1750 }
1751
Greg Clayton13d24fb2012-01-29 20:56:30 +00001752 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granatafa1f6172011-10-24 17:22:21 +00001753
Enrico Granata59df36f2011-10-17 21:45:27 +00001754 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001755 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00001756
1757 FileSpec target_file(pathname, true);
1758
1759 // TODO: would we want to reject any other value?
1760 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1761 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1762 {
1763 error.SetErrorString("invalid pathname");
1764 return false;
1765 }
1766
1767 const char* directory = target_file.GetDirectory().GetCString();
1768 std::string basename(target_file.GetFilename().GetCString());
1769
1770 // now make sure that Python has "directory" in the search path
1771 StreamString command_stream;
1772 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1773 directory,
1774 directory);
Enrico Granatafa1f6172011-10-24 17:22:21 +00001775 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData());
Enrico Granata59df36f2011-10-17 21:45:27 +00001776 if (!syspath_retval)
1777 {
1778 error.SetErrorString("Python sys.path handling failed");
1779 return false;
1780 }
1781
1782 // strip .py or .pyc extension
1783 ConstString extension = target_file.GetFileNameExtension();
1784 if (::strcmp(extension.GetCString(), "py") == 0)
1785 basename.resize(basename.length()-3);
1786 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1787 basename.resize(basename.length()-4);
1788
1789 // check if the module is already import-ed
1790 command_stream.Clear();
1791 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1792 int refcount = 0;
1793 // this call will fail if the module does not exist (because the parameter to it is not a string
1794 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00001795 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
1796 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0);
1797 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00001798 {
1799 error.SetErrorString("module already imported");
1800 return false;
1801 }
1802
1803 // now actually do the import
1804 command_stream.Clear();
1805 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafa1f6172011-10-24 17:22:21 +00001806 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL);
Enrico Granata59df36f2011-10-17 21:45:27 +00001807 if (!import_retval)
1808 {
1809 error.SetErrorString("Python import statement failed");
1810 return false;
1811 }
1812
Enrico Granata16376ed2012-02-15 02:34:21 +00001813 // call __lldb_init_module(debugger,dict)
Enrico Granata59df36f2011-10-17 21:45:27 +00001814 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001815 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001816 debugger_sp))
1817 {
Enrico Granata16376ed2012-02-15 02:34:21 +00001818 error.SetErrorString("calling __lldb_init_module failed");
Enrico Granata59df36f2011-10-17 21:45:27 +00001819 return false;
1820 }
1821 return true;
1822 }
1823}
1824
Enrico Granata6010ace2011-11-07 22:57:04 +00001825ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
1826 ScriptedCommandSynchronicity synchro) :
1827 m_debugger_sp(debugger_sp),
1828 m_synch_wanted(synchro),
1829 m_old_asynch(debugger_sp->GetAsyncExecution())
1830{
1831 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
1832 m_debugger_sp->SetAsyncExecution(false);
1833 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
1834 m_debugger_sp->SetAsyncExecution(true);
1835}
1836
1837ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
1838{
1839 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
1840 m_debugger_sp->SetAsyncExecution(m_old_asynch);
1841}
1842
Enrico Granata59df36f2011-10-17 21:45:27 +00001843bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001844ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1845 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00001846 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001847 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001848 Error& error)
1849{
1850 if (!impl_function)
1851 {
1852 error.SetErrorString("no function to execute");
1853 return false;
1854 }
1855
1856 if (!g_swig_call_command)
1857 {
1858 error.SetErrorString("no helper function to run scripted commands");
1859 return false;
1860 }
1861
Greg Clayton13d24fb2012-01-29 20:56:30 +00001862 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata6010ace2011-11-07 22:57:04 +00001863
1864 if (!debugger_sp.get())
1865 {
1866 error.SetErrorString("invalid Debugger pointer");
1867 return false;
1868 }
Enrico Granatac2a28252011-08-16 16:49:25 +00001869
1870 bool ret_val;
1871
1872 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00001873
Enrico Granatac2a28252011-08-16 16:49:25 +00001874 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001875 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00001876 SynchronicityHandler synch_handler(debugger_sp,
1877 synchronicity);
1878
Enrico Granatac2a28252011-08-16 16:49:25 +00001879 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001880 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00001881 debugger_sp,
1882 args,
1883 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001884 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001885 }
Enrico Granata6010ace2011-11-07 22:57:04 +00001886
Enrico Granatac2a28252011-08-16 16:49:25 +00001887 if (!ret_val)
1888 error.SetErrorString(err_msg.c_str());
1889 else
1890 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00001891
Enrico Granatac2a28252011-08-16 16:49:25 +00001892 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00001893}
1894
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001895// in Python, a special attribute __doc__ contains the docstring
1896// for an object (function, method, class, ...) if any is defined
1897// Otherwise, the attribute's value is None
1898std::string
1899ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1900{
1901 std::string command(item);
1902 command += ".__doc__";
1903
1904 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1905
1906 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001907 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001908 &result_ptr) && result_ptr)
1909 {
1910 return std::string(result_ptr);
1911 }
1912 else
1913 return std::string("");
1914}
Caroline Tice2ade6112010-11-10 19:18:14 +00001915
Caroline Tice0aa2e552011-01-14 00:29:16 +00001916void
Greg Claytone86cbb92011-03-22 01:14:58 +00001917ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00001918 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001919 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
1920 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
1921 SWIGPythonCalculateNumChildren python_swig_calc_children,
1922 SWIGPythonGetChildAtIndex python_swig_get_child_index,
1923 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
Enrico Granata979e20d2011-07-29 19:53:35 +00001924 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue,
Enrico Granatac2a28252011-08-16 16:49:25 +00001925 SWIGPythonUpdateSynthProviderInstance python_swig_update_provider,
Enrico Granata59df36f2011-10-17 21:45:27 +00001926 SWIGPythonCallCommand python_swig_call_command,
1927 SWIGPythonCallModuleInit python_swig_call_mod_init)
Greg Claytone86cbb92011-03-22 01:14:58 +00001928{
1929 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001930 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1931 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001932 g_swig_synthetic_script = python_swig_synthetic_script;
1933 g_swig_calc_children = python_swig_calc_children;
1934 g_swig_get_child_index = python_swig_get_child_index;
1935 g_swig_get_index_child = python_swig_get_index_child;
1936 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Enrico Granata979e20d2011-07-29 19:53:35 +00001937 g_swig_update_provider = python_swig_update_provider;
Enrico Granatac2a28252011-08-16 16:49:25 +00001938 g_swig_call_command = python_swig_call_command;
Enrico Granata59df36f2011-10-17 21:45:27 +00001939 g_swig_call_module_init = python_swig_call_mod_init;
Greg Claytone86cbb92011-03-22 01:14:58 +00001940}
1941
1942void
1943ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001944{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001945 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1946
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001947 // Python will muck with STDIN terminal state, so save off any current TTY
1948 // settings so we can restore them.
1949 TerminalState stdin_tty_state;
1950 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001951
Caroline Tice9d352ce2011-03-07 23:24:28 +00001952 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001953 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001954
Greg Claytone86cbb92011-03-22 01:14:58 +00001955 // Initialize SWIG after setting up python
1956 assert (g_swig_init_callback != NULL);
1957 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001958
1959 // Update the path python uses to search for modules to include the current directory.
1960
Caroline Ticed4d92832011-06-13 21:33:00 +00001961 PyRun_SimpleString ("import sys");
1962 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001963
1964 // Find the module that owns this code and use that path we get to
1965 // set the sys.path appropriately.
1966
1967 FileSpec file_spec;
1968 char python_dir_path[PATH_MAX];
1969 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1970 {
1971 std::string python_path("sys.path.insert(0,\"");
1972 size_t orig_len = python_path.length();
1973 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1974 {
1975 python_path.append (python_dir_path);
1976 python_path.append ("\")");
1977 PyRun_SimpleString (python_path.c_str());
1978 python_path.resize (orig_len);
1979 }
1980
1981 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1982 {
1983 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1984 {
1985 python_path.append (python_dir_path);
1986 python_path.append ("\")");
1987 PyRun_SimpleString (python_path.c_str());
1988 python_path.resize (orig_len);
1989 }
1990 }
1991 }
1992
Jim Ingham4dfa5112011-08-22 19:10:09 +00001993 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001994
Caroline Ticed4d92832011-06-13 21:33:00 +00001995 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001996
Caroline Ticed4d92832011-06-13 21:33:00 +00001997 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1998 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00001999 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00002000
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002001 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002002}
2003
Greg Claytone86cbb92011-03-22 01:14:58 +00002004//void
2005//ScriptInterpreterPython::Terminate ()
2006//{
2007// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
2008// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
2009// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
2010// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
2011// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
2012// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
2013// // within Py_Finalize, which results in a seg fault.
2014// //
2015// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
2016// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
2017// // process exits).
2018// //
2019//// Py_Finalize ();
2020//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00002021
2022#endif // #ifdef LLDB_DISABLE_PYTHON