blob: c584a819aa7c3b400793ea5fe1cf1e93ceb1c116 [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{
306 m_session_is_active = false;
307}
308
309void
310ScriptInterpreterPython::EnterSession ()
311{
312 // If we have already entered the session, without having officially 'left' it, then there is no need to
313 // 'enter' it again.
314
315 if (m_session_is_active)
316 return;
317
318 m_session_is_active = true;
319
Caroline Tice202f6b82011-01-17 21:55:19 +0000320 StreamString run_string;
321
Greg Clayton2fecc452012-01-28 02:11:02 +0000322 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %llu", m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
323 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)", GetCommandInterpreter().GetDebugger().GetID());
324 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
325 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
326 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
327 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
328 // Make sure STDIN is closed since when we run this as an embedded
329 // interpreter we don't want someone to call "line = sys.stdin.readline()"
330 // and lock up. We don't have multiple windows and when the interpreter is
331 // embedded we don't know we should be feeding input to the embedded
332 // interpreter or to the python sys.stdin. We also don't want to let python
333 // play with the real stdin from this process, so we need to close it...
Greg Clayton3eeaf6e2012-02-03 01:30:30 +0000334 //run_string.PutCString ("; sys.stdin.close()");
Greg Clayton2fecc452012-01-28 02:11:02 +0000335 run_string.PutCString ("')");
Caroline Tice0aa2e552011-01-14 00:29:16 +0000336
Caroline Tice6af65cb2011-05-03 21:21:50 +0000337 PyRun_SimpleString (run_string.GetData());
338 run_string.Clear();
339
Caroline Tice0aa2e552011-01-14 00:29:16 +0000340 PyObject *sysmod = PyImport_AddModule ("sys");
341 PyObject *sysdict = PyModule_GetDict (sysmod);
342
Greg Clayton2fecc452012-01-28 02:11:02 +0000343 if (m_new_sysout && sysmod && sysdict)
344 {
345 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
346 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
347 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000348
349 if (PyErr_Occurred())
350 PyErr_Clear ();
Greg Clayton2fecc452012-01-28 02:11:02 +0000351}
Caroline Tice0aa2e552011-01-14 00:29:16 +0000352
Johnny Chen60dde642010-07-30 22:33:14 +0000353bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000354ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000355{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000356 if (!m_valid_session)
357 return false;
358
Caroline Tice4a461da2011-01-14 21:09:29 +0000359 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
360 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
361 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
362 // method to pass the command string directly down to Python.
363
Enrico Granatafa1f6172011-10-24 17:22:21 +0000364 Locker locker(this,
365 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
366 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000367
368 bool success = false;
369
Greg Clayton63094e02010-06-23 01:19:29 +0000370 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000371 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000372 // Find the correct script interpreter dictionary in the main module.
373 PyObject *main_mod = PyImport_AddModule ("__main__");
374 PyObject *script_interpreter_dict = NULL;
375 if (main_mod != NULL)
376 {
377 PyObject *main_dict = PyModule_GetDict (main_mod);
378 if ((main_dict != NULL)
379 && PyDict_Check (main_dict))
380 {
381 // Go through the main dictionary looking for the correct python script interpreter dictionary
382 PyObject *key, *value;
383 Py_ssize_t pos = 0;
384
385 while (PyDict_Next (main_dict, &pos, &key, &value))
386 {
387 // We have stolen references to the key and value objects in the dictionary; we need to increment
388 // them now so that Python's garbage collector doesn't collect them out from under us.
389 Py_INCREF (key);
390 Py_INCREF (value);
391 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
392 {
393 script_interpreter_dict = value;
394 break;
395 }
396 }
397 }
398
399 if (script_interpreter_dict != NULL)
400 {
401 PyObject *pfunc = NULL;
402 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
403 if (pmod != NULL)
404 {
405 PyObject *pmod_dict = PyModule_GetDict (pmod);
406 if ((pmod_dict != NULL)
407 && PyDict_Check (pmod_dict))
408 {
409 PyObject *key, *value;
410 Py_ssize_t pos = 0;
411
412 while (PyDict_Next (pmod_dict, &pos, &key, &value))
413 {
414 Py_INCREF (key);
415 Py_INCREF (value);
416 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
417 {
418 pfunc = value;
419 break;
420 }
421 }
422
423 PyObject *string_arg = PyString_FromString (command);
424 if (pfunc && string_arg && PyCallable_Check (pfunc))
425 {
426 PyObject *pargs = PyTuple_New (2);
427 if (pargs != NULL)
428 {
429 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
430 PyTuple_SetItem (pargs, 1, string_arg);
431 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
432 Py_DECREF (pargs);
433 if (pvalue != NULL)
434 {
435 Py_DECREF (pvalue);
436 success = true;
437 }
438 else if (PyErr_Occurred ())
439 {
440 PyErr_Print();
441 PyErr_Clear();
442 }
443 }
444 }
445 }
446 }
447 Py_INCREF (script_interpreter_dict);
448 }
449 }
Greg Clayton63094e02010-06-23 01:19:29 +0000450
Caroline Tice4a461da2011-01-14 21:09:29 +0000451 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000452 return true;
453
454 // The one-liner failed. Append the error message.
455 if (result)
456 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
457 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000458 }
Johnny Chen60dde642010-07-30 22:33:14 +0000459
460 if (result)
461 result->AppendError ("empty command passed to python\n");
462 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000463}
464
Chris Lattner24943d22010-06-08 16:52:24 +0000465size_t
466ScriptInterpreterPython::InputReaderCallback
467(
468 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000469 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000470 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000471 const char *bytes,
472 size_t bytes_len
473)
474{
Caroline Tice2ade6112010-11-10 19:18:14 +0000475 lldb::thread_t embedded_interpreter_thread;
476 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
477
Chris Lattner24943d22010-06-08 16:52:24 +0000478 if (baton == NULL)
479 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000480
481 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000482
Caroline Tice0aa2e552011-01-14 00:29:16 +0000483 if (script_interpreter->m_script_lang != eScriptLanguagePython)
484 return 0;
485
Caroline Tice892fadd2011-06-16 16:27:19 +0000486 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
487 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
488
Chris Lattner24943d22010-06-08 16:52:24 +0000489 switch (notification)
490 {
491 case eInputReaderActivate:
492 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000493 if (!batch_mode)
494 {
495 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
496 out_stream->Flush();
497 }
Greg Clayton58928562011-02-09 01:08:52 +0000498
Chris Lattner24943d22010-06-08 16:52:24 +0000499 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000500 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
501 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000502 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000503
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000504 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000505
Caroline Tice202f6b82011-01-17 21:55:19 +0000506 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000507 ScriptInterpreterPython::Locker locker(script_interpreter,
508 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
509 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000510 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000511
Caroline Tice2ade6112010-11-10 19:18:14 +0000512 char error_str[1024];
513 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
514 sizeof(error_str)))
515 {
516 if (log)
517 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
518 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
519 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
520 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
521 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000522 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000523 {
524 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000525 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000526 Error detach_error;
527 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
528 }
529 else
530 {
531 if (log)
532 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
533 reader.SetIsDone (true);
534 }
535 }
536 else
537 {
538 if (log)
539 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
540 reader.SetIsDone (true);
541 }
Chris Lattner24943d22010-06-08 16:52:24 +0000542 }
543 break;
544
545 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000546 // When another input reader is pushed, don't leave the session...
547 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000548 break;
549
550 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000551 {
Greg Claytona1cec242012-01-06 00:47:38 +0000552 // Don't try and acquire the interpreter lock here because code like
553 // this:
554 //
555 // (lldb) script
556 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
557 //
558 // This will cause the process to run. The interpreter lock is taken
559 // by the input reader for the "script" command. If we try and acquire
560 // the lock here, when the process runs it might deactivate this input
561 // reader (if STDIN is hooked up to the inferior process) and
562 // reactivate it when the process stops which will deadlock.
563 //ScriptInterpreterPython::Locker locker(script_interpreter,
564 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
565 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000566 }
Chris Lattner24943d22010-06-08 16:52:24 +0000567 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000568
Caroline Tice4a348082011-05-02 20:41:46 +0000569 case eInputReaderAsynchronousOutputWritten:
570 break;
571
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000572 case eInputReaderInterrupt:
573 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
574 break;
575
576 case eInputReaderEndOfFile:
577 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
578 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000579
580 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000581 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000582 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000583 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000584 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000585 bytes_len);
586 if (bytes && bytes_len)
587 {
588 if ((int) bytes[0] == 4)
589 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
590 else
591 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
592 }
593 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000594 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000595 else
596 {
597 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000598 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000599 bytes,
600 bytes_len);
601 reader.SetIsDone (true);
602 }
603
Chris Lattner24943d22010-06-08 16:52:24 +0000604 break;
605
606 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000607 script_interpreter->LeaveSession ();
608
Chris Lattner24943d22010-06-08 16:52:24 +0000609 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000610 if (log)
611 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000612
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000613 script_interpreter->RestoreTerminalState ();
614
Caroline Tice2ade6112010-11-10 19:18:14 +0000615 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000616 break;
617 }
618
619 return bytes_len;
620}
621
622
623void
Greg Clayton238c0a12010-09-18 01:14:36 +0000624ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000625{
626 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
627
Caroline Tice0aa2e552011-01-14 00:29:16 +0000628 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000629
630 // At the moment, the only time the debugger does not have an input file handle is when this is called
631 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
632 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
633 // do it.
634
Greg Clayton58928562011-02-09 01:08:52 +0000635 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000636 return;
637
Greg Clayton63094e02010-06-23 01:19:29 +0000638 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000639 if (reader_sp)
640 {
641 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
642 this, // baton
643 eInputReaderGranularityLine, // token size, to pass to callback function
644 NULL, // end token
645 NULL, // prompt
646 true)); // echo input
647
648 if (error.Success())
649 {
Greg Clayton63094e02010-06-23 01:19:29 +0000650 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000651 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000652 }
653 }
654}
655
656bool
657ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000658 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000659 void *ret_value)
660{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000661
Enrico Granatafa1f6172011-10-24 17:22:21 +0000662 Locker locker(this,
663 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
664 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000665
Chris Lattner24943d22010-06-08 16:52:24 +0000666 PyObject *py_return = NULL;
667 PyObject *mainmod = PyImport_AddModule ("__main__");
668 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000669 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000670 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000671 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000672 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000673 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000674
675 if (PyDict_Check (globals))
676 {
677 PyObject *key, *value;
678 Py_ssize_t pos = 0;
679
680 int i = 0;
681 while (PyDict_Next (globals, &pos, &key, &value))
682 {
683 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
684 // so that Python's garbage collector doesn't collect them out from under us.
685 Py_INCREF (key);
686 Py_INCREF (value);
687 char *c_str = PyString_AsString (key);
688 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
689 locals = value;
690 ++i;
691 }
692 }
Chris Lattner24943d22010-06-08 16:52:24 +0000693
Caroline Tice0aa2e552011-01-14 00:29:16 +0000694 if (locals == NULL)
695 {
696 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
697 should_decrement_locals = true;
698 }
699
700 if (locals == NULL)
701 {
702 locals = globals;
703 should_decrement_locals = false;
704 }
705
706 py_error = PyErr_Occurred();
707 if (py_error != NULL)
708 PyErr_Clear();
709
Chris Lattner24943d22010-06-08 16:52:24 +0000710 if (in_string != NULL)
711 {
712 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
713 if (py_return == NULL)
714 {
715 py_error = PyErr_Occurred ();
716 if (py_error != NULL)
717 PyErr_Clear ();
718
719 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
720 }
721
Caroline Tice0aa2e552011-01-14 00:29:16 +0000722 if (locals != NULL
723 && should_decrement_locals)
724 Py_DECREF (locals);
725
Chris Lattner24943d22010-06-08 16:52:24 +0000726 if (py_return != NULL)
727 {
728 switch (return_type)
729 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000730 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000731 {
732 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000733 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000734 break;
735 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000736 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000737 {
738 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000739 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000740 break;
741 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000742 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000743 {
744 const char format[2] = "b";
745 success = PyArg_Parse (py_return, format, (bool *) ret_value);
746 break;
747 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000748 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000749 {
750 const char format[2] = "h";
751 success = PyArg_Parse (py_return, format, (short *) ret_value);
752 break;
753 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000754 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000755 {
756 const char format[2] = "H";
757 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
758 break;
759 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000760 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000761 {
762 const char format[2] = "i";
763 success = PyArg_Parse (py_return, format, (int *) ret_value);
764 break;
765 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000766 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000767 {
768 const char format[2] = "I";
769 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
770 break;
771 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000772 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000773 {
774 const char format[2] = "l";
775 success = PyArg_Parse (py_return, format, (long *) ret_value);
776 break;
777 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000778 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000779 {
780 const char format[2] = "k";
781 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
782 break;
783 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000784 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000785 {
786 const char format[2] = "L";
787 success = PyArg_Parse (py_return, format, (long long *) ret_value);
788 break;
789 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000790 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000791 {
792 const char format[2] = "K";
793 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
794 break;
795 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000796 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000797 {
798 const char format[2] = "f";
799 success = PyArg_Parse (py_return, format, (float *) ret_value);
800 break;
801 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000802 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000803 {
804 const char format[2] = "d";
805 success = PyArg_Parse (py_return, format, (double *) ret_value);
806 break;
807 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000808 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000809 {
810 const char format[2] = "c";
811 success = PyArg_Parse (py_return, format, (char *) ret_value);
812 break;
813 }
814 default:
815 {}
816 }
817 Py_DECREF (py_return);
818 if (success)
819 ret_success = true;
820 else
821 ret_success = false;
822 }
823 }
824
825 py_error = PyErr_Occurred();
826 if (py_error != NULL)
827 {
828 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
829 PyErr_Print ();
830 PyErr_Clear();
831 ret_success = false;
832 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000833
Chris Lattner24943d22010-06-08 16:52:24 +0000834 return ret_success;
835}
836
837bool
838ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
839{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000840
841
842 Locker locker(this,
843 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
844 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000845
Chris Lattner24943d22010-06-08 16:52:24 +0000846 bool success = false;
847 PyObject *py_return = NULL;
848 PyObject *mainmod = PyImport_AddModule ("__main__");
849 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000850 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000851 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000852 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000853
Caroline Tice0aa2e552011-01-14 00:29:16 +0000854 if (PyDict_Check (globals))
855 {
856 PyObject *key, *value;
857 Py_ssize_t pos = 0;
858
859 while (PyDict_Next (globals, &pos, &key, &value))
860 {
861 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
862 // so that Python's garbage collector doesn't collect them out from under us.
863 Py_INCREF (key);
864 Py_INCREF (value);
865 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
866 locals = value;
867 }
868 }
869
870 if (locals == NULL)
871 {
872 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
873 should_decrement_locals = true;
874 }
875
876 if (locals == NULL)
877 {
878 locals = globals;
879 should_decrement_locals = false;
880 }
881
882 py_error = PyErr_Occurred();
883 if (py_error != NULL)
884 PyErr_Clear();
885
Chris Lattner24943d22010-06-08 16:52:24 +0000886 if (in_string != NULL)
887 {
888 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
889 if (compiled_node)
890 {
891 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
892 if (compiled_code)
893 {
894 py_return = PyEval_EvalCode (compiled_code, globals, locals);
895 if (py_return != NULL)
896 {
897 success = true;
898 Py_DECREF (py_return);
899 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000900 if (locals && should_decrement_locals)
901 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000902 }
903 }
904 }
905
906 py_error = PyErr_Occurred ();
907 if (py_error != NULL)
908 {
909 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
910 PyErr_Print ();
911 PyErr_Clear();
912 success = false;
913 }
914
915 return success;
916}
917
918static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
919
920size_t
921ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
922(
923 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000924 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000925 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000926 const char *bytes,
927 size_t bytes_len
928)
929{
Caroline Tice892fadd2011-06-16 16:27:19 +0000930 static StringList commands_in_progress;
931
932 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
933 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
934
Chris Lattner24943d22010-06-08 16:52:24 +0000935 switch (notification)
936 {
937 case eInputReaderActivate:
938 {
939 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +0000940 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +0000941 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000942 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000943 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +0000944 out_stream->Printf ("%s", reader.GetPrompt());
945 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +0000946 }
947 }
948 break;
949
950 case eInputReaderDeactivate:
951 break;
952
953 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +0000954 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000955 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000956 out_stream->Printf ("%s", reader.GetPrompt());
957 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +0000958 }
Chris Lattner24943d22010-06-08 16:52:24 +0000959 break;
960
Caroline Tice4a348082011-05-02 20:41:46 +0000961 case eInputReaderAsynchronousOutputWritten:
962 break;
963
Chris Lattner24943d22010-06-08 16:52:24 +0000964 case eInputReaderGotToken:
965 {
966 std::string temp_string (bytes, bytes_len);
967 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +0000968 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000969 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000970 out_stream->Printf ("%s", reader.GetPrompt());
971 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +0000972 }
Chris Lattner24943d22010-06-08 16:52:24 +0000973 }
974 break;
975
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000976 case eInputReaderEndOfFile:
977 case eInputReaderInterrupt:
978 // Control-c (SIGINT) & control-d both mean finish & exit.
979 reader.SetIsDone(true);
980
981 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
982 if (notification == eInputReaderInterrupt)
983 commands_in_progress.Clear();
984
985 // Fall through here...
986
Chris Lattner24943d22010-06-08 16:52:24 +0000987 case eInputReaderDone:
988 {
989 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
990 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
991 data_ap->user_source.AppendList (commands_in_progress);
992 if (data_ap.get())
993 {
Greg Clayton63094e02010-06-23 01:19:29 +0000994 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +0000995 if (interpreter)
996 {
997 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
998 data_ap->script_source))
999 {
1000 if (data_ap->script_source.GetSize() == 1)
1001 {
1002 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1003 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1004 }
1005 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001006 else if (!batch_mode)
1007 {
1008 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1009 out_stream->Flush();
1010 }
Chris Lattner24943d22010-06-08 16:52:24 +00001011 }
1012 else
1013 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001014 if (!batch_mode)
1015 {
1016 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1017 out_stream->Flush();
1018 }
Chris Lattner24943d22010-06-08 16:52:24 +00001019 }
1020 }
1021 }
1022 break;
1023
1024 }
1025
1026 return bytes_len;
1027}
1028
1029void
Greg Clayton238c0a12010-09-18 01:14:36 +00001030ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001031 CommandReturnObject &result)
1032{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001033 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1034
Greg Clayton63094e02010-06-23 01:19:29 +00001035 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001036
1037 if (reader_sp)
1038 {
1039 Error err = reader_sp->Initialize (
1040 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1041 bp_options, // baton
1042 eInputReaderGranularityLine, // token size, for feeding data to callback function
1043 "DONE", // end token
1044 "> ", // prompt
1045 true); // echo input
1046
1047 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001048 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001049 else
1050 {
1051 result.AppendError (err.AsCString());
1052 result.SetStatus (eReturnStatusFailed);
1053 }
1054 }
1055 else
1056 {
1057 result.AppendError("out of memory");
1058 result.SetStatus (eReturnStatusFailed);
1059 }
1060}
1061
Johnny Chen3e0571b2010-09-11 00:23:59 +00001062// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001063void
Greg Clayton238c0a12010-09-18 01:14:36 +00001064ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001065 const char *oneliner)
1066{
1067 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1068
1069 // It's necessary to set both user_source and script_source to the oneliner.
1070 // The former is used to generate callback description (as in breakpoint command list)
1071 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001072
Johnny Chend1c2dca2010-09-10 18:21:10 +00001073 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001074
Caroline Tice5136f942010-09-27 21:35:15 +00001075 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1076 {
1077 if (data_ap->script_source.GetSize() == 1)
1078 {
1079 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1080 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1081 }
1082 }
1083
Johnny Chend1c2dca2010-09-10 18:21:10 +00001084 return;
1085}
1086
Chris Lattner24943d22010-06-08 16:52:24 +00001087bool
1088ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1089{
1090 // Convert StringList to one long, newline delimited, const char *.
1091 std::string function_def_string;
1092
1093 int num_lines = function_def.GetSize();
1094
1095 for (int i = 0; i < num_lines; ++i)
1096 {
1097 function_def_string.append (function_def.GetStringAtIndex(i));
1098 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1099 function_def_string.append ("\n");
1100
1101 }
1102
1103 return ExecuteMultipleLines (function_def_string.c_str());
1104}
1105
Enrico Granataf7a9b142011-07-15 02:26:42 +00001106// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1107// use this code to generate their functions
1108bool
1109ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1110{
1111 int num_lines = input.GetSize ();
1112 if (num_lines == 0)
1113 return false;
1114 StreamString sstr;
1115 StringList auto_generated_function;
1116 auto_generated_function.AppendString (signature.c_str());
1117 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1118 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1119 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1120 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1121 // global dictionary.
1122
1123 // Wrap everything up inside the function, increasing the indentation.
1124
1125 for (int i = 0; i < num_lines; ++i)
1126 {
1127 sstr.Clear ();
1128 sstr.Printf (" %s", input.GetStringAtIndex (i));
1129 auto_generated_function.AppendString (sstr.GetData());
1130 }
1131 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1132 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1133 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1134 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1135
1136 // Verify that the results are valid Python.
1137
1138 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1139 return false;
1140
1141 return true;
1142
1143}
1144
1145// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1146// given to generated functions, of course)
1147bool
Enrico Granata16376ed2012-02-15 02:34:21 +00001148ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001149{
1150 static int num_created_functions = 0;
1151 user_input.RemoveBlankLines ();
1152 int num_lines = user_input.GetSize ();
1153 StreamString sstr;
1154
1155 // Check to see if we have any data; if not, just return.
1156 if (user_input.GetSize() == 0)
1157 return false;
1158
1159 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1160 // ValueObject as parameter to the function.
1161
Enrico Granata16376ed2012-02-15 02:34:21 +00001162 if (!name_token)
1163 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1164 else
1165 sstr.Printf ("lldb_gen_python_type_print_func_%p", name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001166 ++num_created_functions;
1167 std::string auto_generated_function_name = sstr.GetData();
1168
1169 sstr.Clear();
1170 StringList auto_generated_function;
1171
1172 // Create the function name & definition string.
1173
1174 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1175 auto_generated_function.AppendString (sstr.GetData());
1176
1177 // Pre-pend code for setting up the session dictionary.
1178
1179 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1180 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1181 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1182 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1183 // global dictionary.
1184
1185 // Wrap everything up inside the function, increasing the indentation.
1186
1187 for (int i = 0; i < num_lines; ++i)
1188 {
1189 sstr.Clear ();
1190 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1191 auto_generated_function.AppendString (sstr.GetData());
1192 }
1193
1194 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1195 // got written to the values in the global dictionary, not the session dictionary).
1196
1197 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1198 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1199 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1200 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1201
1202 // Verify that the results are valid Python.
1203
1204 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1205 return false;
1206
1207 // Store the name of the auto-generated function to be called.
1208
1209 output.AppendString (auto_generated_function_name.c_str());
1210 return true;
1211}
1212
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001213bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001214ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, StringList &output)
1215{
1216 static int num_created_functions = 0;
1217 user_input.RemoveBlankLines ();
1218 int num_lines = user_input.GetSize ();
1219 StreamString sstr;
1220
1221 // Check to see if we have any data; if not, just return.
1222 if (user_input.GetSize() == 0)
1223 return false;
1224
1225 // 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 +00001226 // required data as parameters to the function.
Enrico Granatac2a28252011-08-16 16:49:25 +00001227
1228 sstr.Printf ("lldb_autogen_python_cmd_alias_func_%d", num_created_functions);
1229 ++num_created_functions;
1230 std::string auto_generated_function_name = sstr.GetData();
1231
1232 sstr.Clear();
1233 StringList auto_generated_function;
1234
1235 // Create the function name & definition string.
1236
Enrico Granata271568f2011-09-09 01:41:30 +00001237 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001238 auto_generated_function.AppendString (sstr.GetData());
1239
1240 // Pre-pend code for setting up the session dictionary.
1241
1242 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1243 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1244 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1245 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1246 // global dictionary.
1247
1248 // Wrap everything up inside the function, increasing the indentation.
1249
1250 for (int i = 0; i < num_lines; ++i)
1251 {
1252 sstr.Clear ();
1253 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1254 auto_generated_function.AppendString (sstr.GetData());
1255 }
1256
1257 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1258 // got written to the values in the global dictionary, not the session dictionary).
1259
1260 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1261 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1262 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1263 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1264
1265 // Verify that the results are valid Python.
1266
1267 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1268 return false;
1269
1270 // Store the name of the auto-generated function to be called.
1271
1272 output.AppendString (auto_generated_function_name.c_str());
1273 return true;
1274}
1275
1276
1277bool
Enrico Granata16376ed2012-02-15 02:34:21 +00001278ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output, void* name_token)
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001279{
1280 static int num_created_classes = 0;
1281 user_input.RemoveBlankLines ();
1282 int num_lines = user_input.GetSize ();
1283 StreamString sstr;
1284
1285 // Check to see if we have any data; if not, just return.
1286 if (user_input.GetSize() == 0)
1287 return false;
1288
1289 // Wrap all user input into a Python class
1290
Enrico Granata16376ed2012-02-15 02:34:21 +00001291 if (!name_token)
1292 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1293 else
1294 sstr.Printf ("lldb_gen_python_type_synth_class_%p", name_token);
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001295 ++num_created_classes;
1296 std::string auto_generated_class_name = sstr.GetData();
1297
1298 sstr.Clear();
1299 StringList auto_generated_class;
1300
1301 // Create the function name & definition string.
1302
1303 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1304 auto_generated_class.AppendString (sstr.GetData());
1305
1306 // Wrap everything up inside the class, increasing the indentation.
1307
1308 for (int i = 0; i < num_lines; ++i)
1309 {
1310 sstr.Clear ();
1311 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1312 auto_generated_class.AppendString (sstr.GetData());
1313 }
1314
1315
1316 // Verify that the results are valid Python.
1317 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1318 // (TODO: rename that method to ExportDefinitionToInterpreter)
1319 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1320 return false;
1321
1322 // Store the name of the auto-generated class
1323
1324 output.AppendString (auto_generated_class_name.c_str());
1325 return true;
1326}
1327
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001328void*
1329ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1330 lldb::ValueObjectSP valobj)
1331{
1332 if (class_name.empty())
1333 return NULL;
1334
1335 if (!valobj.get())
1336 return NULL;
1337
Greg Claytonb4d7fc02012-02-17 07:49:44 +00001338 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1339 Target *target = exe_ctx.GetTargetPtr();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001340
1341 if (!target)
1342 return NULL;
1343
1344 Debugger &debugger = target->GetDebugger();
1345 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1346 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1347
1348 if (!script_interpreter)
1349 return NULL;
1350
1351 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001352
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001353 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001354 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001355 ret_val = g_swig_synthetic_script (class_name,
1356 python_interpreter->m_dictionary_name.c_str(),
1357 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001358 }
1359
1360 return ret_val;
1361}
1362
Enrico Granataf7a9b142011-07-15 02:26:42 +00001363bool
Enrico Granata16376ed2012-02-15 02:34:21 +00001364ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001365{
Enrico Granata16376ed2012-02-15 02:34:21 +00001366 StringList input;
1367 input.SplitIntoLines(oneliner, strlen(oneliner));
1368 return GenerateTypeScriptFunction(input, output, name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001369}
1370
Chris Lattner24943d22010-06-08 16:52:24 +00001371bool
Enrico Granata16376ed2012-02-15 02:34:21 +00001372ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, StringList &output, void* name_token)
1373{
1374 StringList input;
1375 input.SplitIntoLines(oneliner, strlen(oneliner));
1376 return GenerateTypeSynthClass(input, output, name_token);
1377}
1378
1379
1380bool
Chris Lattner24943d22010-06-08 16:52:24 +00001381ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1382{
1383 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001384 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001385 int num_lines = user_input.GetSize ();
1386 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001387
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001388 // Check to see if we have any data; if not, just return.
1389 if (user_input.GetSize() == 0)
1390 return false;
1391
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001392 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1393 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001394
Caroline Ticeb447e842010-09-21 19:25:28 +00001395
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001396 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1397 ++num_created_functions;
1398 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001399
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001400 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001401 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001402
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001403 // Create the function name & definition string.
1404
Caroline Tice0aa2e552011-01-14 00:29:16 +00001405 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001406 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001407
1408 // Pre-pend code for setting up the session dictionary.
1409
1410 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1411 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1412 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1413 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1414 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001415
1416 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001417
1418 for (int i = 0; i < num_lines; ++i)
1419 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001420 sstr.Clear ();
1421 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1422 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001423 }
Chris Lattner24943d22010-06-08 16:52:24 +00001424
Caroline Tice0aa2e552011-01-14 00:29:16 +00001425 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1426 // got written to the values in the global dictionary, not the session dictionary).
1427
1428 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1429 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1430 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1431 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1432
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001433 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001434
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001435 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001436 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001437 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001438 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001439
1440 // Store the name of the auto-generated function to be called.
1441
1442 callback_data.AppendString (auto_generated_function_name.c_str());
1443 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001444}
1445
Enrico Granataf7a9b142011-07-15 02:26:42 +00001446std::string
1447ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1448 lldb::ValueObjectSP valobj)
1449{
1450
1451 if (!python_function_name || !(*python_function_name))
1452 return "<no function>";
1453
1454 if (!valobj.get())
1455 return "<no object>";
1456
Greg Claytonb4d7fc02012-02-17 07:49:44 +00001457 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1458 Target *target = exe_ctx.GetTargetPtr();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001459
1460 if (!target)
1461 return "<no target>";
1462
1463 Debugger &debugger = target->GetDebugger();
1464 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1465 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1466
1467 if (!script_interpreter)
1468 return "<no python>";
1469
1470 std::string ret_val;
1471
1472 if (python_function_name
1473 && *python_function_name)
1474 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001475 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001476 Locker py_lock(python_interpreter);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001477 ret_val = g_swig_typescript_callback (python_function_name,
1478 python_interpreter->m_dictionary_name.c_str(),
1479 valobj);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001480 }
1481 }
1482 else
1483 return "<no function name>";
1484
1485 return ret_val;
1486
1487}
1488
Greg Clayton5144f382010-10-07 17:14:24 +00001489bool
1490ScriptInterpreterPython::BreakpointCallbackFunction
1491(
1492 void *baton,
1493 StoppointCallbackContext *context,
1494 user_id_t break_id,
1495 user_id_t break_loc_id
1496)
1497{
1498 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1499 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001500
1501 if (!context)
1502 return true;
1503
Greg Claytonf4124de2012-02-21 00:09:25 +00001504 ExecutionContext exe_ctx (context->exe_ctx_ref);
1505 Target *target = exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001506
1507 if (!target)
1508 return true;
1509
1510 Debugger &debugger = target->GetDebugger();
1511 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1512 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1513
1514 if (!script_interpreter)
1515 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001516
1517 if (python_function_name != NULL
1518 && python_function_name[0] != '\0')
1519 {
Greg Claytonf4124de2012-02-21 00:09:25 +00001520 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001521 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001522 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001523 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001524 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1525
1526 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001527 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001528 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001529 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001530 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001531 ret_val = g_swig_breakpoint_callback (python_function_name,
1532 python_interpreter->m_dictionary_name.c_str(),
1533 stop_frame_sp,
1534 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001535 }
1536 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001537 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001538 }
Greg Clayton5144f382010-10-07 17:14:24 +00001539 }
1540 // We currently always true so we stop in case anything goes wrong when
1541 // trying to call the script function
1542 return true;
1543}
Caroline Tice2ade6112010-11-10 19:18:14 +00001544
1545lldb::thread_result_t
1546ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1547{
1548 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1549
1550 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1551
1552 if (log)
1553 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1554
1555 char error_str[1024];
1556 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001557
Enrico Granatafa1f6172011-10-24 17:22:21 +00001558 Locker locker(script_interpreter,
1559 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1560 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1561
1562 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001563 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001564 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001565
Caroline Tice0aa2e552011-01-14 00:29:16 +00001566 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1567 PyRun_SimpleString (run_string.GetData());
1568 run_string.Clear ();
1569
1570 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1571 PyRun_SimpleString (run_string.GetData());
1572 run_string.Clear ();
1573
1574 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1575 PyRun_SimpleString (run_string.GetData());
1576 run_string.Clear ();
1577
1578 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1579 pty_slave_name);
1580 PyRun_SimpleString (run_string.GetData());
1581 run_string.Clear ();
1582
Johnny Chen8054ba32011-03-11 00:28:50 +00001583 // The following call drops into the embedded interpreter loop and stays there until the
1584 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001585
Caroline Ticece207c12011-03-11 00:21:55 +00001586 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001587 // 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 +00001588 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1589
1590 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1591 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1592 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1593 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1594 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1595 // hang (it's happened before).
1596
Caroline Tice9d352ce2011-03-07 23:24:28 +00001597 Py_BEGIN_ALLOW_THREADS
1598 PyGILState_STATE gstate = PyGILState_Ensure();
1599
Caroline Tice0aa2e552011-01-14 00:29:16 +00001600 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1601 PyRun_SimpleString (run_string.GetData());
1602 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001603
Caroline Tice9d352ce2011-03-07 23:24:28 +00001604 PyGILState_Release (gstate);
1605 Py_END_ALLOW_THREADS
1606
Caroline Tice0aa2e552011-01-14 00:29:16 +00001607 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1608 PyRun_SimpleString (run_string.GetData());
1609 run_string.Clear();
1610
1611 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1612 PyRun_SimpleString (run_string.GetData());
1613 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001614
Caroline Tice2ade6112010-11-10 19:18:14 +00001615 }
1616
1617 if (script_interpreter->m_embedded_thread_input_reader_sp)
1618 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1619
1620 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001621
Caroline Tice2ade6112010-11-10 19:18:14 +00001622 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1623 if (log)
1624 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1625
1626
Johnny Chen8054ba32011-03-11 00:28:50 +00001627 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001628 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001629 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1630 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1631 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001632
Caroline Tice2ade6112010-11-10 19:18:14 +00001633 return NULL;
1634}
1635
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001636uint32_t
1637ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1638{
1639 if (!implementor)
1640 return 0;
1641
1642 if (!g_swig_calc_children)
1643 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001644
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001645 uint32_t ret_val = 0;
1646
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001647 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001648 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001649 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001650 }
1651
1652 return ret_val;
1653}
1654
Enrico Granata91544802011-09-06 19:20:51 +00001655lldb::ValueObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001656ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1657{
1658 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001659 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001660
Enrico Granata91544802011-09-06 19:20:51 +00001661 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1662 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001663
Enrico Granata91544802011-09-06 19:20:51 +00001664 void* child_ptr = NULL;
1665 lldb::SBValue* value_sb = NULL;
1666 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001667
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001668 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001669 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +00001670 child_ptr = g_swig_get_child_index (implementor,idx);
1671 if (child_ptr != NULL && child_ptr != Py_None)
1672 {
1673 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1674 if (value_sb == NULL)
1675 Py_XDECREF(child_ptr);
1676 else
1677 ret_val = value_sb->get_sp();
1678 }
1679 else
1680 {
1681 Py_XDECREF(child_ptr);
1682 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001683 }
1684
1685 return ret_val;
1686}
1687
1688int
1689ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1690{
1691 if (!implementor)
1692 return UINT32_MAX;
1693
1694 if (!g_swig_get_index_child)
1695 return UINT32_MAX;
1696
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001697 int ret_val = UINT32_MAX;
1698
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001699 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001700 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001701 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001702 }
1703
1704 return ret_val;
1705}
1706
Enrico Granata979e20d2011-07-29 19:53:35 +00001707void
1708ScriptInterpreterPython::UpdateSynthProviderInstance (void* implementor)
1709{
1710 if (!implementor)
1711 return;
1712
1713 if (!g_swig_update_provider)
1714 return;
1715
Enrico Granata979e20d2011-07-29 19:53:35 +00001716 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001717 Locker py_lock(this);
Enrico Granata979e20d2011-07-29 19:53:35 +00001718 g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001719 }
1720
1721 return;
1722}
1723
Enrico Granatac2a28252011-08-16 16:49:25 +00001724bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001725ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00001726 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00001727 lldb_private::Error& error)
1728{
1729 if (!pathname || !pathname[0])
1730 {
1731 error.SetErrorString("invalid pathname");
1732 return false;
1733 }
1734
1735 if (!g_swig_call_module_init)
1736 {
1737 error.SetErrorString("internal helper function missing");
1738 return false;
1739 }
1740
Greg Clayton13d24fb2012-01-29 20:56:30 +00001741 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granatafa1f6172011-10-24 17:22:21 +00001742
Enrico Granata59df36f2011-10-17 21:45:27 +00001743 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001744 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00001745
1746 FileSpec target_file(pathname, true);
1747
1748 // TODO: would we want to reject any other value?
1749 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1750 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1751 {
1752 error.SetErrorString("invalid pathname");
1753 return false;
1754 }
1755
1756 const char* directory = target_file.GetDirectory().GetCString();
1757 std::string basename(target_file.GetFilename().GetCString());
1758
1759 // now make sure that Python has "directory" in the search path
1760 StreamString command_stream;
1761 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1762 directory,
1763 directory);
Enrico Granatafa1f6172011-10-24 17:22:21 +00001764 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData());
Enrico Granata59df36f2011-10-17 21:45:27 +00001765 if (!syspath_retval)
1766 {
1767 error.SetErrorString("Python sys.path handling failed");
1768 return false;
1769 }
1770
1771 // strip .py or .pyc extension
1772 ConstString extension = target_file.GetFileNameExtension();
1773 if (::strcmp(extension.GetCString(), "py") == 0)
1774 basename.resize(basename.length()-3);
1775 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1776 basename.resize(basename.length()-4);
1777
1778 // check if the module is already import-ed
1779 command_stream.Clear();
1780 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1781 int refcount = 0;
1782 // this call will fail if the module does not exist (because the parameter to it is not a string
1783 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00001784 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
1785 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0);
1786 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00001787 {
1788 error.SetErrorString("module already imported");
1789 return false;
1790 }
1791
1792 // now actually do the import
1793 command_stream.Clear();
1794 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafa1f6172011-10-24 17:22:21 +00001795 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL);
Enrico Granata59df36f2011-10-17 21:45:27 +00001796 if (!import_retval)
1797 {
1798 error.SetErrorString("Python import statement failed");
1799 return false;
1800 }
1801
Enrico Granata16376ed2012-02-15 02:34:21 +00001802 // call __lldb_init_module(debugger,dict)
Enrico Granata59df36f2011-10-17 21:45:27 +00001803 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001804 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001805 debugger_sp))
1806 {
Enrico Granata16376ed2012-02-15 02:34:21 +00001807 error.SetErrorString("calling __lldb_init_module failed");
Enrico Granata59df36f2011-10-17 21:45:27 +00001808 return false;
1809 }
1810 return true;
1811 }
1812}
1813
Enrico Granata6010ace2011-11-07 22:57:04 +00001814ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
1815 ScriptedCommandSynchronicity synchro) :
1816 m_debugger_sp(debugger_sp),
1817 m_synch_wanted(synchro),
1818 m_old_asynch(debugger_sp->GetAsyncExecution())
1819{
1820 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
1821 m_debugger_sp->SetAsyncExecution(false);
1822 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
1823 m_debugger_sp->SetAsyncExecution(true);
1824}
1825
1826ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
1827{
1828 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
1829 m_debugger_sp->SetAsyncExecution(m_old_asynch);
1830}
1831
Enrico Granata59df36f2011-10-17 21:45:27 +00001832bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001833ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1834 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00001835 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001836 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001837 Error& error)
1838{
1839 if (!impl_function)
1840 {
1841 error.SetErrorString("no function to execute");
1842 return false;
1843 }
1844
1845 if (!g_swig_call_command)
1846 {
1847 error.SetErrorString("no helper function to run scripted commands");
1848 return false;
1849 }
1850
Greg Clayton13d24fb2012-01-29 20:56:30 +00001851 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata6010ace2011-11-07 22:57:04 +00001852
1853 if (!debugger_sp.get())
1854 {
1855 error.SetErrorString("invalid Debugger pointer");
1856 return false;
1857 }
Enrico Granatac2a28252011-08-16 16:49:25 +00001858
1859 bool ret_val;
1860
1861 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00001862
Enrico Granatac2a28252011-08-16 16:49:25 +00001863 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001864 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00001865 SynchronicityHandler synch_handler(debugger_sp,
1866 synchronicity);
1867
Enrico Granatac2a28252011-08-16 16:49:25 +00001868 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001869 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00001870 debugger_sp,
1871 args,
1872 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001873 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001874 }
Enrico Granata6010ace2011-11-07 22:57:04 +00001875
Enrico Granatac2a28252011-08-16 16:49:25 +00001876 if (!ret_val)
1877 error.SetErrorString(err_msg.c_str());
1878 else
1879 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00001880
Enrico Granatac2a28252011-08-16 16:49:25 +00001881 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00001882}
1883
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001884// in Python, a special attribute __doc__ contains the docstring
1885// for an object (function, method, class, ...) if any is defined
1886// Otherwise, the attribute's value is None
1887std::string
1888ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1889{
1890 std::string command(item);
1891 command += ".__doc__";
1892
1893 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1894
1895 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001896 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001897 &result_ptr) && result_ptr)
1898 {
1899 return std::string(result_ptr);
1900 }
1901 else
1902 return std::string("");
1903}
Caroline Tice2ade6112010-11-10 19:18:14 +00001904
Caroline Tice0aa2e552011-01-14 00:29:16 +00001905void
Greg Claytone86cbb92011-03-22 01:14:58 +00001906ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00001907 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001908 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
1909 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
1910 SWIGPythonCalculateNumChildren python_swig_calc_children,
1911 SWIGPythonGetChildAtIndex python_swig_get_child_index,
1912 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
Enrico Granata979e20d2011-07-29 19:53:35 +00001913 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue,
Enrico Granatac2a28252011-08-16 16:49:25 +00001914 SWIGPythonUpdateSynthProviderInstance python_swig_update_provider,
Enrico Granata59df36f2011-10-17 21:45:27 +00001915 SWIGPythonCallCommand python_swig_call_command,
1916 SWIGPythonCallModuleInit python_swig_call_mod_init)
Greg Claytone86cbb92011-03-22 01:14:58 +00001917{
1918 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001919 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1920 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001921 g_swig_synthetic_script = python_swig_synthetic_script;
1922 g_swig_calc_children = python_swig_calc_children;
1923 g_swig_get_child_index = python_swig_get_child_index;
1924 g_swig_get_index_child = python_swig_get_index_child;
1925 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Enrico Granata979e20d2011-07-29 19:53:35 +00001926 g_swig_update_provider = python_swig_update_provider;
Enrico Granatac2a28252011-08-16 16:49:25 +00001927 g_swig_call_command = python_swig_call_command;
Enrico Granata59df36f2011-10-17 21:45:27 +00001928 g_swig_call_module_init = python_swig_call_mod_init;
Greg Claytone86cbb92011-03-22 01:14:58 +00001929}
1930
1931void
1932ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001933{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001934 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1935
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001936 // Python will muck with STDIN terminal state, so save off any current TTY
1937 // settings so we can restore them.
1938 TerminalState stdin_tty_state;
1939 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001940
Caroline Tice9d352ce2011-03-07 23:24:28 +00001941 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001942 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001943
Greg Claytone86cbb92011-03-22 01:14:58 +00001944 // Initialize SWIG after setting up python
1945 assert (g_swig_init_callback != NULL);
1946 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001947
1948 // Update the path python uses to search for modules to include the current directory.
1949
Caroline Ticed4d92832011-06-13 21:33:00 +00001950 PyRun_SimpleString ("import sys");
1951 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001952
1953 // Find the module that owns this code and use that path we get to
1954 // set the sys.path appropriately.
1955
1956 FileSpec file_spec;
1957 char python_dir_path[PATH_MAX];
1958 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1959 {
1960 std::string python_path("sys.path.insert(0,\"");
1961 size_t orig_len = python_path.length();
1962 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1963 {
1964 python_path.append (python_dir_path);
1965 python_path.append ("\")");
1966 PyRun_SimpleString (python_path.c_str());
1967 python_path.resize (orig_len);
1968 }
1969
1970 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1971 {
1972 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1973 {
1974 python_path.append (python_dir_path);
1975 python_path.append ("\")");
1976 PyRun_SimpleString (python_path.c_str());
1977 python_path.resize (orig_len);
1978 }
1979 }
1980 }
1981
Jim Ingham4dfa5112011-08-22 19:10:09 +00001982 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001983
Caroline Ticed4d92832011-06-13 21:33:00 +00001984 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001985
Caroline Ticed4d92832011-06-13 21:33:00 +00001986 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1987 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00001988 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001989
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001990 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001991}
1992
Greg Claytone86cbb92011-03-22 01:14:58 +00001993//void
1994//ScriptInterpreterPython::Terminate ()
1995//{
1996// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1997// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1998// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1999// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
2000// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
2001// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
2002// // within Py_Finalize, which results in a seg fault.
2003// //
2004// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
2005// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
2006// // process exits).
2007// //
2008//// Py_Finalize ();
2009//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00002010
2011#endif // #ifdef LLDB_DISABLE_PYTHON