blob: 81bbf3f11acf195b16725f4841caafa0fd629158 [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);
Enrico Granatacf09f882012-03-19 22:58:49 +000094extern "C" bool LLDBSwigPython_UpdateSynthProviderInstance (void* implementor);
Enrico Granata1328b142012-02-29 03:28:49 +000095
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),
Johnny Chenc65046d2012-03-08 20:53:04 +0000243 m_old_sysout (NULL),
244 m_old_syserr (NULL),
Enrico Granata400105d2012-03-06 23:42:15 +0000245 m_run_one_line (NULL),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000246 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000247 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000248 m_session_is_active (false),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000249 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000250{
251
Greg Clayton7c330d62011-01-27 01:01:10 +0000252 static int g_initialized = false;
253
254 if (!g_initialized)
255 {
256 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000257 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000258 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000259
260 Locker locker(this,
261 ScriptInterpreterPython::Locker::AcquireLock,
262 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Greg Clayton7c330d62011-01-27 01:01:10 +0000263
Caroline Tice0aa2e552011-01-14 00:29:16 +0000264 m_dictionary_name.append("_dict");
265 StreamString run_string;
266 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
267 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000268
Caroline Tice0aa2e552011-01-14 00:29:16 +0000269 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000270
271 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
272 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
273 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
274 // call to Debugger::Terminate is made, the ref-count has the correct value.
275 //
276 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
277 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000278
Caroline Tice0aa2e552011-01-14 00:29:16 +0000279 int old_count = Debugger::TestDebuggerRefCount();
Greg Claytonb302dff2012-02-01 08:09:32 +0000280
Chris Lattner24943d22010-06-08 16:52:24 +0000281
Enrico Granata66205ce2012-03-12 19:47:17 +0000282 run_string.Printf ("run_one_line (%s, 'import copy, os, re, sys, uuid, lldb, gnu_libstdcpp, libcxx, objc')", m_dictionary_name.c_str());
Caroline Tice0aa2e552011-01-14 00:29:16 +0000283 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000284
Enrico Granata8f84cfb2012-02-23 23:10:03 +0000285 // WARNING: temporary code that loads Cocoa formatters - this should be done on a per-platform basis rather than loading the whole set
286 // and letting the individual formatter classes exploit APIs to check whether they can/cannot do their task
287 run_string.Clear();
Enrico Granatade3b25b2012-03-03 00:45:57 +0000288 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 +0000289 PyRun_SimpleString (run_string.GetData());
Greg Claytonb302dff2012-02-01 08:09:32 +0000290
Caroline Tice0aa2e552011-01-14 00:29:16 +0000291 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000292
Caroline Tice0aa2e552011-01-14 00:29:16 +0000293 if (new_count > old_count)
294 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000295
Caroline Tice0aa2e552011-01-14 00:29:16 +0000296 run_string.Clear();
Greg Clayton444e35b2011-10-19 18:09:39 +0000297 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000298 interpreter.GetDebugger().GetID());
299 PyRun_SimpleString (run_string.GetData());
300
301 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000302 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000303 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000304 }
Chris Lattner24943d22010-06-08 16:52:24 +0000305}
306
307ScriptInterpreterPython::~ScriptInterpreterPython ()
308{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000309 Debugger &debugger = GetCommandInterpreter().GetDebugger();
310
311 if (m_embedded_thread_input_reader_sp.get() != NULL)
312 {
313 m_embedded_thread_input_reader_sp->SetIsDone (true);
314 m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000315 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
316 m_embedded_thread_input_reader_sp.reset();
317 debugger.PopInputReader (reader_sp);
318 }
319
320 if (m_new_sysout)
321 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000322 Locker locker(this,
323 ScriptInterpreterPython::Locker::AcquireLock,
324 ScriptInterpreterPython::Locker::FreeLock);
325 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000326 }
Chris Lattner24943d22010-06-08 16:52:24 +0000327}
328
Caroline Tice0aa2e552011-01-14 00:29:16 +0000329void
330ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
331{
332 if (fh == NULL)
333 return;
334
335 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000336
Johnny Chenc65046d2012-03-08 20:53:04 +0000337 Locker locker(this,
338 ScriptInterpreterPython::Locker::AcquireLock,
339 ScriptInterpreterPython::Locker::FreeAcquiredLock);
340
Enrico Granata91544802011-09-06 19:20:51 +0000341 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000342}
343
344void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000345ScriptInterpreterPython::SaveTerminalState (int fd)
346{
347 // Python mucks with the terminal state of STDIN. If we can possibly avoid
348 // this by setting the file handles up correctly prior to entering the
349 // interpreter we should. For now we save and restore the terminal state
350 // on the input file handle.
351 m_terminal_state.Save (fd, false);
352}
353
354void
355ScriptInterpreterPython::RestoreTerminalState ()
356{
357 // Python mucks with the terminal state of STDIN. If we can possibly avoid
358 // this by setting the file handles up correctly prior to entering the
359 // interpreter we should. For now we save and restore the terminal state
360 // on the input file handle.
361 m_terminal_state.Restore();
362}
363
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000364void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000365ScriptInterpreterPython::LeaveSession ()
366{
Johnny Chen41641f92012-02-29 01:52:13 +0000367 PyObject *sysmod = PyImport_AddModule ("sys");
368 PyObject *sysdict = PyModule_GetDict (sysmod);
369
370 if (m_new_sysout && sysmod && sysdict)
371 {
Johnny Chenc65046d2012-03-08 20:53:04 +0000372 if (m_old_sysout)
373 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_old_sysout);
374 if (m_old_syserr)
375 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_old_syserr);
Johnny Chen41641f92012-02-29 01:52:13 +0000376 }
377
Caroline Tice0aa2e552011-01-14 00:29:16 +0000378 m_session_is_active = false;
379}
380
381void
382ScriptInterpreterPython::EnterSession ()
383{
384 // If we have already entered the session, without having officially 'left' it, then there is no need to
385 // 'enter' it again.
386
387 if (m_session_is_active)
388 return;
389
390 m_session_is_active = true;
391
Caroline Tice202f6b82011-01-17 21:55:19 +0000392 StreamString run_string;
393
Greg Clayton2fecc452012-01-28 02:11:02 +0000394 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %llu", m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
395 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)", GetCommandInterpreter().GetDebugger().GetID());
396 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
397 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
398 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
399 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
400 // Make sure STDIN is closed since when we run this as an embedded
401 // interpreter we don't want someone to call "line = sys.stdin.readline()"
402 // and lock up. We don't have multiple windows and when the interpreter is
403 // embedded we don't know we should be feeding input to the embedded
404 // interpreter or to the python sys.stdin. We also don't want to let python
405 // play with the real stdin from this process, so we need to close it...
Greg Clayton3eeaf6e2012-02-03 01:30:30 +0000406 //run_string.PutCString ("; sys.stdin.close()");
Greg Clayton2fecc452012-01-28 02:11:02 +0000407 run_string.PutCString ("')");
Caroline Tice0aa2e552011-01-14 00:29:16 +0000408
Caroline Tice6af65cb2011-05-03 21:21:50 +0000409 PyRun_SimpleString (run_string.GetData());
410 run_string.Clear();
Johnny Chen41641f92012-02-29 01:52:13 +0000411
Caroline Tice0aa2e552011-01-14 00:29:16 +0000412 PyObject *sysmod = PyImport_AddModule ("sys");
413 PyObject *sysdict = PyModule_GetDict (sysmod);
Johnny Chen41641f92012-02-29 01:52:13 +0000414
Greg Clayton2fecc452012-01-28 02:11:02 +0000415 if (m_new_sysout && sysmod && sysdict)
416 {
Johnny Chen41641f92012-02-29 01:52:13 +0000417 m_old_sysout = PyDict_GetItemString(sysdict, "stdout");
418 m_old_syserr = PyDict_GetItemString(sysdict, "stderr");
Johnny Chenc65046d2012-03-08 20:53:04 +0000419 if (m_new_sysout)
420 {
421 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
422 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
423 }
Greg Clayton2fecc452012-01-28 02:11:02 +0000424 }
Johnny Chen41641f92012-02-29 01:52:13 +0000425
Caroline Tice0aa2e552011-01-14 00:29:16 +0000426 if (PyErr_Occurred())
427 PyErr_Clear ();
Greg Clayton2fecc452012-01-28 02:11:02 +0000428}
Caroline Tice0aa2e552011-01-14 00:29:16 +0000429
Enrico Granata400105d2012-03-06 23:42:15 +0000430static PyObject*
431FindSessionDictionary (const char* dict_name)
432{
433 static std::map<ConstString,PyObject*> g_dict_map;
434
435 ConstString dict(dict_name);
436
437 std::map<ConstString,PyObject*>::iterator iter = g_dict_map.find(dict);
438
439 if (iter != g_dict_map.end())
440 return iter->second;
441
442 PyObject *main_mod = PyImport_AddModule ("__main__");
443 if (main_mod != NULL)
444 {
445 PyObject *main_dict = PyModule_GetDict (main_mod);
446 if ((main_dict != NULL)
447 && PyDict_Check (main_dict))
448 {
449 // Go through the main dictionary looking for the correct python script interpreter dictionary
450 PyObject *key, *value;
451 Py_ssize_t pos = 0;
452
453 while (PyDict_Next (main_dict, &pos, &key, &value))
454 {
455 // We have stolen references to the key and value objects in the dictionary; we need to increment
456 // them now so that Python's garbage collector doesn't collect them out from under us.
457 Py_INCREF (key);
458 Py_INCREF (value);
459 if (strcmp (PyString_AsString (key), dict_name) == 0)
460 {
461 g_dict_map[dict] = value;
462 return value;
463 }
464 }
465 }
466 }
467 return NULL;
468}
469
470static std::string
471GenerateUniqueName (const char* base_name_wanted,
472 uint32_t& functions_counter,
473 void* name_token = NULL)
474{
475 StreamString sstr;
476
477 if (!base_name_wanted)
478 return std::string();
479
480 if (!name_token)
481 sstr.Printf ("%s_%d", base_name_wanted, functions_counter++);
482 else
483 sstr.Printf ("%s_%p", base_name_wanted, name_token);
484
485 return sstr.GetString();
486}
487
Johnny Chen60dde642010-07-30 22:33:14 +0000488bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000489ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000490{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000491 if (!m_valid_session)
492 return false;
493
Caroline Tice4a461da2011-01-14 21:09:29 +0000494 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
495 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
496 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
497 // method to pass the command string directly down to Python.
498
Enrico Granatafa1f6172011-10-24 17:22:21 +0000499 Locker locker(this,
500 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
501 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000502
503 bool success = false;
504
Greg Clayton63094e02010-06-23 01:19:29 +0000505 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000506 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000507 // Find the correct script interpreter dictionary in the main module.
Enrico Granata400105d2012-03-06 23:42:15 +0000508 PyObject *script_interpreter_dict = FindSessionDictionary(m_dictionary_name.c_str());
509 if (script_interpreter_dict != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000510 {
Enrico Granata400105d2012-03-06 23:42:15 +0000511 PyObject *pfunc = (PyObject*)m_run_one_line;
512 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
513 if (pmod != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000514 {
Enrico Granata400105d2012-03-06 23:42:15 +0000515 PyObject *pmod_dict = PyModule_GetDict (pmod);
516 if ((pmod_dict != NULL)
517 && PyDict_Check (pmod_dict))
Caroline Tice4a461da2011-01-14 21:09:29 +0000518 {
Enrico Granata400105d2012-03-06 23:42:15 +0000519 if (!pfunc)
Caroline Tice4a461da2011-01-14 21:09:29 +0000520 {
521 PyObject *key, *value;
522 Py_ssize_t pos = 0;
523
524 while (PyDict_Next (pmod_dict, &pos, &key, &value))
525 {
526 Py_INCREF (key);
527 Py_INCREF (value);
528 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
529 {
530 pfunc = value;
531 break;
532 }
533 }
Enrico Granata400105d2012-03-06 23:42:15 +0000534 m_run_one_line = pfunc;
535 }
536
537 if (pfunc && PyCallable_Check (pfunc))
538 {
539 PyObject *pargs = Py_BuildValue("(Os)",script_interpreter_dict,command);
540 if (pargs != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000541 {
Enrico Granata400105d2012-03-06 23:42:15 +0000542 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
543 Py_DECREF (pargs);
544 if (pvalue != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000545 {
Enrico Granata400105d2012-03-06 23:42:15 +0000546 Py_DECREF (pvalue);
547 success = true;
548 }
549 else if (PyErr_Occurred ())
550 {
551 PyErr_Print();
552 PyErr_Clear();
Caroline Tice4a461da2011-01-14 21:09:29 +0000553 }
554 }
555 }
556 }
Caroline Tice4a461da2011-01-14 21:09:29 +0000557 }
Enrico Granata400105d2012-03-06 23:42:15 +0000558 Py_INCREF (script_interpreter_dict);
Caroline Tice4a461da2011-01-14 21:09:29 +0000559 }
Greg Clayton63094e02010-06-23 01:19:29 +0000560
Caroline Tice4a461da2011-01-14 21:09:29 +0000561 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000562 return true;
563
564 // The one-liner failed. Append the error message.
565 if (result)
566 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
567 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000568 }
Johnny Chen60dde642010-07-30 22:33:14 +0000569
570 if (result)
571 result->AppendError ("empty command passed to python\n");
572 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000573}
574
Chris Lattner24943d22010-06-08 16:52:24 +0000575size_t
576ScriptInterpreterPython::InputReaderCallback
577(
578 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000579 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000580 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000581 const char *bytes,
582 size_t bytes_len
583)
584{
Caroline Tice2ade6112010-11-10 19:18:14 +0000585 lldb::thread_t embedded_interpreter_thread;
586 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
587
Chris Lattner24943d22010-06-08 16:52:24 +0000588 if (baton == NULL)
589 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000590
591 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000592
Caroline Tice0aa2e552011-01-14 00:29:16 +0000593 if (script_interpreter->m_script_lang != eScriptLanguagePython)
594 return 0;
595
Caroline Tice892fadd2011-06-16 16:27:19 +0000596 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
597 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
598
Chris Lattner24943d22010-06-08 16:52:24 +0000599 switch (notification)
600 {
601 case eInputReaderActivate:
602 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000603 if (!batch_mode)
604 {
605 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
606 out_stream->Flush();
607 }
Greg Clayton58928562011-02-09 01:08:52 +0000608
Chris Lattner24943d22010-06-08 16:52:24 +0000609 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000610 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
611 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000612 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000613
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000614 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000615
Caroline Tice202f6b82011-01-17 21:55:19 +0000616 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000617 ScriptInterpreterPython::Locker locker(script_interpreter,
618 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
619 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000620 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000621
Caroline Tice2ade6112010-11-10 19:18:14 +0000622 char error_str[1024];
623 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
624 sizeof(error_str)))
625 {
626 if (log)
627 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
628 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
629 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
630 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
631 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000632 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000633 {
634 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000635 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000636 Error detach_error;
637 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
638 }
639 else
640 {
641 if (log)
642 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
643 reader.SetIsDone (true);
644 }
645 }
646 else
647 {
648 if (log)
649 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
650 reader.SetIsDone (true);
651 }
Chris Lattner24943d22010-06-08 16:52:24 +0000652 }
653 break;
654
655 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000656 // When another input reader is pushed, don't leave the session...
657 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000658 break;
659
660 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000661 {
Greg Claytona1cec242012-01-06 00:47:38 +0000662 // Don't try and acquire the interpreter lock here because code like
663 // this:
664 //
665 // (lldb) script
666 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
667 //
668 // This will cause the process to run. The interpreter lock is taken
669 // by the input reader for the "script" command. If we try and acquire
670 // the lock here, when the process runs it might deactivate this input
671 // reader (if STDIN is hooked up to the inferior process) and
672 // reactivate it when the process stops which will deadlock.
673 //ScriptInterpreterPython::Locker locker(script_interpreter,
674 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
675 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000676 }
Chris Lattner24943d22010-06-08 16:52:24 +0000677 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000678
Caroline Tice4a348082011-05-02 20:41:46 +0000679 case eInputReaderAsynchronousOutputWritten:
680 break;
681
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000682 case eInputReaderInterrupt:
683 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
684 break;
685
686 case eInputReaderEndOfFile:
687 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
688 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000689
690 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000691 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000692 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000693 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000694 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000695 bytes_len);
696 if (bytes && bytes_len)
697 {
698 if ((int) bytes[0] == 4)
699 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
700 else
701 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
702 }
703 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000704 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000705 else
706 {
707 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000708 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000709 bytes,
710 bytes_len);
711 reader.SetIsDone (true);
712 }
713
Chris Lattner24943d22010-06-08 16:52:24 +0000714 break;
715
716 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000717 script_interpreter->LeaveSession ();
718
Chris Lattner24943d22010-06-08 16:52:24 +0000719 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000720 if (log)
721 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000722
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000723 script_interpreter->RestoreTerminalState ();
724
Caroline Tice2ade6112010-11-10 19:18:14 +0000725 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000726 break;
727 }
728
729 return bytes_len;
730}
731
732
733void
Greg Clayton238c0a12010-09-18 01:14:36 +0000734ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000735{
736 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
737
Caroline Tice0aa2e552011-01-14 00:29:16 +0000738 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000739
740 // At the moment, the only time the debugger does not have an input file handle is when this is called
741 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
742 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
743 // do it.
744
Greg Clayton58928562011-02-09 01:08:52 +0000745 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000746 return;
747
Greg Clayton63094e02010-06-23 01:19:29 +0000748 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000749 if (reader_sp)
750 {
751 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
752 this, // baton
753 eInputReaderGranularityLine, // token size, to pass to callback function
754 NULL, // end token
755 NULL, // prompt
756 true)); // echo input
757
758 if (error.Success())
759 {
Greg Clayton63094e02010-06-23 01:19:29 +0000760 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000761 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000762 }
763 }
764}
765
766bool
767ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000768 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000769 void *ret_value)
770{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000771
Enrico Granatafa1f6172011-10-24 17:22:21 +0000772 Locker locker(this,
773 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
774 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000775
Chris Lattner24943d22010-06-08 16:52:24 +0000776 PyObject *py_return = NULL;
777 PyObject *mainmod = PyImport_AddModule ("__main__");
778 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000779 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000780 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000781 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000782 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000783 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000784
Enrico Granata400105d2012-03-06 23:42:15 +0000785 locals = FindSessionDictionary(m_dictionary_name.c_str());
786
Caroline Tice0aa2e552011-01-14 00:29:16 +0000787 if (locals == NULL)
788 {
789 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
790 should_decrement_locals = true;
791 }
792
793 if (locals == NULL)
794 {
795 locals = globals;
796 should_decrement_locals = false;
797 }
798
799 py_error = PyErr_Occurred();
800 if (py_error != NULL)
801 PyErr_Clear();
802
Chris Lattner24943d22010-06-08 16:52:24 +0000803 if (in_string != NULL)
804 {
805 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
806 if (py_return == NULL)
807 {
808 py_error = PyErr_Occurred ();
809 if (py_error != NULL)
810 PyErr_Clear ();
811
812 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
813 }
814
Caroline Tice0aa2e552011-01-14 00:29:16 +0000815 if (locals != NULL
816 && should_decrement_locals)
817 Py_DECREF (locals);
818
Chris Lattner24943d22010-06-08 16:52:24 +0000819 if (py_return != NULL)
820 {
821 switch (return_type)
822 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000823 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000824 {
825 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000826 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000827 break;
828 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000829 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000830 {
831 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000832 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000833 break;
834 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000835 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000836 {
837 const char format[2] = "b";
838 success = PyArg_Parse (py_return, format, (bool *) ret_value);
839 break;
840 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000841 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000842 {
843 const char format[2] = "h";
844 success = PyArg_Parse (py_return, format, (short *) ret_value);
845 break;
846 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000847 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000848 {
849 const char format[2] = "H";
850 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
851 break;
852 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000853 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000854 {
855 const char format[2] = "i";
856 success = PyArg_Parse (py_return, format, (int *) ret_value);
857 break;
858 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000859 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000860 {
861 const char format[2] = "I";
862 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
863 break;
864 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000865 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000866 {
867 const char format[2] = "l";
868 success = PyArg_Parse (py_return, format, (long *) ret_value);
869 break;
870 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000871 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000872 {
873 const char format[2] = "k";
874 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
875 break;
876 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000877 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000878 {
879 const char format[2] = "L";
880 success = PyArg_Parse (py_return, format, (long long *) ret_value);
881 break;
882 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000883 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000884 {
885 const char format[2] = "K";
886 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
887 break;
888 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000889 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000890 {
891 const char format[2] = "f";
892 success = PyArg_Parse (py_return, format, (float *) ret_value);
893 break;
894 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000895 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000896 {
897 const char format[2] = "d";
898 success = PyArg_Parse (py_return, format, (double *) ret_value);
899 break;
900 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000901 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000902 {
903 const char format[2] = "c";
904 success = PyArg_Parse (py_return, format, (char *) ret_value);
905 break;
906 }
907 default:
908 {}
909 }
910 Py_DECREF (py_return);
911 if (success)
912 ret_success = true;
913 else
914 ret_success = false;
915 }
916 }
917
918 py_error = PyErr_Occurred();
919 if (py_error != NULL)
920 {
921 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
922 PyErr_Print ();
923 PyErr_Clear();
924 ret_success = false;
925 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000926
Chris Lattner24943d22010-06-08 16:52:24 +0000927 return ret_success;
928}
929
930bool
931ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
932{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000933
934
935 Locker locker(this,
936 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
937 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000938
Chris Lattner24943d22010-06-08 16:52:24 +0000939 bool success = false;
940 PyObject *py_return = NULL;
941 PyObject *mainmod = PyImport_AddModule ("__main__");
942 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000943 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000944 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000945 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000946
Enrico Granata400105d2012-03-06 23:42:15 +0000947 locals = FindSessionDictionary(m_dictionary_name.c_str());
948
Caroline Tice0aa2e552011-01-14 00:29:16 +0000949 if (locals == NULL)
950 {
951 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
952 should_decrement_locals = true;
953 }
954
955 if (locals == NULL)
956 {
957 locals = globals;
958 should_decrement_locals = false;
959 }
960
961 py_error = PyErr_Occurred();
962 if (py_error != NULL)
963 PyErr_Clear();
964
Chris Lattner24943d22010-06-08 16:52:24 +0000965 if (in_string != NULL)
966 {
967 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
968 if (compiled_node)
969 {
970 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
971 if (compiled_code)
972 {
973 py_return = PyEval_EvalCode (compiled_code, globals, locals);
974 if (py_return != NULL)
975 {
976 success = true;
977 Py_DECREF (py_return);
978 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000979 if (locals && should_decrement_locals)
980 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000981 }
982 }
983 }
984
985 py_error = PyErr_Occurred ();
986 if (py_error != NULL)
987 {
988 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
989 PyErr_Print ();
990 PyErr_Clear();
991 success = false;
992 }
993
994 return success;
995}
996
997static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
998
999size_t
1000ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1001(
1002 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001003 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001004 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001005 const char *bytes,
1006 size_t bytes_len
1007)
1008{
Caroline Tice892fadd2011-06-16 16:27:19 +00001009 static StringList commands_in_progress;
1010
1011 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1012 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1013
Chris Lattner24943d22010-06-08 16:52:24 +00001014 switch (notification)
1015 {
1016 case eInputReaderActivate:
1017 {
1018 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +00001019 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +00001020 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001021 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001022 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +00001023 out_stream->Printf ("%s", reader.GetPrompt());
1024 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001025 }
1026 }
1027 break;
1028
1029 case eInputReaderDeactivate:
1030 break;
1031
1032 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001033 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001034 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001035 out_stream->Printf ("%s", reader.GetPrompt());
1036 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001037 }
Chris Lattner24943d22010-06-08 16:52:24 +00001038 break;
1039
Caroline Tice4a348082011-05-02 20:41:46 +00001040 case eInputReaderAsynchronousOutputWritten:
1041 break;
1042
Chris Lattner24943d22010-06-08 16:52:24 +00001043 case eInputReaderGotToken:
1044 {
1045 std::string temp_string (bytes, bytes_len);
1046 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001047 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001048 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001049 out_stream->Printf ("%s", reader.GetPrompt());
1050 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001051 }
Chris Lattner24943d22010-06-08 16:52:24 +00001052 }
1053 break;
1054
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001055 case eInputReaderEndOfFile:
1056 case eInputReaderInterrupt:
1057 // Control-c (SIGINT) & control-d both mean finish & exit.
1058 reader.SetIsDone(true);
1059
1060 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1061 if (notification == eInputReaderInterrupt)
1062 commands_in_progress.Clear();
1063
1064 // Fall through here...
1065
Chris Lattner24943d22010-06-08 16:52:24 +00001066 case eInputReaderDone:
1067 {
1068 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1069 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1070 data_ap->user_source.AppendList (commands_in_progress);
1071 if (data_ap.get())
1072 {
Greg Clayton63094e02010-06-23 01:19:29 +00001073 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001074 if (interpreter)
1075 {
1076 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1077 data_ap->script_source))
1078 {
Enrico Granata400105d2012-03-06 23:42:15 +00001079 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1080 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001081 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001082 else if (!batch_mode)
1083 {
1084 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1085 out_stream->Flush();
1086 }
Chris Lattner24943d22010-06-08 16:52:24 +00001087 }
1088 else
1089 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001090 if (!batch_mode)
1091 {
1092 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1093 out_stream->Flush();
1094 }
Chris Lattner24943d22010-06-08 16:52:24 +00001095 }
1096 }
1097 }
1098 break;
1099
1100 }
1101
1102 return bytes_len;
1103}
1104
1105void
Greg Clayton238c0a12010-09-18 01:14:36 +00001106ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001107 CommandReturnObject &result)
1108{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001109 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1110
Greg Clayton63094e02010-06-23 01:19:29 +00001111 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001112
1113 if (reader_sp)
1114 {
1115 Error err = reader_sp->Initialize (
1116 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1117 bp_options, // baton
1118 eInputReaderGranularityLine, // token size, for feeding data to callback function
1119 "DONE", // end token
1120 "> ", // prompt
1121 true); // echo input
1122
1123 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001124 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001125 else
1126 {
1127 result.AppendError (err.AsCString());
1128 result.SetStatus (eReturnStatusFailed);
1129 }
1130 }
1131 else
1132 {
1133 result.AppendError("out of memory");
1134 result.SetStatus (eReturnStatusFailed);
1135 }
1136}
1137
Johnny Chen3e0571b2010-09-11 00:23:59 +00001138// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001139void
Greg Clayton238c0a12010-09-18 01:14:36 +00001140ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001141 const char *oneliner)
1142{
1143 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1144
1145 // It's necessary to set both user_source and script_source to the oneliner.
1146 // The former is used to generate callback description (as in breakpoint command list)
1147 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001148
Johnny Chend1c2dca2010-09-10 18:21:10 +00001149 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001150
Caroline Tice5136f942010-09-27 21:35:15 +00001151 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1152 {
Enrico Granata400105d2012-03-06 23:42:15 +00001153 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1154 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Caroline Tice5136f942010-09-27 21:35:15 +00001155 }
1156
Johnny Chend1c2dca2010-09-10 18:21:10 +00001157 return;
1158}
1159
Chris Lattner24943d22010-06-08 16:52:24 +00001160bool
1161ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1162{
1163 // Convert StringList to one long, newline delimited, const char *.
Enrico Granata400105d2012-03-06 23:42:15 +00001164 std::string function_def_string(function_def.CopyList());
Chris Lattner24943d22010-06-08 16:52:24 +00001165
1166 return ExecuteMultipleLines (function_def_string.c_str());
1167}
1168
Enrico Granataf7a9b142011-07-15 02:26:42 +00001169bool
Enrico Granata400105d2012-03-06 23:42:15 +00001170ScriptInterpreterPython::GenerateFunction(const char *signature, const StringList &input)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001171{
1172 int num_lines = input.GetSize ();
1173 if (num_lines == 0)
1174 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001175
1176 if (!signature || *signature == 0)
1177 return false;
1178
Enrico Granataf7a9b142011-07-15 02:26:42 +00001179 StreamString sstr;
1180 StringList auto_generated_function;
Enrico Granata400105d2012-03-06 23:42:15 +00001181 auto_generated_function.AppendString (signature);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001182 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1183 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1184 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1185 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1186 // global dictionary.
1187
1188 // Wrap everything up inside the function, increasing the indentation.
1189
1190 for (int i = 0; i < num_lines; ++i)
1191 {
1192 sstr.Clear ();
1193 sstr.Printf (" %s", input.GetStringAtIndex (i));
1194 auto_generated_function.AppendString (sstr.GetData());
1195 }
1196 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1197 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1198 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1199 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1200
1201 // Verify that the results are valid Python.
1202
1203 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1204 return false;
1205
1206 return true;
1207
1208}
1209
Enrico Granataf7a9b142011-07-15 02:26:42 +00001210bool
Enrico Granata400105d2012-03-06 23:42:15 +00001211ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001212{
Enrico Granata400105d2012-03-06 23:42:15 +00001213 static uint32_t num_created_functions = 0;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001214 user_input.RemoveBlankLines ();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001215 StreamString sstr;
1216
1217 // Check to see if we have any data; if not, just return.
1218 if (user_input.GetSize() == 0)
1219 return false;
1220
1221 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1222 // ValueObject as parameter to the function.
1223
Enrico Granata400105d2012-03-06 23:42:15 +00001224 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 +00001225 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
Enrico Granataf7a9b142011-07-15 02:26:42 +00001226
Enrico Granata400105d2012-03-06 23:42:15 +00001227 if (!GenerateFunction(sstr.GetData(), user_input))
Enrico Granataf7a9b142011-07-15 02:26:42 +00001228 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001229
Enrico Granataf7a9b142011-07-15 02:26:42 +00001230 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001231 output.assign(auto_generated_function_name);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001232 return true;
1233}
1234
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001235bool
Enrico Granata400105d2012-03-06 23:42:15 +00001236ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, std::string &output)
Enrico Granatac2a28252011-08-16 16:49:25 +00001237{
Enrico Granata400105d2012-03-06 23:42:15 +00001238 static uint32_t num_created_functions = 0;
Enrico Granatac2a28252011-08-16 16:49:25 +00001239 user_input.RemoveBlankLines ();
Enrico Granatac2a28252011-08-16 16:49:25 +00001240 StreamString sstr;
1241
1242 // Check to see if we have any data; if not, just return.
1243 if (user_input.GetSize() == 0)
1244 return false;
1245
Enrico Granata400105d2012-03-06 23:42:15 +00001246 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_cmd_alias_func", num_created_functions));
1247
Enrico Granata271568f2011-09-09 01:41:30 +00001248 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001249
Enrico Granata400105d2012-03-06 23:42:15 +00001250 if (!GenerateFunction(sstr.GetData(),user_input))
Enrico Granatac2a28252011-08-16 16:49:25 +00001251 return false;
1252
1253 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001254 output.assign(auto_generated_function_name);
Enrico Granatac2a28252011-08-16 16:49:25 +00001255 return true;
1256}
1257
1258
1259bool
Enrico Granata400105d2012-03-06 23:42:15 +00001260ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, std::string &output, void* name_token)
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001261{
Enrico Granata400105d2012-03-06 23:42:15 +00001262 static uint32_t num_created_classes = 0;
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001263 user_input.RemoveBlankLines ();
1264 int num_lines = user_input.GetSize ();
1265 StreamString sstr;
1266
1267 // Check to see if we have any data; if not, just return.
1268 if (user_input.GetSize() == 0)
1269 return false;
1270
1271 // Wrap all user input into a Python class
1272
Enrico Granata400105d2012-03-06 23:42:15 +00001273 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 +00001274
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001275 StringList auto_generated_class;
1276
1277 // Create the function name & definition string.
1278
1279 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1280 auto_generated_class.AppendString (sstr.GetData());
1281
1282 // Wrap everything up inside the class, increasing the indentation.
1283
1284 for (int i = 0; i < num_lines; ++i)
1285 {
1286 sstr.Clear ();
1287 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1288 auto_generated_class.AppendString (sstr.GetData());
1289 }
1290
1291
1292 // Verify that the results are valid Python.
1293 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1294 // (TODO: rename that method to ExportDefinitionToInterpreter)
1295 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1296 return false;
1297
1298 // Store the name of the auto-generated class
1299
Enrico Granata400105d2012-03-06 23:42:15 +00001300 output.assign(auto_generated_class_name);
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001301 return true;
1302}
1303
Enrico Granata400105d2012-03-06 23:42:15 +00001304lldb::ScriptInterpreterObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001305ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1306 lldb::ValueObjectSP valobj)
1307{
1308 if (class_name.empty())
Enrico Granata400105d2012-03-06 23:42:15 +00001309 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001310
1311 if (!valobj.get())
Enrico Granata400105d2012-03-06 23:42:15 +00001312 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001313
Greg Claytonb4d7fc02012-02-17 07:49:44 +00001314 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1315 Target *target = exe_ctx.GetTargetPtr();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001316
1317 if (!target)
Enrico Granata400105d2012-03-06 23:42:15 +00001318 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001319
1320 Debugger &debugger = target->GetDebugger();
1321 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1322 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1323
1324 if (!script_interpreter)
Enrico Granata400105d2012-03-06 23:42:15 +00001325 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001326
1327 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001328
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001329 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001330 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001331 ret_val = g_swig_synthetic_script (class_name,
1332 python_interpreter->m_dictionary_name.c_str(),
1333 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001334 }
1335
Enrico Granata400105d2012-03-06 23:42:15 +00001336 return MakeScriptObject(ret_val);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001337}
1338
Enrico Granataf7a9b142011-07-15 02:26:42 +00001339bool
Enrico Granata400105d2012-03-06 23:42:15 +00001340ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001341{
Enrico Granata16376ed2012-02-15 02:34:21 +00001342 StringList input;
1343 input.SplitIntoLines(oneliner, strlen(oneliner));
1344 return GenerateTypeScriptFunction(input, output, name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001345}
1346
Chris Lattner24943d22010-06-08 16:52:24 +00001347bool
Enrico Granata400105d2012-03-06 23:42:15 +00001348ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, std::string& output, void* name_token)
Enrico Granata16376ed2012-02-15 02:34:21 +00001349{
1350 StringList input;
1351 input.SplitIntoLines(oneliner, strlen(oneliner));
1352 return GenerateTypeSynthClass(input, output, name_token);
1353}
1354
1355
1356bool
Enrico Granata400105d2012-03-06 23:42:15 +00001357ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, std::string& output)
Chris Lattner24943d22010-06-08 16:52:24 +00001358{
Enrico Granata400105d2012-03-06 23:42:15 +00001359 static uint32_t num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001360 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001361 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001362
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001363 if (user_input.GetSize() == 0)
1364 return false;
1365
Enrico Granata400105d2012-03-06 23:42:15 +00001366 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_bp_callback_func_",num_created_functions));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001367 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001368
Enrico Granata400105d2012-03-06 23:42:15 +00001369 if (!GenerateFunction(sstr.GetData(), user_input))
Caroline Ticeb447e842010-09-21 19:25:28 +00001370 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001371
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001372 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001373 output.assign(auto_generated_function_name);
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001374 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001375}
1376
Enrico Granata1328b142012-02-29 03:28:49 +00001377bool
1378ScriptInterpreterPython::GetScriptedSummary (const char *python_function_name,
1379 lldb::ValueObjectSP valobj,
1380 lldb::ScriptInterpreterObjectSP& callee_wrapper_sp,
1381 std::string& retval)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001382{
1383
Enrico Granata1328b142012-02-29 03:28:49 +00001384 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001385
1386 if (!valobj.get())
Enrico Granata1328b142012-02-29 03:28:49 +00001387 {
1388 retval.assign("<no object>");
1389 return false;
1390 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001391
Enrico Granata1328b142012-02-29 03:28:49 +00001392 void* old_callee = (callee_wrapper_sp ? callee_wrapper_sp->GetObject() : NULL);
1393 void* new_callee = old_callee;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001394
Enrico Granata1328b142012-02-29 03:28:49 +00001395 bool ret_val;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001396 if (python_function_name
1397 && *python_function_name)
1398 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001399 {
Enrico Granata1328b142012-02-29 03:28:49 +00001400 Locker py_lock(this);
1401 {
1402 Timer scoped_timer ("g_swig_typescript_callback","g_swig_typescript_callback");
1403 ret_val = g_swig_typescript_callback (python_function_name,
1404 FindSessionDictionary(m_dictionary_name.c_str()),
1405 valobj,
1406 &new_callee,
1407 retval);
1408 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001409 }
1410 }
1411 else
Enrico Granata1328b142012-02-29 03:28:49 +00001412 {
1413 retval.assign("<no function name>");
1414 return false;
1415 }
1416
1417 if (new_callee && old_callee != new_callee)
1418 callee_wrapper_sp = MakeScriptObject(new_callee);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001419
1420 return ret_val;
1421
1422}
1423
Greg Clayton5144f382010-10-07 17:14:24 +00001424bool
1425ScriptInterpreterPython::BreakpointCallbackFunction
1426(
1427 void *baton,
1428 StoppointCallbackContext *context,
1429 user_id_t break_id,
1430 user_id_t break_loc_id
1431)
1432{
1433 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
Enrico Granata400105d2012-03-06 23:42:15 +00001434 const char *python_function_name = bp_option_data->script_source.c_str();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001435
1436 if (!context)
1437 return true;
1438
Greg Claytonf4124de2012-02-21 00:09:25 +00001439 ExecutionContext exe_ctx (context->exe_ctx_ref);
1440 Target *target = exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001441
1442 if (!target)
1443 return true;
1444
1445 Debugger &debugger = target->GetDebugger();
1446 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1447 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1448
1449 if (!script_interpreter)
1450 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001451
1452 if (python_function_name != NULL
1453 && python_function_name[0] != '\0')
1454 {
Greg Claytonf4124de2012-02-21 00:09:25 +00001455 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001456 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001457 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001458 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001459 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1460
1461 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001462 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001463 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001464 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001465 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001466 ret_val = g_swig_breakpoint_callback (python_function_name,
1467 python_interpreter->m_dictionary_name.c_str(),
1468 stop_frame_sp,
1469 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001470 }
1471 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001472 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001473 }
Greg Clayton5144f382010-10-07 17:14:24 +00001474 }
1475 // We currently always true so we stop in case anything goes wrong when
1476 // trying to call the script function
1477 return true;
1478}
Caroline Tice2ade6112010-11-10 19:18:14 +00001479
1480lldb::thread_result_t
1481ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1482{
1483 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1484
1485 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1486
1487 if (log)
1488 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1489
1490 char error_str[1024];
1491 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001492
Enrico Granatafa1f6172011-10-24 17:22:21 +00001493 Locker locker(script_interpreter,
1494 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1495 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1496
1497 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001498 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001499 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001500
Caroline Tice0aa2e552011-01-14 00:29:16 +00001501 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1502 PyRun_SimpleString (run_string.GetData());
1503 run_string.Clear ();
1504
1505 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1506 PyRun_SimpleString (run_string.GetData());
1507 run_string.Clear ();
1508
1509 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1510 PyRun_SimpleString (run_string.GetData());
1511 run_string.Clear ();
1512
1513 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1514 pty_slave_name);
1515 PyRun_SimpleString (run_string.GetData());
1516 run_string.Clear ();
1517
Johnny Chen8054ba32011-03-11 00:28:50 +00001518 // The following call drops into the embedded interpreter loop and stays there until the
1519 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001520
Caroline Ticece207c12011-03-11 00:21:55 +00001521 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001522 // 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 +00001523 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1524
1525 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1526 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1527 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1528 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1529 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1530 // hang (it's happened before).
1531
Caroline Tice9d352ce2011-03-07 23:24:28 +00001532 Py_BEGIN_ALLOW_THREADS
1533 PyGILState_STATE gstate = PyGILState_Ensure();
1534
Caroline Tice0aa2e552011-01-14 00:29:16 +00001535 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1536 PyRun_SimpleString (run_string.GetData());
1537 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001538
Caroline Tice9d352ce2011-03-07 23:24:28 +00001539 PyGILState_Release (gstate);
1540 Py_END_ALLOW_THREADS
1541
Caroline Tice0aa2e552011-01-14 00:29:16 +00001542 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1543 PyRun_SimpleString (run_string.GetData());
1544 run_string.Clear();
1545
1546 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1547 PyRun_SimpleString (run_string.GetData());
1548 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001549
Caroline Tice2ade6112010-11-10 19:18:14 +00001550 }
1551
1552 if (script_interpreter->m_embedded_thread_input_reader_sp)
1553 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1554
1555 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001556
Caroline Tice2ade6112010-11-10 19:18:14 +00001557 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1558 if (log)
1559 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1560
1561
Johnny Chen8054ba32011-03-11 00:28:50 +00001562 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001563 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001564 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1565 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1566 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001567
Caroline Tice2ade6112010-11-10 19:18:14 +00001568 return NULL;
1569}
1570
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001571uint32_t
Enrico Granata400105d2012-03-06 23:42:15 +00001572ScriptInterpreterPython::CalculateNumChildren (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001573{
Enrico Granata400105d2012-03-06 23:42:15 +00001574 if (!implementor_sp)
1575 return 0;
1576
1577 void* implementor = implementor_sp->GetObject();
1578
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001579 if (!implementor)
1580 return 0;
1581
1582 if (!g_swig_calc_children)
1583 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001584
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001585 uint32_t ret_val = 0;
1586
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001587 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001588 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001589 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001590 }
1591
1592 return ret_val;
1593}
1594
Enrico Granata91544802011-09-06 19:20:51 +00001595lldb::ValueObjectSP
Enrico Granata400105d2012-03-06 23:42:15 +00001596ScriptInterpreterPython::GetChildAtIndex (const lldb::ScriptInterpreterObjectSP& implementor_sp, uint32_t idx)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001597{
Enrico Granata400105d2012-03-06 23:42:15 +00001598 if (!implementor_sp)
1599 return lldb::ValueObjectSP();
1600
1601 void* implementor = implementor_sp->GetObject();
1602
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001603 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001604 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001605
Enrico Granata91544802011-09-06 19:20:51 +00001606 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1607 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001608
Enrico Granata91544802011-09-06 19:20:51 +00001609 void* child_ptr = NULL;
1610 lldb::SBValue* value_sb = NULL;
1611 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001612
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001613 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001614 Locker py_lock(this);
Enrico Granata91544802011-09-06 19:20:51 +00001615 child_ptr = g_swig_get_child_index (implementor,idx);
1616 if (child_ptr != NULL && child_ptr != Py_None)
1617 {
1618 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1619 if (value_sb == NULL)
1620 Py_XDECREF(child_ptr);
1621 else
1622 ret_val = value_sb->get_sp();
1623 }
1624 else
1625 {
1626 Py_XDECREF(child_ptr);
1627 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001628 }
1629
1630 return ret_val;
1631}
1632
1633int
Enrico Granata400105d2012-03-06 23:42:15 +00001634ScriptInterpreterPython::GetIndexOfChildWithName (const lldb::ScriptInterpreterObjectSP& implementor_sp, const char* child_name)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001635{
Enrico Granata400105d2012-03-06 23:42:15 +00001636 if (!implementor_sp)
1637 return UINT32_MAX;
1638
1639 void* implementor = implementor_sp->GetObject();
1640
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001641 if (!implementor)
1642 return UINT32_MAX;
1643
1644 if (!g_swig_get_index_child)
1645 return UINT32_MAX;
1646
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001647 int ret_val = UINT32_MAX;
1648
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001649 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001650 Locker py_lock(this);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001651 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001652 }
1653
1654 return ret_val;
1655}
1656
Enrico Granatacf09f882012-03-19 22:58:49 +00001657bool
Enrico Granata400105d2012-03-06 23:42:15 +00001658ScriptInterpreterPython::UpdateSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata979e20d2011-07-29 19:53:35 +00001659{
Enrico Granatacf09f882012-03-19 22:58:49 +00001660 bool ret_val = false;
1661
Enrico Granata400105d2012-03-06 23:42:15 +00001662 if (!implementor_sp)
Enrico Granatacf09f882012-03-19 22:58:49 +00001663 return ret_val;
Enrico Granata400105d2012-03-06 23:42:15 +00001664
1665 void* implementor = implementor_sp->GetObject();
1666
Enrico Granata979e20d2011-07-29 19:53:35 +00001667 if (!implementor)
Enrico Granatacf09f882012-03-19 22:58:49 +00001668 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001669
1670 if (!g_swig_update_provider)
Enrico Granatacf09f882012-03-19 22:58:49 +00001671 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001672
Enrico Granata979e20d2011-07-29 19:53:35 +00001673 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001674 Locker py_lock(this);
Enrico Granatacf09f882012-03-19 22:58:49 +00001675 ret_val = g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001676 }
1677
Enrico Granatacf09f882012-03-19 22:58:49 +00001678 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001679}
1680
Enrico Granatac2a28252011-08-16 16:49:25 +00001681bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001682ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00001683 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00001684 lldb_private::Error& error)
1685{
1686 if (!pathname || !pathname[0])
1687 {
1688 error.SetErrorString("invalid pathname");
1689 return false;
1690 }
1691
1692 if (!g_swig_call_module_init)
1693 {
1694 error.SetErrorString("internal helper function missing");
1695 return false;
1696 }
1697
Greg Clayton13d24fb2012-01-29 20:56:30 +00001698 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granatafa1f6172011-10-24 17:22:21 +00001699
Enrico Granata59df36f2011-10-17 21:45:27 +00001700 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001701 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00001702
1703 FileSpec target_file(pathname, true);
1704
1705 // TODO: would we want to reject any other value?
1706 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1707 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1708 {
1709 error.SetErrorString("invalid pathname");
1710 return false;
1711 }
1712
1713 const char* directory = target_file.GetDirectory().GetCString();
1714 std::string basename(target_file.GetFilename().GetCString());
1715
1716 // now make sure that Python has "directory" in the search path
1717 StreamString command_stream;
1718 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1719 directory,
1720 directory);
Enrico Granatafa1f6172011-10-24 17:22:21 +00001721 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData());
Enrico Granata59df36f2011-10-17 21:45:27 +00001722 if (!syspath_retval)
1723 {
1724 error.SetErrorString("Python sys.path handling failed");
1725 return false;
1726 }
1727
1728 // strip .py or .pyc extension
1729 ConstString extension = target_file.GetFileNameExtension();
1730 if (::strcmp(extension.GetCString(), "py") == 0)
1731 basename.resize(basename.length()-3);
1732 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1733 basename.resize(basename.length()-4);
1734
1735 // check if the module is already import-ed
1736 command_stream.Clear();
1737 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1738 int refcount = 0;
1739 // this call will fail if the module does not exist (because the parameter to it is not a string
1740 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00001741 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
1742 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0);
1743 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00001744 {
1745 error.SetErrorString("module already imported");
1746 return false;
1747 }
1748
1749 // now actually do the import
1750 command_stream.Clear();
1751 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafa1f6172011-10-24 17:22:21 +00001752 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL);
Enrico Granata59df36f2011-10-17 21:45:27 +00001753 if (!import_retval)
1754 {
1755 error.SetErrorString("Python import statement failed");
1756 return false;
1757 }
1758
Enrico Granata16376ed2012-02-15 02:34:21 +00001759 // call __lldb_init_module(debugger,dict)
Enrico Granata59df36f2011-10-17 21:45:27 +00001760 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001761 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001762 debugger_sp))
1763 {
Enrico Granata16376ed2012-02-15 02:34:21 +00001764 error.SetErrorString("calling __lldb_init_module failed");
Enrico Granata59df36f2011-10-17 21:45:27 +00001765 return false;
1766 }
1767 return true;
1768 }
1769}
1770
Enrico Granata1328b142012-02-29 03:28:49 +00001771lldb::ScriptInterpreterObjectSP
1772ScriptInterpreterPython::MakeScriptObject (void* object)
1773{
1774 return lldb::ScriptInterpreterObjectSP(new ScriptInterpreterPythonObject(object));
1775}
1776
Enrico Granata6010ace2011-11-07 22:57:04 +00001777ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
1778 ScriptedCommandSynchronicity synchro) :
1779 m_debugger_sp(debugger_sp),
1780 m_synch_wanted(synchro),
1781 m_old_asynch(debugger_sp->GetAsyncExecution())
1782{
1783 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
1784 m_debugger_sp->SetAsyncExecution(false);
1785 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
1786 m_debugger_sp->SetAsyncExecution(true);
1787}
1788
1789ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
1790{
1791 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
1792 m_debugger_sp->SetAsyncExecution(m_old_asynch);
1793}
1794
Enrico Granata59df36f2011-10-17 21:45:27 +00001795bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001796ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1797 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00001798 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001799 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001800 Error& error)
1801{
1802 if (!impl_function)
1803 {
1804 error.SetErrorString("no function to execute");
1805 return false;
1806 }
1807
1808 if (!g_swig_call_command)
1809 {
1810 error.SetErrorString("no helper function to run scripted commands");
1811 return false;
1812 }
1813
Greg Clayton13d24fb2012-01-29 20:56:30 +00001814 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata6010ace2011-11-07 22:57:04 +00001815
1816 if (!debugger_sp.get())
1817 {
1818 error.SetErrorString("invalid Debugger pointer");
1819 return false;
1820 }
Enrico Granatac2a28252011-08-16 16:49:25 +00001821
1822 bool ret_val;
1823
1824 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00001825
Enrico Granatac2a28252011-08-16 16:49:25 +00001826 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001827 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00001828 SynchronicityHandler synch_handler(debugger_sp,
1829 synchronicity);
1830
Enrico Granatac2a28252011-08-16 16:49:25 +00001831 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001832 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00001833 debugger_sp,
1834 args,
1835 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001836 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001837 }
Enrico Granata6010ace2011-11-07 22:57:04 +00001838
Enrico Granatac2a28252011-08-16 16:49:25 +00001839 if (!ret_val)
1840 error.SetErrorString(err_msg.c_str());
1841 else
1842 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00001843
Enrico Granatac2a28252011-08-16 16:49:25 +00001844 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00001845}
1846
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001847// in Python, a special attribute __doc__ contains the docstring
1848// for an object (function, method, class, ...) if any is defined
1849// Otherwise, the attribute's value is None
1850std::string
1851ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1852{
1853 std::string command(item);
1854 command += ".__doc__";
1855
1856 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1857
1858 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001859 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001860 &result_ptr) && result_ptr)
1861 {
1862 return std::string(result_ptr);
1863 }
1864 else
1865 return std::string("");
1866}
Caroline Tice2ade6112010-11-10 19:18:14 +00001867
Caroline Tice0aa2e552011-01-14 00:29:16 +00001868void
Enrico Granata1328b142012-02-29 03:28:49 +00001869ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback)
Greg Claytone86cbb92011-03-22 01:14:58 +00001870{
1871 g_swig_init_callback = python_swig_init_callback;
Enrico Granata1328b142012-02-29 03:28:49 +00001872 g_swig_breakpoint_callback = LLDBSwigPythonBreakpointCallbackFunction;
1873 g_swig_typescript_callback = LLDBSwigPythonCallTypeScript;
1874 g_swig_synthetic_script = LLDBSwigPythonCreateSyntheticProvider;
1875 g_swig_calc_children = LLDBSwigPython_CalculateNumChildren;
1876 g_swig_get_child_index = LLDBSwigPython_GetChildAtIndex;
1877 g_swig_get_index_child = LLDBSwigPython_GetIndexOfChildWithName;
1878 g_swig_cast_to_sbvalue = LLDBSWIGPython_CastPyObjectToSBValue;
1879 g_swig_update_provider = LLDBSwigPython_UpdateSynthProviderInstance;
1880 g_swig_call_command = LLDBSwigPythonCallCommand;
1881 g_swig_call_module_init = LLDBSwigPythonCallModuleInit;
Greg Claytone86cbb92011-03-22 01:14:58 +00001882}
1883
1884void
1885ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001886{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001887 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1888
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001889 // Python will muck with STDIN terminal state, so save off any current TTY
1890 // settings so we can restore them.
1891 TerminalState stdin_tty_state;
1892 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001893
Caroline Tice9d352ce2011-03-07 23:24:28 +00001894 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001895 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001896
Greg Claytone86cbb92011-03-22 01:14:58 +00001897 // Initialize SWIG after setting up python
1898 assert (g_swig_init_callback != NULL);
1899 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001900
1901 // Update the path python uses to search for modules to include the current directory.
1902
Caroline Ticed4d92832011-06-13 21:33:00 +00001903 PyRun_SimpleString ("import sys");
1904 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001905
1906 // Find the module that owns this code and use that path we get to
1907 // set the sys.path appropriately.
1908
1909 FileSpec file_spec;
1910 char python_dir_path[PATH_MAX];
1911 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1912 {
1913 std::string python_path("sys.path.insert(0,\"");
1914 size_t orig_len = python_path.length();
1915 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1916 {
1917 python_path.append (python_dir_path);
1918 python_path.append ("\")");
1919 PyRun_SimpleString (python_path.c_str());
1920 python_path.resize (orig_len);
1921 }
1922
1923 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1924 {
1925 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1926 {
1927 python_path.append (python_dir_path);
1928 python_path.append ("\")");
1929 PyRun_SimpleString (python_path.c_str());
1930 python_path.resize (orig_len);
1931 }
1932 }
1933 }
1934
Jim Ingham4dfa5112011-08-22 19:10:09 +00001935 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001936
Caroline Ticed4d92832011-06-13 21:33:00 +00001937 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001938
Caroline Ticed4d92832011-06-13 21:33:00 +00001939 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1940 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00001941 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001942
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001943 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001944}
1945
Greg Claytone86cbb92011-03-22 01:14:58 +00001946//void
1947//ScriptInterpreterPython::Terminate ()
1948//{
1949// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1950// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1951// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1952// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1953// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1954// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1955// // within Py_Finalize, which results in a seg fault.
1956// //
1957// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1958// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1959// // process exits).
1960// //
1961//// Py_Finalize ();
1962//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00001963
1964#endif // #ifdef LLDB_DISABLE_PYTHON