blob: 1653e92e9b5c06f48b0c33a1f985b1d353da0989 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ScriptInterpreterPython.cpp -----------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// In order to guarantee correct working with Python, Python.h *MUST* be
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +000011// the *FIRST* header file included here.
Greg Clayton3e4238d2011-11-04 03:34:56 +000012#ifdef LLDB_DISABLE_PYTHON
13
14// Python is disabled in this build
15
16#else
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +000017
18#if defined (__APPLE__)
19#include <Python/Python.h>
20#else
21#include <Python.h>
22#endif
Chris Lattner24943d22010-06-08 16:52:24 +000023
24#include "lldb/Interpreter/ScriptInterpreterPython.h"
25
Chris Lattner24943d22010-06-08 16:52:24 +000026#include <stdlib.h>
27#include <stdio.h>
28
29#include <string>
30
Enrico Granata91544802011-09-06 19:20:51 +000031#include "lldb/API/SBValue.h"
Greg Clayton987c7eb2011-09-17 08:33:22 +000032#include "lldb/Breakpoint/BreakpointLocation.h"
Greg Clayton63094e02010-06-23 01:19:29 +000033#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner24943d22010-06-08 16:52:24 +000034#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000035#include "lldb/Core/Timer.h"
36#include "lldb/Host/Host.h"
37#include "lldb/Interpreter/CommandInterpreter.h"
38#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton5144f382010-10-07 17:14:24 +000039#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040
Chris Lattner24943d22010-06-08 16:52:24 +000041using namespace lldb;
42using namespace lldb_private;
43
Greg Claytone86cbb92011-03-22 01:14:58 +000044
45static ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL;
46static ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL;
Enrico Granataf7a9b142011-07-15 02:26:42 +000047static ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL;
Enrico Granata9ae7cef2011-07-24 00:14:56 +000048static ScriptInterpreter::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = NULL;
49static ScriptInterpreter::SWIGPythonCalculateNumChildren g_swig_calc_children = NULL;
50static ScriptInterpreter::SWIGPythonGetChildAtIndex g_swig_get_child_index = NULL;
51static ScriptInterpreter::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = NULL;
52static ScriptInterpreter::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = NULL;
Enrico Granata979e20d2011-07-29 19:53:35 +000053static ScriptInterpreter::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = NULL;
Enrico Granatac2a28252011-08-16 16:49:25 +000054static ScriptInterpreter::SWIGPythonCallCommand g_swig_call_command = NULL;
Enrico Granata59df36f2011-10-17 21:45:27 +000055static ScriptInterpreter::SWIGPythonCallModuleInit g_swig_call_module_init = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +000056
Enrico Granata1328b142012-02-29 03:28:49 +000057// these are the Pythonic implementations of the required callbacks
58// these are scripting-language specific, which is why they belong here
59// we still need to use function pointers to them instead of relying
60// on linkage-time resolution because the SWIG stuff and this file
61// get built at different times
62extern "C" bool
63LLDBSwigPythonBreakpointCallbackFunction
64(
65 const char *python_function_name,
66 const char *session_dictionary_name,
67 const lldb::StackFrameSP& sb_frame,
68 const lldb::BreakpointLocationSP& sb_bp_loc
69 );
70
71extern "C" bool
72LLDBSwigPythonCallTypeScript
73(
74 const char *python_function_name,
75 void *session_dictionary,
76 const lldb::ValueObjectSP& valobj_sp,
77 void** pyfunct_wrapper,
78 std::string& retval
79 );
80
81extern "C" void*
82LLDBSwigPythonCreateSyntheticProvider
83(
84 const std::string python_class_name,
85 const char *session_dictionary_name,
86 const lldb::ValueObjectSP& valobj_sp
87 );
88
89
90extern "C" uint32_t LLDBSwigPython_CalculateNumChildren (void *implementor);
91extern "C" void* LLDBSwigPython_GetChildAtIndex (void *implementor, uint32_t idx);
92extern "C" int LLDBSwigPython_GetIndexOfChildWithName (void *implementor, const char* child_name);
93extern "C" void* LLDBSWIGPython_CastPyObjectToSBValue (void* data);
94extern "C" void LLDBSwigPython_UpdateSynthProviderInstance (void* implementor);
95
96extern "C" bool LLDBSwigPythonCallCommand
97(
98 const char *python_function_name,
99 const char *session_dictionary_name,
100 lldb::DebuggerSP& debugger,
101 const char* args,
102 std::string& err_msg,
103 lldb_private::CommandReturnObject& cmd_retobj
104 );
105
106extern "C" bool LLDBSwigPythonCallModuleInit
107(
108 const std::string python_module_name,
109 const char *session_dictionary_name,
110 lldb::DebuggerSP& debugger
111 );
112
Chris Lattner24943d22010-06-08 16:52:24 +0000113static int
114_check_and_flush (FILE *stream)
115{
116 int prev_fail = ferror (stream);
117 return fflush (stream) || prev_fail ? EOF : 0;
118}
119
Caroline Tice202f6b82011-01-17 21:55:19 +0000120static Predicate<lldb::tid_t> &
121PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +0000122{
Caroline Tice202f6b82011-01-17 21:55:19 +0000123 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
124 return g_interpreter_is_running;
125}
126
Enrico Granatafa1f6172011-10-24 17:22:21 +0000127bool
128ScriptInterpreterPython::Locker::CurrentThreadHasPythonLock ()
Caroline Tice202f6b82011-01-17 21:55:19 +0000129{
130 TimeValue timeout;
131
132 timeout = TimeValue::Now(); // Don't wait any time.
133
134 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
135}
136
Enrico Granatafa1f6172011-10-24 17:22:21 +0000137bool
138ScriptInterpreterPython::Locker::TryGetPythonLock (uint32_t seconds_to_wait)
Caroline Tice202f6b82011-01-17 21:55:19 +0000139{
140
141 TimeValue timeout;
142
143 if (seconds_to_wait != UINT32_MAX)
144 {
145 timeout = TimeValue::Now();
146 timeout.OffsetWithSeconds (seconds_to_wait);
147 }
148
149 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
150 Host::GetCurrentThreadID(), &timeout, NULL);
151}
152
Enrico Granatafa1f6172011-10-24 17:22:21 +0000153void
154ScriptInterpreterPython::Locker::ReleasePythonLock ()
Caroline Tice202f6b82011-01-17 21:55:19 +0000155{
156 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000157}
158
Enrico Granatafa1f6172011-10-24 17:22:21 +0000159ScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *py_interpreter,
160 uint16_t on_entry,
161 uint16_t on_leave,
162 FILE* wait_msg_handle) :
163 m_need_session( (on_leave & TearDownSession) == TearDownSession ),
164 m_release_lock ( false ), // decide in constructor body
165 m_python_interpreter(py_interpreter),
166 m_tmp_fh(wait_msg_handle)
Enrico Granata91544802011-09-06 19:20:51 +0000167{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000168 if (m_python_interpreter && !m_tmp_fh)
169 m_tmp_fh = (m_python_interpreter->m_dbg_stdout ? m_python_interpreter->m_dbg_stdout : stdout);
170
171 if ( (on_entry & AcquireLock) == AcquireLock )
172 {
173 if (CurrentThreadHasPythonLock())
174 {
175 if ( (on_leave & FreeLock) == FreeLock )
176 m_release_lock = true;
177 }
178 else
179 {
180 DoAcquireLock();
181 if ( (on_leave & FreeLock) == FreeLock )
182 m_release_lock = true;
183 if ( (on_leave & FreeAcquiredLock) == FreeAcquiredLock )
184 m_release_lock = true;
185 }
186 }
187 if ( (on_entry & InitSession) == InitSession )
188 DoInitSession();
189}
190
191bool
192ScriptInterpreterPython::Locker::DoAcquireLock()
193{
Enrico Granata91544802011-09-06 19:20:51 +0000194 if (!CurrentThreadHasPythonLock())
195 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000196 while (!TryGetPythonLock (1))
197 if (m_tmp_fh)
198 fprintf (m_tmp_fh,
Enrico Granata91544802011-09-06 19:20:51 +0000199 "Python interpreter locked on another thread; waiting to acquire lock...\n");
Enrico Granata91544802011-09-06 19:20:51 +0000200 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000201 return true;
202}
203
204bool
205ScriptInterpreterPython::Locker::DoInitSession()
206{
207 if (!m_python_interpreter)
208 return false;
209 m_python_interpreter->EnterSession ();
210 return true;
211}
212
213bool
214ScriptInterpreterPython::Locker::DoFreeLock()
215{
216 ReleasePythonLock ();
217 return true;
218}
219
220bool
221ScriptInterpreterPython::Locker::DoTearDownSession()
222{
223 if (!m_python_interpreter)
224 return false;
225 m_python_interpreter->LeaveSession ();
226 return true;
Enrico Granata91544802011-09-06 19:20:51 +0000227}
228
229ScriptInterpreterPython::Locker::~Locker()
230{
231 if (m_need_session)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000232 DoTearDownSession();
Enrico Granata91544802011-09-06 19:20:51 +0000233 if (m_release_lock)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000234 DoFreeLock();
Enrico Granata91544802011-09-06 19:20:51 +0000235}
236
Greg Clayton63094e02010-06-23 01:19:29 +0000237ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000238 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000239 m_embedded_python_pty (),
240 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +0000241 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000242 m_new_sysout (NULL),
Enrico Granata400105d2012-03-06 23:42:15 +0000243 m_run_one_line (NULL),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000244 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000245 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000246 m_session_is_active (false),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000247 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000248{
249
Greg Clayton7c330d62011-01-27 01:01:10 +0000250 static int g_initialized = false;
251
252 if (!g_initialized)
253 {
254 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000255 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000256 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000257
258 Locker locker(this,
259 ScriptInterpreterPython::Locker::AcquireLock,
260 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Greg Clayton7c330d62011-01-27 01:01:10 +0000261
Caroline Tice0aa2e552011-01-14 00:29:16 +0000262 m_dictionary_name.append("_dict");
263 StreamString run_string;
264 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
265 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000266
Caroline Tice0aa2e552011-01-14 00:29:16 +0000267 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000268
269 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
270 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
271 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
272 // call to Debugger::Terminate is made, the ref-count has the correct value.
273 //
274 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
275 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000276
Caroline Tice0aa2e552011-01-14 00:29:16 +0000277 int old_count = Debugger::TestDebuggerRefCount();
Greg Claytonb302dff2012-02-01 08:09:32 +0000278
Chris Lattner24943d22010-06-08 16:52:24 +0000279
Greg Claytonb302dff2012-02-01 08:09:32 +0000280 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 +0000281 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000282
Enrico Granata8f84cfb2012-02-23 23:10:03 +0000283 // WARNING: temporary code that loads Cocoa formatters - this should be done on a per-platform basis rather than loading the whole set
284 // and letting the individual formatter classes exploit APIs to check whether they can/cannot do their task
285 run_string.Clear();
Enrico Granatade3b25b2012-03-03 00:45:57 +0000286 run_string.Printf ("run_one_line (%s, 'import CFString, CFArray, CFDictionary, NSData, NSMachPort, NSSet, NSNotification, NSException, CFBag, CFBinaryHeap, NSURL, NSBundle, NSNumber, NSDate, NSIndexSet, Selector, CFBitVector')", m_dictionary_name.c_str());
Enrico Granata8f84cfb2012-02-23 23:10:03 +0000287 PyRun_SimpleString (run_string.GetData());
Greg Claytonb302dff2012-02-01 08:09:32 +0000288
Caroline Tice0aa2e552011-01-14 00:29:16 +0000289 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000290
Caroline Tice0aa2e552011-01-14 00:29:16 +0000291 if (new_count > old_count)
292 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000293
Caroline Tice0aa2e552011-01-14 00:29:16 +0000294 run_string.Clear();
Greg Clayton444e35b2011-10-19 18:09:39 +0000295 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000296 interpreter.GetDebugger().GetID());
297 PyRun_SimpleString (run_string.GetData());
298
299 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000300 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000301 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000302 }
Chris Lattner24943d22010-06-08 16:52:24 +0000303}
304
305ScriptInterpreterPython::~ScriptInterpreterPython ()
306{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000307 Debugger &debugger = GetCommandInterpreter().GetDebugger();
308
309 if (m_embedded_thread_input_reader_sp.get() != NULL)
310 {
311 m_embedded_thread_input_reader_sp->SetIsDone (true);
312 m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000313 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
314 m_embedded_thread_input_reader_sp.reset();
315 debugger.PopInputReader (reader_sp);
316 }
317
318 if (m_new_sysout)
319 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000320 Locker locker(this,
321 ScriptInterpreterPython::Locker::AcquireLock,
322 ScriptInterpreterPython::Locker::FreeLock);
323 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000324 }
Chris Lattner24943d22010-06-08 16:52:24 +0000325}
326
Caroline Tice0aa2e552011-01-14 00:29:16 +0000327void
328ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
329{
330 if (fh == NULL)
331 return;
332
333 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000334
Enrico Granatafa1f6172011-10-24 17:22:21 +0000335 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +0000336
337 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000338}
339
340void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000341ScriptInterpreterPython::SaveTerminalState (int fd)
342{
343 // Python mucks with the terminal state of STDIN. If we can possibly avoid
344 // this by setting the file handles up correctly prior to entering the
345 // interpreter we should. For now we save and restore the terminal state
346 // on the input file handle.
347 m_terminal_state.Save (fd, false);
348}
349
350void
351ScriptInterpreterPython::RestoreTerminalState ()
352{
353 // Python mucks with the terminal state of STDIN. If we can possibly avoid
354 // this by setting the file handles up correctly prior to entering the
355 // interpreter we should. For now we save and restore the terminal state
356 // on the input file handle.
357 m_terminal_state.Restore();
358}
359
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000360void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000361ScriptInterpreterPython::LeaveSession ()
362{
Johnny Chen41641f92012-02-29 01:52:13 +0000363 PyObject *sysmod = PyImport_AddModule ("sys");
364 PyObject *sysdict = PyModule_GetDict (sysmod);
365
366 if (m_new_sysout && sysmod && sysdict)
367 {
368 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_old_sysout);
369 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_old_sysout);
370 }
371
Caroline Tice0aa2e552011-01-14 00:29:16 +0000372 m_session_is_active = false;
373}
374
375void
376ScriptInterpreterPython::EnterSession ()
377{
378 // If we have already entered the session, without having officially 'left' it, then there is no need to
379 // 'enter' it again.
380
381 if (m_session_is_active)
382 return;
383
384 m_session_is_active = true;
385
Caroline Tice202f6b82011-01-17 21:55:19 +0000386 StreamString run_string;
387
Greg Clayton2fecc452012-01-28 02:11:02 +0000388 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %llu", m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
389 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)", GetCommandInterpreter().GetDebugger().GetID());
390 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
391 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
392 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
393 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
394 // Make sure STDIN is closed since when we run this as an embedded
395 // interpreter we don't want someone to call "line = sys.stdin.readline()"
396 // and lock up. We don't have multiple windows and when the interpreter is
397 // embedded we don't know we should be feeding input to the embedded
398 // interpreter or to the python sys.stdin. We also don't want to let python
399 // play with the real stdin from this process, so we need to close it...
Greg Clayton3eeaf6e2012-02-03 01:30:30 +0000400 //run_string.PutCString ("; sys.stdin.close()");
Greg Clayton2fecc452012-01-28 02:11:02 +0000401 run_string.PutCString ("')");
Caroline Tice0aa2e552011-01-14 00:29:16 +0000402
Caroline Tice6af65cb2011-05-03 21:21:50 +0000403 PyRun_SimpleString (run_string.GetData());
404 run_string.Clear();
Johnny Chen41641f92012-02-29 01:52:13 +0000405
Caroline Tice0aa2e552011-01-14 00:29:16 +0000406 PyObject *sysmod = PyImport_AddModule ("sys");
407 PyObject *sysdict = PyModule_GetDict (sysmod);
Johnny Chen41641f92012-02-29 01:52:13 +0000408
Greg Clayton2fecc452012-01-28 02:11:02 +0000409 if (m_new_sysout && sysmod && sysdict)
410 {
Johnny Chen41641f92012-02-29 01:52:13 +0000411 m_old_sysout = PyDict_GetItemString(sysdict, "stdout");
412 m_old_syserr = PyDict_GetItemString(sysdict, "stderr");
Greg Clayton2fecc452012-01-28 02:11:02 +0000413 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
414 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
415 }
Johnny Chen41641f92012-02-29 01:52:13 +0000416
Caroline Tice0aa2e552011-01-14 00:29:16 +0000417 if (PyErr_Occurred())
418 PyErr_Clear ();
Greg Clayton2fecc452012-01-28 02:11:02 +0000419}
Caroline Tice0aa2e552011-01-14 00:29:16 +0000420
Enrico Granata400105d2012-03-06 23:42:15 +0000421static PyObject*
422FindSessionDictionary (const char* dict_name)
423{
424 static std::map<ConstString,PyObject*> g_dict_map;
425
426 ConstString dict(dict_name);
427
428 std::map<ConstString,PyObject*>::iterator iter = g_dict_map.find(dict);
429
430 if (iter != g_dict_map.end())
431 return iter->second;
432
433 PyObject *main_mod = PyImport_AddModule ("__main__");
434 if (main_mod != NULL)
435 {
436 PyObject *main_dict = PyModule_GetDict (main_mod);
437 if ((main_dict != NULL)
438 && PyDict_Check (main_dict))
439 {
440 // Go through the main dictionary looking for the correct python script interpreter dictionary
441 PyObject *key, *value;
442 Py_ssize_t pos = 0;
443
444 while (PyDict_Next (main_dict, &pos, &key, &value))
445 {
446 // We have stolen references to the key and value objects in the dictionary; we need to increment
447 // them now so that Python's garbage collector doesn't collect them out from under us.
448 Py_INCREF (key);
449 Py_INCREF (value);
450 if (strcmp (PyString_AsString (key), dict_name) == 0)
451 {
452 g_dict_map[dict] = value;
453 return value;
454 }
455 }
456 }
457 }
458 return NULL;
459}
460
461static std::string
462GenerateUniqueName (const char* base_name_wanted,
463 uint32_t& functions_counter,
464 void* name_token = NULL)
465{
466 StreamString sstr;
467
468 if (!base_name_wanted)
469 return std::string();
470
471 if (!name_token)
472 sstr.Printf ("%s_%d", base_name_wanted, functions_counter++);
473 else
474 sstr.Printf ("%s_%p", base_name_wanted, name_token);
475
476 return sstr.GetString();
477}
478
Johnny Chen60dde642010-07-30 22:33:14 +0000479bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000480ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000481{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000482 if (!m_valid_session)
483 return false;
484
Caroline Tice4a461da2011-01-14 21:09:29 +0000485 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
486 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
487 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
488 // method to pass the command string directly down to Python.
489
Enrico Granatafa1f6172011-10-24 17:22:21 +0000490 Locker locker(this,
491 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
492 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000493
494 bool success = false;
495
Greg Clayton63094e02010-06-23 01:19:29 +0000496 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000497 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000498 // Find the correct script interpreter dictionary in the main module.
Enrico Granata400105d2012-03-06 23:42:15 +0000499 PyObject *script_interpreter_dict = FindSessionDictionary(m_dictionary_name.c_str());
500 if (script_interpreter_dict != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000501 {
Enrico Granata400105d2012-03-06 23:42:15 +0000502 PyObject *pfunc = (PyObject*)m_run_one_line;
503 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
504 if (pmod != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000505 {
Enrico Granata400105d2012-03-06 23:42:15 +0000506 PyObject *pmod_dict = PyModule_GetDict (pmod);
507 if ((pmod_dict != NULL)
508 && PyDict_Check (pmod_dict))
Caroline Tice4a461da2011-01-14 21:09:29 +0000509 {
Enrico Granata400105d2012-03-06 23:42:15 +0000510 if (!pfunc)
Caroline Tice4a461da2011-01-14 21:09:29 +0000511 {
512 PyObject *key, *value;
513 Py_ssize_t pos = 0;
514
515 while (PyDict_Next (pmod_dict, &pos, &key, &value))
516 {
517 Py_INCREF (key);
518 Py_INCREF (value);
519 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
520 {
521 pfunc = value;
522 break;
523 }
524 }
Enrico Granata400105d2012-03-06 23:42:15 +0000525 m_run_one_line = pfunc;
526 }
527
528 if (pfunc && PyCallable_Check (pfunc))
529 {
530 PyObject *pargs = Py_BuildValue("(Os)",script_interpreter_dict,command);
531 if (pargs != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000532 {
Enrico Granata400105d2012-03-06 23:42:15 +0000533 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
534 Py_DECREF (pargs);
535 if (pvalue != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000536 {
Enrico Granata400105d2012-03-06 23:42:15 +0000537 Py_DECREF (pvalue);
538 success = true;
539 }
540 else if (PyErr_Occurred ())
541 {
542 PyErr_Print();
543 PyErr_Clear();
Caroline Tice4a461da2011-01-14 21:09:29 +0000544 }
545 }
546 }
547 }
Caroline Tice4a461da2011-01-14 21:09:29 +0000548 }
Enrico Granata400105d2012-03-06 23:42:15 +0000549 Py_INCREF (script_interpreter_dict);
Caroline Tice4a461da2011-01-14 21:09:29 +0000550 }
Greg Clayton63094e02010-06-23 01:19:29 +0000551
Caroline Tice4a461da2011-01-14 21:09:29 +0000552 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000553 return true;
554
555 // The one-liner failed. Append the error message.
556 if (result)
557 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
558 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000559 }
Johnny Chen60dde642010-07-30 22:33:14 +0000560
561 if (result)
562 result->AppendError ("empty command passed to python\n");
563 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000564}
565
Chris Lattner24943d22010-06-08 16:52:24 +0000566size_t
567ScriptInterpreterPython::InputReaderCallback
568(
569 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000570 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000571 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000572 const char *bytes,
573 size_t bytes_len
574)
575{
Caroline Tice2ade6112010-11-10 19:18:14 +0000576 lldb::thread_t embedded_interpreter_thread;
577 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
578
Chris Lattner24943d22010-06-08 16:52:24 +0000579 if (baton == NULL)
580 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000581
582 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000583
Caroline Tice0aa2e552011-01-14 00:29:16 +0000584 if (script_interpreter->m_script_lang != eScriptLanguagePython)
585 return 0;
586
Caroline Tice892fadd2011-06-16 16:27:19 +0000587 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
588 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
589
Chris Lattner24943d22010-06-08 16:52:24 +0000590 switch (notification)
591 {
592 case eInputReaderActivate:
593 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000594 if (!batch_mode)
595 {
596 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
597 out_stream->Flush();
598 }
Greg Clayton58928562011-02-09 01:08:52 +0000599
Chris Lattner24943d22010-06-08 16:52:24 +0000600 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000601 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
602 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000603 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000604
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000605 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000606
Caroline Tice202f6b82011-01-17 21:55:19 +0000607 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000608 ScriptInterpreterPython::Locker locker(script_interpreter,
609 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
610 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000611 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000612
Caroline Tice2ade6112010-11-10 19:18:14 +0000613 char error_str[1024];
614 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
615 sizeof(error_str)))
616 {
617 if (log)
618 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
619 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
620 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
621 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
622 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000623 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000624 {
625 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000626 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000627 Error detach_error;
628 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
629 }
630 else
631 {
632 if (log)
633 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
634 reader.SetIsDone (true);
635 }
636 }
637 else
638 {
639 if (log)
640 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
641 reader.SetIsDone (true);
642 }
Chris Lattner24943d22010-06-08 16:52:24 +0000643 }
644 break;
645
646 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000647 // When another input reader is pushed, don't leave the session...
648 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000649 break;
650
651 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000652 {
Greg Claytona1cec242012-01-06 00:47:38 +0000653 // Don't try and acquire the interpreter lock here because code like
654 // this:
655 //
656 // (lldb) script
657 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
658 //
659 // This will cause the process to run. The interpreter lock is taken
660 // by the input reader for the "script" command. If we try and acquire
661 // the lock here, when the process runs it might deactivate this input
662 // reader (if STDIN is hooked up to the inferior process) and
663 // reactivate it when the process stops which will deadlock.
664 //ScriptInterpreterPython::Locker locker(script_interpreter,
665 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
666 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000667 }
Chris Lattner24943d22010-06-08 16:52:24 +0000668 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000669
Caroline Tice4a348082011-05-02 20:41:46 +0000670 case eInputReaderAsynchronousOutputWritten:
671 break;
672
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000673 case eInputReaderInterrupt:
674 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
675 break;
676
677 case eInputReaderEndOfFile:
678 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
679 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000680
681 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000682 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000683 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000684 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000685 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000686 bytes_len);
687 if (bytes && bytes_len)
688 {
689 if ((int) bytes[0] == 4)
690 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
691 else
692 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
693 }
694 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000695 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000696 else
697 {
698 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000699 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000700 bytes,
701 bytes_len);
702 reader.SetIsDone (true);
703 }
704
Chris Lattner24943d22010-06-08 16:52:24 +0000705 break;
706
707 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000708 script_interpreter->LeaveSession ();
709
Chris Lattner24943d22010-06-08 16:52:24 +0000710 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000711 if (log)
712 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000713
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000714 script_interpreter->RestoreTerminalState ();
715
Caroline Tice2ade6112010-11-10 19:18:14 +0000716 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000717 break;
718 }
719
720 return bytes_len;
721}
722
723
724void
Greg Clayton238c0a12010-09-18 01:14:36 +0000725ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000726{
727 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
728
Caroline Tice0aa2e552011-01-14 00:29:16 +0000729 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000730
731 // At the moment, the only time the debugger does not have an input file handle is when this is called
732 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
733 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
734 // do it.
735
Greg Clayton58928562011-02-09 01:08:52 +0000736 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000737 return;
738
Greg Clayton63094e02010-06-23 01:19:29 +0000739 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000740 if (reader_sp)
741 {
742 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
743 this, // baton
744 eInputReaderGranularityLine, // token size, to pass to callback function
745 NULL, // end token
746 NULL, // prompt
747 true)); // echo input
748
749 if (error.Success())
750 {
Greg Clayton63094e02010-06-23 01:19:29 +0000751 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000752 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000753 }
754 }
755}
756
757bool
758ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000759 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000760 void *ret_value)
761{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000762
Enrico Granatafa1f6172011-10-24 17:22:21 +0000763 Locker locker(this,
764 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
765 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000766
Chris Lattner24943d22010-06-08 16:52:24 +0000767 PyObject *py_return = NULL;
768 PyObject *mainmod = PyImport_AddModule ("__main__");
769 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000770 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000771 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000772 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000773 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000774 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000775
Enrico Granata400105d2012-03-06 23:42:15 +0000776 locals = FindSessionDictionary(m_dictionary_name.c_str());
777
Caroline Tice0aa2e552011-01-14 00:29:16 +0000778 if (locals == NULL)
779 {
780 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
781 should_decrement_locals = true;
782 }
783
784 if (locals == NULL)
785 {
786 locals = globals;
787 should_decrement_locals = false;
788 }
789
790 py_error = PyErr_Occurred();
791 if (py_error != NULL)
792 PyErr_Clear();
793
Chris Lattner24943d22010-06-08 16:52:24 +0000794 if (in_string != NULL)
795 {
796 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
797 if (py_return == NULL)
798 {
799 py_error = PyErr_Occurred ();
800 if (py_error != NULL)
801 PyErr_Clear ();
802
803 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
804 }
805
Caroline Tice0aa2e552011-01-14 00:29:16 +0000806 if (locals != NULL
807 && should_decrement_locals)
808 Py_DECREF (locals);
809
Chris Lattner24943d22010-06-08 16:52:24 +0000810 if (py_return != NULL)
811 {
812 switch (return_type)
813 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000814 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000815 {
816 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000817 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000818 break;
819 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000820 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000821 {
822 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000823 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000824 break;
825 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000826 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000827 {
828 const char format[2] = "b";
829 success = PyArg_Parse (py_return, format, (bool *) ret_value);
830 break;
831 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000832 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000833 {
834 const char format[2] = "h";
835 success = PyArg_Parse (py_return, format, (short *) ret_value);
836 break;
837 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000838 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000839 {
840 const char format[2] = "H";
841 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
842 break;
843 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000844 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000845 {
846 const char format[2] = "i";
847 success = PyArg_Parse (py_return, format, (int *) ret_value);
848 break;
849 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000850 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000851 {
852 const char format[2] = "I";
853 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
854 break;
855 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000856 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000857 {
858 const char format[2] = "l";
859 success = PyArg_Parse (py_return, format, (long *) ret_value);
860 break;
861 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000862 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000863 {
864 const char format[2] = "k";
865 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
866 break;
867 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000868 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000869 {
870 const char format[2] = "L";
871 success = PyArg_Parse (py_return, format, (long long *) ret_value);
872 break;
873 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000874 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000875 {
876 const char format[2] = "K";
877 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
878 break;
879 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000880 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000881 {
882 const char format[2] = "f";
883 success = PyArg_Parse (py_return, format, (float *) ret_value);
884 break;
885 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000886 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000887 {
888 const char format[2] = "d";
889 success = PyArg_Parse (py_return, format, (double *) ret_value);
890 break;
891 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000892 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000893 {
894 const char format[2] = "c";
895 success = PyArg_Parse (py_return, format, (char *) ret_value);
896 break;
897 }
898 default:
899 {}
900 }
901 Py_DECREF (py_return);
902 if (success)
903 ret_success = true;
904 else
905 ret_success = false;
906 }
907 }
908
909 py_error = PyErr_Occurred();
910 if (py_error != NULL)
911 {
912 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
913 PyErr_Print ();
914 PyErr_Clear();
915 ret_success = false;
916 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000917
Chris Lattner24943d22010-06-08 16:52:24 +0000918 return ret_success;
919}
920
921bool
922ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
923{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000924
925
926 Locker locker(this,
927 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
928 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000929
Chris Lattner24943d22010-06-08 16:52:24 +0000930 bool success = false;
931 PyObject *py_return = NULL;
932 PyObject *mainmod = PyImport_AddModule ("__main__");
933 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000934 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000935 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000936 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000937
Enrico Granata400105d2012-03-06 23:42:15 +0000938 locals = FindSessionDictionary(m_dictionary_name.c_str());
939
Caroline Tice0aa2e552011-01-14 00:29:16 +0000940 if (locals == NULL)
941 {
942 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
943 should_decrement_locals = true;
944 }
945
946 if (locals == NULL)
947 {
948 locals = globals;
949 should_decrement_locals = false;
950 }
951
952 py_error = PyErr_Occurred();
953 if (py_error != NULL)
954 PyErr_Clear();
955
Chris Lattner24943d22010-06-08 16:52:24 +0000956 if (in_string != NULL)
957 {
958 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
959 if (compiled_node)
960 {
961 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
962 if (compiled_code)
963 {
964 py_return = PyEval_EvalCode (compiled_code, globals, locals);
965 if (py_return != NULL)
966 {
967 success = true;
968 Py_DECREF (py_return);
969 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000970 if (locals && should_decrement_locals)
971 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000972 }
973 }
974 }
975
976 py_error = PyErr_Occurred ();
977 if (py_error != NULL)
978 {
979 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
980 PyErr_Print ();
981 PyErr_Clear();
982 success = false;
983 }
984
985 return success;
986}
987
988static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
989
990size_t
991ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
992(
993 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000994 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000995 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000996 const char *bytes,
997 size_t bytes_len
998)
999{
Caroline Tice892fadd2011-06-16 16:27:19 +00001000 static StringList commands_in_progress;
1001
1002 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1003 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1004
Chris Lattner24943d22010-06-08 16:52:24 +00001005 switch (notification)
1006 {
1007 case eInputReaderActivate:
1008 {
1009 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +00001010 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +00001011 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001012 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001013 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +00001014 out_stream->Printf ("%s", reader.GetPrompt());
1015 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001016 }
1017 }
1018 break;
1019
1020 case eInputReaderDeactivate:
1021 break;
1022
1023 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001024 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001025 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001026 out_stream->Printf ("%s", reader.GetPrompt());
1027 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001028 }
Chris Lattner24943d22010-06-08 16:52:24 +00001029 break;
1030
Caroline Tice4a348082011-05-02 20:41:46 +00001031 case eInputReaderAsynchronousOutputWritten:
1032 break;
1033
Chris Lattner24943d22010-06-08 16:52:24 +00001034 case eInputReaderGotToken:
1035 {
1036 std::string temp_string (bytes, bytes_len);
1037 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001038 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001039 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001040 out_stream->Printf ("%s", reader.GetPrompt());
1041 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001042 }
Chris Lattner24943d22010-06-08 16:52:24 +00001043 }
1044 break;
1045
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001046 case eInputReaderEndOfFile:
1047 case eInputReaderInterrupt:
1048 // Control-c (SIGINT) & control-d both mean finish & exit.
1049 reader.SetIsDone(true);
1050
1051 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1052 if (notification == eInputReaderInterrupt)
1053 commands_in_progress.Clear();
1054
1055 // Fall through here...
1056
Chris Lattner24943d22010-06-08 16:52:24 +00001057 case eInputReaderDone:
1058 {
1059 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1060 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1061 data_ap->user_source.AppendList (commands_in_progress);
1062 if (data_ap.get())
1063 {
Greg Clayton63094e02010-06-23 01:19:29 +00001064 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001065 if (interpreter)
1066 {
1067 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1068 data_ap->script_source))
1069 {
Enrico Granata400105d2012-03-06 23:42:15 +00001070 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1071 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001072 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001073 else if (!batch_mode)
1074 {
1075 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1076 out_stream->Flush();
1077 }
Chris Lattner24943d22010-06-08 16:52:24 +00001078 }
1079 else
1080 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001081 if (!batch_mode)
1082 {
1083 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1084 out_stream->Flush();
1085 }
Chris Lattner24943d22010-06-08 16:52:24 +00001086 }
1087 }
1088 }
1089 break;
1090
1091 }
1092
1093 return bytes_len;
1094}
1095
1096void
Greg Clayton238c0a12010-09-18 01:14:36 +00001097ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001098 CommandReturnObject &result)
1099{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001100 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1101
Greg Clayton63094e02010-06-23 01:19:29 +00001102 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001103
1104 if (reader_sp)
1105 {
1106 Error err = reader_sp->Initialize (
1107 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1108 bp_options, // baton
1109 eInputReaderGranularityLine, // token size, for feeding data to callback function
1110 "DONE", // end token
1111 "> ", // prompt
1112 true); // echo input
1113
1114 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001115 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001116 else
1117 {
1118 result.AppendError (err.AsCString());
1119 result.SetStatus (eReturnStatusFailed);
1120 }
1121 }
1122 else
1123 {
1124 result.AppendError("out of memory");
1125 result.SetStatus (eReturnStatusFailed);
1126 }
1127}
1128
Johnny Chen3e0571b2010-09-11 00:23:59 +00001129// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001130void
Greg Clayton238c0a12010-09-18 01:14:36 +00001131ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001132 const char *oneliner)
1133{
1134 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1135
1136 // It's necessary to set both user_source and script_source to the oneliner.
1137 // The former is used to generate callback description (as in breakpoint command list)
1138 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001139
Johnny Chend1c2dca2010-09-10 18:21:10 +00001140 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001141
Caroline Tice5136f942010-09-27 21:35:15 +00001142 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1143 {
Enrico Granata400105d2012-03-06 23:42:15 +00001144 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1145 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Caroline Tice5136f942010-09-27 21:35:15 +00001146 }
1147
Johnny Chend1c2dca2010-09-10 18:21:10 +00001148 return;
1149}
1150
Chris Lattner24943d22010-06-08 16:52:24 +00001151bool
1152ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1153{
1154 // Convert StringList to one long, newline delimited, const char *.
Enrico Granata400105d2012-03-06 23:42:15 +00001155 std::string function_def_string(function_def.CopyList());
Chris Lattner24943d22010-06-08 16:52:24 +00001156
1157 return ExecuteMultipleLines (function_def_string.c_str());
1158}
1159
Enrico Granataf7a9b142011-07-15 02:26:42 +00001160bool
Enrico Granata400105d2012-03-06 23:42:15 +00001161ScriptInterpreterPython::GenerateFunction(const char *signature, const StringList &input)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001162{
1163 int num_lines = input.GetSize ();
1164 if (num_lines == 0)
1165 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001166
1167 if (!signature || *signature == 0)
1168 return false;
1169
Enrico Granataf7a9b142011-07-15 02:26:42 +00001170 StreamString sstr;
1171 StringList auto_generated_function;
Enrico Granata400105d2012-03-06 23:42:15 +00001172 auto_generated_function.AppendString (signature);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001173 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1174 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1175 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1176 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1177 // global dictionary.
1178
1179 // Wrap everything up inside the function, increasing the indentation.
1180
1181 for (int i = 0; i < num_lines; ++i)
1182 {
1183 sstr.Clear ();
1184 sstr.Printf (" %s", input.GetStringAtIndex (i));
1185 auto_generated_function.AppendString (sstr.GetData());
1186 }
1187 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1188 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1189 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1190 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1191
1192 // Verify that the results are valid Python.
1193
1194 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1195 return false;
1196
1197 return true;
1198
1199}
1200
Enrico Granataf7a9b142011-07-15 02:26:42 +00001201bool
Enrico Granata400105d2012-03-06 23:42:15 +00001202ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001203{
Enrico Granata400105d2012-03-06 23:42:15 +00001204 static uint32_t num_created_functions = 0;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001205 user_input.RemoveBlankLines ();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001206 StreamString sstr;
1207
1208 // Check to see if we have any data; if not, just return.
1209 if (user_input.GetSize() == 0)
1210 return false;
1211
1212 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1213 // ValueObject as parameter to the function.
1214
Enrico Granata400105d2012-03-06 23:42:15 +00001215 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_type_print_func", num_created_functions, name_token));
Enrico Granataf7a9b142011-07-15 02:26:42 +00001216 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
Enrico Granataf7a9b142011-07-15 02:26:42 +00001217
Enrico Granata400105d2012-03-06 23:42:15 +00001218 if (!GenerateFunction(sstr.GetData(), user_input))
Enrico Granataf7a9b142011-07-15 02:26:42 +00001219 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001220
Enrico Granataf7a9b142011-07-15 02:26:42 +00001221 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001222 output.assign(auto_generated_function_name);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001223 return true;
1224}
1225
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001226bool
Enrico Granata400105d2012-03-06 23:42:15 +00001227ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, std::string &output)
Enrico Granatac2a28252011-08-16 16:49:25 +00001228{
Enrico Granata400105d2012-03-06 23:42:15 +00001229 static uint32_t num_created_functions = 0;
Enrico Granatac2a28252011-08-16 16:49:25 +00001230 user_input.RemoveBlankLines ();
Enrico Granatac2a28252011-08-16 16:49:25 +00001231 StreamString sstr;
1232
1233 // Check to see if we have any data; if not, just return.
1234 if (user_input.GetSize() == 0)
1235 return false;
1236
Enrico Granata400105d2012-03-06 23:42:15 +00001237 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_cmd_alias_func", num_created_functions));
1238
Enrico Granata271568f2011-09-09 01:41:30 +00001239 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001240
Enrico Granata400105d2012-03-06 23:42:15 +00001241 if (!GenerateFunction(sstr.GetData(),user_input))
Enrico Granatac2a28252011-08-16 16:49:25 +00001242 return false;
1243
1244 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001245 output.assign(auto_generated_function_name);
Enrico Granatac2a28252011-08-16 16:49:25 +00001246 return true;
1247}
1248
1249
1250bool
Enrico Granata400105d2012-03-06 23:42:15 +00001251ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, std::string &output, void* name_token)
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001252{
Enrico Granata400105d2012-03-06 23:42:15 +00001253 static uint32_t num_created_classes = 0;
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001254 user_input.RemoveBlankLines ();
1255 int num_lines = user_input.GetSize ();
1256 StreamString sstr;
1257
1258 // Check to see if we have any data; if not, just return.
1259 if (user_input.GetSize() == 0)
1260 return false;
1261
1262 // Wrap all user input into a Python class
1263
Enrico Granata400105d2012-03-06 23:42:15 +00001264 std::string auto_generated_class_name(GenerateUniqueName("lldb_autogen_python_type_synth_class",num_created_classes,name_token));
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001265
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001266 StringList auto_generated_class;
1267
1268 // Create the function name & definition string.
1269
1270 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1271 auto_generated_class.AppendString (sstr.GetData());
1272
1273 // Wrap everything up inside the class, increasing the indentation.
1274
1275 for (int i = 0; i < num_lines; ++i)
1276 {
1277 sstr.Clear ();
1278 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1279 auto_generated_class.AppendString (sstr.GetData());
1280 }
1281
1282
1283 // Verify that the results are valid Python.
1284 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1285 // (TODO: rename that method to ExportDefinitionToInterpreter)
1286 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1287 return false;
1288
1289 // Store the name of the auto-generated class
1290
Enrico Granata400105d2012-03-06 23:42:15 +00001291 output.assign(auto_generated_class_name);
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001292 return true;
1293}
1294
Enrico Granata400105d2012-03-06 23:42:15 +00001295lldb::ScriptInterpreterObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001296ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1297 lldb::ValueObjectSP valobj)
1298{
1299 if (class_name.empty())
Enrico Granata400105d2012-03-06 23:42:15 +00001300 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001301
1302 if (!valobj.get())
Enrico Granata400105d2012-03-06 23:42:15 +00001303 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001304
Greg Claytonb4d7fc02012-02-17 07:49:44 +00001305 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1306 Target *target = exe_ctx.GetTargetPtr();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001307
1308 if (!target)
Enrico Granata400105d2012-03-06 23:42:15 +00001309 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001310
1311 Debugger &debugger = target->GetDebugger();
1312 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1313 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1314
1315 if (!script_interpreter)
Enrico Granata400105d2012-03-06 23:42:15 +00001316 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001317
1318 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001319
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001320 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001321 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001322 ret_val = g_swig_synthetic_script (class_name,
1323 python_interpreter->m_dictionary_name.c_str(),
1324 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001325 }
1326
Enrico Granata400105d2012-03-06 23:42:15 +00001327 return MakeScriptObject(ret_val);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001328}
1329
Enrico Granataf7a9b142011-07-15 02:26:42 +00001330bool
Enrico Granata400105d2012-03-06 23:42:15 +00001331ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001332{
Enrico Granata16376ed2012-02-15 02:34:21 +00001333 StringList input;
1334 input.SplitIntoLines(oneliner, strlen(oneliner));
1335 return GenerateTypeScriptFunction(input, output, name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001336}
1337
Chris Lattner24943d22010-06-08 16:52:24 +00001338bool
Enrico Granata400105d2012-03-06 23:42:15 +00001339ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, std::string& output, void* name_token)
Enrico Granata16376ed2012-02-15 02:34:21 +00001340{
1341 StringList input;
1342 input.SplitIntoLines(oneliner, strlen(oneliner));
1343 return GenerateTypeSynthClass(input, output, name_token);
1344}
1345
1346
1347bool
Enrico Granata400105d2012-03-06 23:42:15 +00001348ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, std::string& output)
Chris Lattner24943d22010-06-08 16:52:24 +00001349{
Enrico Granata400105d2012-03-06 23:42:15 +00001350 static uint32_t num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001351 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001352 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001353
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001354 if (user_input.GetSize() == 0)
1355 return false;
1356
Enrico Granata400105d2012-03-06 23:42:15 +00001357 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_bp_callback_func_",num_created_functions));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001358 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001359
Enrico Granata400105d2012-03-06 23:42:15 +00001360 if (!GenerateFunction(sstr.GetData(), user_input))
Caroline Ticeb447e842010-09-21 19:25:28 +00001361 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001362
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001363 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001364 output.assign(auto_generated_function_name);
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001365 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001366}
1367
Enrico Granata1328b142012-02-29 03:28:49 +00001368bool
1369ScriptInterpreterPython::GetScriptedSummary (const char *python_function_name,
1370 lldb::ValueObjectSP valobj,
1371 lldb::ScriptInterpreterObjectSP& callee_wrapper_sp,
1372 std::string& retval)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001373{
1374
Enrico Granata1328b142012-02-29 03:28:49 +00001375 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001376
1377 if (!valobj.get())
Enrico Granata1328b142012-02-29 03:28:49 +00001378 {
1379 retval.assign("<no object>");
1380 return false;
1381 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001382
Enrico Granata1328b142012-02-29 03:28:49 +00001383 void* old_callee = (callee_wrapper_sp ? callee_wrapper_sp->GetObject() : NULL);
1384 void* new_callee = old_callee;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001385
Enrico Granata1328b142012-02-29 03:28:49 +00001386 bool ret_val;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001387 if (python_function_name
1388 && *python_function_name)
1389 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001390 {
Enrico Granata1328b142012-02-29 03:28:49 +00001391 Locker py_lock(this);
1392 {
1393 Timer scoped_timer ("g_swig_typescript_callback","g_swig_typescript_callback");
1394 ret_val = g_swig_typescript_callback (python_function_name,
1395 FindSessionDictionary(m_dictionary_name.c_str()),
1396 valobj,
1397 &new_callee,
1398 retval);
1399 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001400 }
1401 }
1402 else
Enrico Granata1328b142012-02-29 03:28:49 +00001403 {
1404 retval.assign("<no function name>");
1405 return false;
1406 }
1407
1408 if (new_callee && old_callee != new_callee)
1409 callee_wrapper_sp = MakeScriptObject(new_callee);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001410
1411 return ret_val;
1412
1413}
1414
Greg Clayton5144f382010-10-07 17:14:24 +00001415bool
1416ScriptInterpreterPython::BreakpointCallbackFunction
1417(
1418 void *baton,
1419 StoppointCallbackContext *context,
1420 user_id_t break_id,
1421 user_id_t break_loc_id
1422)
1423{
1424 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
Enrico Granata400105d2012-03-06 23:42:15 +00001425 const char *python_function_name = bp_option_data->script_source.c_str();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001426
1427 if (!context)
1428 return true;
1429
Greg Claytonf4124de2012-02-21 00:09:25 +00001430 ExecutionContext exe_ctx (context->exe_ctx_ref);
1431 Target *target = exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001432
1433 if (!target)
1434 return true;
1435
1436 Debugger &debugger = target->GetDebugger();
1437 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1438 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1439
1440 if (!script_interpreter)
1441 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001442
1443 if (python_function_name != NULL
1444 && python_function_name[0] != '\0')
1445 {
Greg Claytonf4124de2012-02-21 00:09:25 +00001446 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001447 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001448 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001449 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001450 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1451
1452 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001453 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001454 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001455 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001456 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001457 ret_val = g_swig_breakpoint_callback (python_function_name,
1458 python_interpreter->m_dictionary_name.c_str(),
1459 stop_frame_sp,
1460 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001461 }
1462 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001463 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001464 }
Greg Clayton5144f382010-10-07 17:14:24 +00001465 }
1466 // We currently always true so we stop in case anything goes wrong when
1467 // trying to call the script function
1468 return true;
1469}
Caroline Tice2ade6112010-11-10 19:18:14 +00001470
1471lldb::thread_result_t
1472ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1473{
1474 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1475
1476 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1477
1478 if (log)
1479 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1480
1481 char error_str[1024];
1482 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001483
Enrico Granatafa1f6172011-10-24 17:22:21 +00001484 Locker locker(script_interpreter,
1485 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1486 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1487
1488 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001489 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001490 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001491
Caroline Tice0aa2e552011-01-14 00:29:16 +00001492 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1493 PyRun_SimpleString (run_string.GetData());
1494 run_string.Clear ();
1495
1496 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1497 PyRun_SimpleString (run_string.GetData());
1498 run_string.Clear ();
1499
1500 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1501 PyRun_SimpleString (run_string.GetData());
1502 run_string.Clear ();
1503
1504 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1505 pty_slave_name);
1506 PyRun_SimpleString (run_string.GetData());
1507 run_string.Clear ();
1508
Johnny Chen8054ba32011-03-11 00:28:50 +00001509 // The following call drops into the embedded interpreter loop and stays there until the
1510 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001511
Caroline Ticece207c12011-03-11 00:21:55 +00001512 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001513 // 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 +00001514 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1515
1516 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1517 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1518 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1519 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1520 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1521 // hang (it's happened before).
1522
Caroline Tice9d352ce2011-03-07 23:24:28 +00001523 Py_BEGIN_ALLOW_THREADS
1524 PyGILState_STATE gstate = PyGILState_Ensure();
1525
Caroline Tice0aa2e552011-01-14 00:29:16 +00001526 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1527 PyRun_SimpleString (run_string.GetData());
1528 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001529
Caroline Tice9d352ce2011-03-07 23:24:28 +00001530 PyGILState_Release (gstate);
1531 Py_END_ALLOW_THREADS
1532
Caroline Tice0aa2e552011-01-14 00:29:16 +00001533 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1534 PyRun_SimpleString (run_string.GetData());
1535 run_string.Clear();
1536
1537 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1538 PyRun_SimpleString (run_string.GetData());
1539 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001540
Caroline Tice2ade6112010-11-10 19:18:14 +00001541 }
1542
1543 if (script_interpreter->m_embedded_thread_input_reader_sp)
1544 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1545
1546 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001547
Caroline Tice2ade6112010-11-10 19:18:14 +00001548 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1549 if (log)
1550 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1551
1552
Johnny Chen8054ba32011-03-11 00:28:50 +00001553 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001554 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001555 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1556 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1557 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001558
Caroline Tice2ade6112010-11-10 19:18:14 +00001559 return NULL;
1560}
1561
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001562uint32_t
Enrico Granata400105d2012-03-06 23:42:15 +00001563ScriptInterpreterPython::CalculateNumChildren (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001564{
Enrico Granata400105d2012-03-06 23:42:15 +00001565 if (!implementor_sp)
1566 return 0;
1567
1568 void* implementor = implementor_sp->GetObject();
1569
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001570 if (!implementor)
1571 return 0;
1572
1573 if (!g_swig_calc_children)
1574 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001575
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001576 uint32_t ret_val = 0;
1577
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001578 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001579 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001580 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001581 }
1582
1583 return ret_val;
1584}
1585
Enrico Granata91544802011-09-06 19:20:51 +00001586lldb::ValueObjectSP
Enrico Granata400105d2012-03-06 23:42:15 +00001587ScriptInterpreterPython::GetChildAtIndex (const lldb::ScriptInterpreterObjectSP& implementor_sp, uint32_t idx)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001588{
Enrico Granata400105d2012-03-06 23:42:15 +00001589 if (!implementor_sp)
1590 return lldb::ValueObjectSP();
1591
1592 void* implementor = implementor_sp->GetObject();
1593
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001594 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001595 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001596
Enrico Granata91544802011-09-06 19:20:51 +00001597 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1598 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001599
Enrico Granata91544802011-09-06 19:20:51 +00001600 void* child_ptr = NULL;
1601 lldb::SBValue* value_sb = NULL;
1602 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001603
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001604 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001605 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +00001606 child_ptr = g_swig_get_child_index (implementor,idx);
1607 if (child_ptr != NULL && child_ptr != Py_None)
1608 {
1609 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1610 if (value_sb == NULL)
1611 Py_XDECREF(child_ptr);
1612 else
1613 ret_val = value_sb->get_sp();
1614 }
1615 else
1616 {
1617 Py_XDECREF(child_ptr);
1618 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001619 }
1620
1621 return ret_val;
1622}
1623
1624int
Enrico Granata400105d2012-03-06 23:42:15 +00001625ScriptInterpreterPython::GetIndexOfChildWithName (const lldb::ScriptInterpreterObjectSP& implementor_sp, const char* child_name)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001626{
Enrico Granata400105d2012-03-06 23:42:15 +00001627 if (!implementor_sp)
1628 return UINT32_MAX;
1629
1630 void* implementor = implementor_sp->GetObject();
1631
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001632 if (!implementor)
1633 return UINT32_MAX;
1634
1635 if (!g_swig_get_index_child)
1636 return UINT32_MAX;
1637
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001638 int ret_val = UINT32_MAX;
1639
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001640 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001641 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001642 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001643 }
1644
1645 return ret_val;
1646}
1647
Enrico Granata979e20d2011-07-29 19:53:35 +00001648void
Enrico Granata400105d2012-03-06 23:42:15 +00001649ScriptInterpreterPython::UpdateSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata979e20d2011-07-29 19:53:35 +00001650{
Enrico Granata400105d2012-03-06 23:42:15 +00001651 if (!implementor_sp)
1652 return;
1653
1654 void* implementor = implementor_sp->GetObject();
1655
Enrico Granata979e20d2011-07-29 19:53:35 +00001656 if (!implementor)
1657 return;
1658
1659 if (!g_swig_update_provider)
1660 return;
1661
Enrico Granata979e20d2011-07-29 19:53:35 +00001662 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001663 Locker py_lock(this);
Enrico Granata979e20d2011-07-29 19:53:35 +00001664 g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001665 }
1666
1667 return;
1668}
1669
Enrico Granatac2a28252011-08-16 16:49:25 +00001670bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001671ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00001672 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00001673 lldb_private::Error& error)
1674{
1675 if (!pathname || !pathname[0])
1676 {
1677 error.SetErrorString("invalid pathname");
1678 return false;
1679 }
1680
1681 if (!g_swig_call_module_init)
1682 {
1683 error.SetErrorString("internal helper function missing");
1684 return false;
1685 }
1686
Greg Clayton13d24fb2012-01-29 20:56:30 +00001687 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granatafa1f6172011-10-24 17:22:21 +00001688
Enrico Granata59df36f2011-10-17 21:45:27 +00001689 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001690 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00001691
1692 FileSpec target_file(pathname, true);
1693
1694 // TODO: would we want to reject any other value?
1695 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1696 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1697 {
1698 error.SetErrorString("invalid pathname");
1699 return false;
1700 }
1701
1702 const char* directory = target_file.GetDirectory().GetCString();
1703 std::string basename(target_file.GetFilename().GetCString());
1704
1705 // now make sure that Python has "directory" in the search path
1706 StreamString command_stream;
1707 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1708 directory,
1709 directory);
Enrico Granatafa1f6172011-10-24 17:22:21 +00001710 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData());
Enrico Granata59df36f2011-10-17 21:45:27 +00001711 if (!syspath_retval)
1712 {
1713 error.SetErrorString("Python sys.path handling failed");
1714 return false;
1715 }
1716
1717 // strip .py or .pyc extension
1718 ConstString extension = target_file.GetFileNameExtension();
1719 if (::strcmp(extension.GetCString(), "py") == 0)
1720 basename.resize(basename.length()-3);
1721 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1722 basename.resize(basename.length()-4);
1723
1724 // check if the module is already import-ed
1725 command_stream.Clear();
1726 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1727 int refcount = 0;
1728 // this call will fail if the module does not exist (because the parameter to it is not a string
1729 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00001730 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
1731 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0);
1732 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00001733 {
1734 error.SetErrorString("module already imported");
1735 return false;
1736 }
1737
1738 // now actually do the import
1739 command_stream.Clear();
1740 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafa1f6172011-10-24 17:22:21 +00001741 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL);
Enrico Granata59df36f2011-10-17 21:45:27 +00001742 if (!import_retval)
1743 {
1744 error.SetErrorString("Python import statement failed");
1745 return false;
1746 }
1747
Enrico Granata16376ed2012-02-15 02:34:21 +00001748 // call __lldb_init_module(debugger,dict)
Enrico Granata59df36f2011-10-17 21:45:27 +00001749 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001750 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001751 debugger_sp))
1752 {
Enrico Granata16376ed2012-02-15 02:34:21 +00001753 error.SetErrorString("calling __lldb_init_module failed");
Enrico Granata59df36f2011-10-17 21:45:27 +00001754 return false;
1755 }
1756 return true;
1757 }
1758}
1759
Enrico Granata1328b142012-02-29 03:28:49 +00001760lldb::ScriptInterpreterObjectSP
1761ScriptInterpreterPython::MakeScriptObject (void* object)
1762{
1763 return lldb::ScriptInterpreterObjectSP(new ScriptInterpreterPythonObject(object));
1764}
1765
Enrico Granata6010ace2011-11-07 22:57:04 +00001766ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
1767 ScriptedCommandSynchronicity synchro) :
1768 m_debugger_sp(debugger_sp),
1769 m_synch_wanted(synchro),
1770 m_old_asynch(debugger_sp->GetAsyncExecution())
1771{
1772 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
1773 m_debugger_sp->SetAsyncExecution(false);
1774 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
1775 m_debugger_sp->SetAsyncExecution(true);
1776}
1777
1778ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
1779{
1780 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
1781 m_debugger_sp->SetAsyncExecution(m_old_asynch);
1782}
1783
Enrico Granata59df36f2011-10-17 21:45:27 +00001784bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001785ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1786 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00001787 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001788 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001789 Error& error)
1790{
1791 if (!impl_function)
1792 {
1793 error.SetErrorString("no function to execute");
1794 return false;
1795 }
1796
1797 if (!g_swig_call_command)
1798 {
1799 error.SetErrorString("no helper function to run scripted commands");
1800 return false;
1801 }
1802
Greg Clayton13d24fb2012-01-29 20:56:30 +00001803 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata6010ace2011-11-07 22:57:04 +00001804
1805 if (!debugger_sp.get())
1806 {
1807 error.SetErrorString("invalid Debugger pointer");
1808 return false;
1809 }
Enrico Granatac2a28252011-08-16 16:49:25 +00001810
1811 bool ret_val;
1812
1813 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00001814
Enrico Granatac2a28252011-08-16 16:49:25 +00001815 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001816 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00001817 SynchronicityHandler synch_handler(debugger_sp,
1818 synchronicity);
1819
Enrico Granatac2a28252011-08-16 16:49:25 +00001820 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001821 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00001822 debugger_sp,
1823 args,
1824 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001825 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001826 }
Enrico Granata6010ace2011-11-07 22:57:04 +00001827
Enrico Granatac2a28252011-08-16 16:49:25 +00001828 if (!ret_val)
1829 error.SetErrorString(err_msg.c_str());
1830 else
1831 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00001832
Enrico Granatac2a28252011-08-16 16:49:25 +00001833 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00001834}
1835
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001836// in Python, a special attribute __doc__ contains the docstring
1837// for an object (function, method, class, ...) if any is defined
1838// Otherwise, the attribute's value is None
1839std::string
1840ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1841{
1842 std::string command(item);
1843 command += ".__doc__";
1844
1845 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1846
1847 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001848 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001849 &result_ptr) && result_ptr)
1850 {
1851 return std::string(result_ptr);
1852 }
1853 else
1854 return std::string("");
1855}
Caroline Tice2ade6112010-11-10 19:18:14 +00001856
Caroline Tice0aa2e552011-01-14 00:29:16 +00001857void
Enrico Granata1328b142012-02-29 03:28:49 +00001858ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback)
Greg Claytone86cbb92011-03-22 01:14:58 +00001859{
1860 g_swig_init_callback = python_swig_init_callback;
Enrico Granata1328b142012-02-29 03:28:49 +00001861 g_swig_breakpoint_callback = LLDBSwigPythonBreakpointCallbackFunction;
1862 g_swig_typescript_callback = LLDBSwigPythonCallTypeScript;
1863 g_swig_synthetic_script = LLDBSwigPythonCreateSyntheticProvider;
1864 g_swig_calc_children = LLDBSwigPython_CalculateNumChildren;
1865 g_swig_get_child_index = LLDBSwigPython_GetChildAtIndex;
1866 g_swig_get_index_child = LLDBSwigPython_GetIndexOfChildWithName;
1867 g_swig_cast_to_sbvalue = LLDBSWIGPython_CastPyObjectToSBValue;
1868 g_swig_update_provider = LLDBSwigPython_UpdateSynthProviderInstance;
1869 g_swig_call_command = LLDBSwigPythonCallCommand;
1870 g_swig_call_module_init = LLDBSwigPythonCallModuleInit;
Greg Claytone86cbb92011-03-22 01:14:58 +00001871}
1872
1873void
1874ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001875{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001876 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1877
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001878 // Python will muck with STDIN terminal state, so save off any current TTY
1879 // settings so we can restore them.
1880 TerminalState stdin_tty_state;
1881 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001882
Caroline Tice9d352ce2011-03-07 23:24:28 +00001883 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001884 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001885
Greg Claytone86cbb92011-03-22 01:14:58 +00001886 // Initialize SWIG after setting up python
1887 assert (g_swig_init_callback != NULL);
1888 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001889
1890 // Update the path python uses to search for modules to include the current directory.
1891
Caroline Ticed4d92832011-06-13 21:33:00 +00001892 PyRun_SimpleString ("import sys");
1893 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001894
1895 // Find the module that owns this code and use that path we get to
1896 // set the sys.path appropriately.
1897
1898 FileSpec file_spec;
1899 char python_dir_path[PATH_MAX];
1900 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1901 {
1902 std::string python_path("sys.path.insert(0,\"");
1903 size_t orig_len = python_path.length();
1904 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1905 {
1906 python_path.append (python_dir_path);
1907 python_path.append ("\")");
1908 PyRun_SimpleString (python_path.c_str());
1909 python_path.resize (orig_len);
1910 }
1911
1912 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1913 {
1914 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1915 {
1916 python_path.append (python_dir_path);
1917 python_path.append ("\")");
1918 PyRun_SimpleString (python_path.c_str());
1919 python_path.resize (orig_len);
1920 }
1921 }
1922 }
1923
Jim Ingham4dfa5112011-08-22 19:10:09 +00001924 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001925
Caroline Ticed4d92832011-06-13 21:33:00 +00001926 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001927
Caroline Ticed4d92832011-06-13 21:33:00 +00001928 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1929 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00001930 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001931
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001932 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001933}
1934
Greg Claytone86cbb92011-03-22 01:14:58 +00001935//void
1936//ScriptInterpreterPython::Terminate ()
1937//{
1938// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1939// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1940// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1941// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1942// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1943// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1944// // within Py_Finalize, which results in a seg fault.
1945// //
1946// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1947// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1948// // process exits).
1949// //
1950//// Py_Finalize ();
1951//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00001952
1953#endif // #ifdef LLDB_DISABLE_PYTHON