blob: 9c84eab00d2d28264b28dd53ed9ffd95a656237c [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
Enrico Granatadba1de82012-03-27 02:35:13 +0000237class ForceDisableSyntheticChildren
238{
239public:
240 ForceDisableSyntheticChildren (Target* target) :
241 m_target(target)
242 {
243 m_old_value = target->GetSuppressSyntheticValue();
244 target->SetSuppressSyntheticValue(true);
245 }
246 ~ForceDisableSyntheticChildren ()
247 {
248 m_target->SetSuppressSyntheticValue(m_old_value);
249 }
250private:
251 Target* m_target;
252 bool m_old_value;
253};
254
Greg Clayton63094e02010-06-23 01:19:29 +0000255ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000256 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000257 m_embedded_python_pty (),
258 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +0000259 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000260 m_new_sysout (NULL),
Johnny Chenc65046d2012-03-08 20:53:04 +0000261 m_old_sysout (NULL),
262 m_old_syserr (NULL),
Enrico Granata400105d2012-03-06 23:42:15 +0000263 m_run_one_line (NULL),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000264 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000265 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000266 m_session_is_active (false),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000267 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000268{
269
Greg Clayton7c330d62011-01-27 01:01:10 +0000270 static int g_initialized = false;
271
272 if (!g_initialized)
273 {
274 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000275 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000276 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000277
278 Locker locker(this,
279 ScriptInterpreterPython::Locker::AcquireLock,
280 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Greg Clayton7c330d62011-01-27 01:01:10 +0000281
Caroline Tice0aa2e552011-01-14 00:29:16 +0000282 m_dictionary_name.append("_dict");
283 StreamString run_string;
284 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
285 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000286
Caroline Tice0aa2e552011-01-14 00:29:16 +0000287 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000288
289 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
290 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
291 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
292 // call to Debugger::Terminate is made, the ref-count has the correct value.
293 //
294 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
295 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000296
Caroline Tice0aa2e552011-01-14 00:29:16 +0000297 int old_count = Debugger::TestDebuggerRefCount();
Greg Claytonb302dff2012-02-01 08:09:32 +0000298
Chris Lattner24943d22010-06-08 16:52:24 +0000299
Enrico Granata66205ce2012-03-12 19:47:17 +0000300 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 +0000301 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000302
Enrico Granata8f84cfb2012-02-23 23:10:03 +0000303 // WARNING: temporary code that loads Cocoa formatters - this should be done on a per-platform basis rather than loading the whole set
304 // and letting the individual formatter classes exploit APIs to check whether they can/cannot do their task
305 run_string.Clear();
Enrico Granatade3b25b2012-03-03 00:45:57 +0000306 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 +0000307 PyRun_SimpleString (run_string.GetData());
Greg Claytonb302dff2012-02-01 08:09:32 +0000308
Caroline Tice0aa2e552011-01-14 00:29:16 +0000309 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000310
Caroline Tice0aa2e552011-01-14 00:29:16 +0000311 if (new_count > old_count)
312 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000313
Caroline Tice0aa2e552011-01-14 00:29:16 +0000314 run_string.Clear();
Greg Clayton444e35b2011-10-19 18:09:39 +0000315 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000316 interpreter.GetDebugger().GetID());
317 PyRun_SimpleString (run_string.GetData());
318
319 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000320 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000321 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000322 }
Chris Lattner24943d22010-06-08 16:52:24 +0000323}
324
325ScriptInterpreterPython::~ScriptInterpreterPython ()
326{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000327 Debugger &debugger = GetCommandInterpreter().GetDebugger();
328
329 if (m_embedded_thread_input_reader_sp.get() != NULL)
330 {
331 m_embedded_thread_input_reader_sp->SetIsDone (true);
332 m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000333 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
334 m_embedded_thread_input_reader_sp.reset();
335 debugger.PopInputReader (reader_sp);
336 }
337
338 if (m_new_sysout)
339 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000340 Locker locker(this,
341 ScriptInterpreterPython::Locker::AcquireLock,
342 ScriptInterpreterPython::Locker::FreeLock);
343 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000344 }
Chris Lattner24943d22010-06-08 16:52:24 +0000345}
346
Caroline Tice0aa2e552011-01-14 00:29:16 +0000347void
348ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
349{
350 if (fh == NULL)
351 return;
352
353 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000354
Johnny Chenc65046d2012-03-08 20:53:04 +0000355 Locker locker(this,
356 ScriptInterpreterPython::Locker::AcquireLock,
357 ScriptInterpreterPython::Locker::FreeAcquiredLock);
358
Enrico Granata91544802011-09-06 19:20:51 +0000359 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000360}
361
362void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000363ScriptInterpreterPython::SaveTerminalState (int fd)
364{
365 // Python mucks with the terminal state of STDIN. If we can possibly avoid
366 // this by setting the file handles up correctly prior to entering the
367 // interpreter we should. For now we save and restore the terminal state
368 // on the input file handle.
369 m_terminal_state.Save (fd, false);
370}
371
372void
373ScriptInterpreterPython::RestoreTerminalState ()
374{
375 // Python mucks with the terminal state of STDIN. If we can possibly avoid
376 // this by setting the file handles up correctly prior to entering the
377 // interpreter we should. For now we save and restore the terminal state
378 // on the input file handle.
379 m_terminal_state.Restore();
380}
381
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000382void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000383ScriptInterpreterPython::LeaveSession ()
384{
Johnny Chen41641f92012-02-29 01:52:13 +0000385 PyObject *sysmod = PyImport_AddModule ("sys");
386 PyObject *sysdict = PyModule_GetDict (sysmod);
387
388 if (m_new_sysout && sysmod && sysdict)
389 {
Johnny Chenc65046d2012-03-08 20:53:04 +0000390 if (m_old_sysout)
391 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_old_sysout);
392 if (m_old_syserr)
393 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_old_syserr);
Johnny Chen41641f92012-02-29 01:52:13 +0000394 }
395
Caroline Tice0aa2e552011-01-14 00:29:16 +0000396 m_session_is_active = false;
397}
398
399void
400ScriptInterpreterPython::EnterSession ()
401{
402 // If we have already entered the session, without having officially 'left' it, then there is no need to
403 // 'enter' it again.
404
405 if (m_session_is_active)
406 return;
407
408 m_session_is_active = true;
409
Caroline Tice202f6b82011-01-17 21:55:19 +0000410 StreamString run_string;
411
Greg Clayton2fecc452012-01-28 02:11:02 +0000412 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %llu", m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
413 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)", GetCommandInterpreter().GetDebugger().GetID());
414 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
415 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
416 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
417 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
418 // Make sure STDIN is closed since when we run this as an embedded
419 // interpreter we don't want someone to call "line = sys.stdin.readline()"
420 // and lock up. We don't have multiple windows and when the interpreter is
421 // embedded we don't know we should be feeding input to the embedded
422 // interpreter or to the python sys.stdin. We also don't want to let python
423 // play with the real stdin from this process, so we need to close it...
Greg Clayton3eeaf6e2012-02-03 01:30:30 +0000424 //run_string.PutCString ("; sys.stdin.close()");
Greg Clayton2fecc452012-01-28 02:11:02 +0000425 run_string.PutCString ("')");
Caroline Tice0aa2e552011-01-14 00:29:16 +0000426
Caroline Tice6af65cb2011-05-03 21:21:50 +0000427 PyRun_SimpleString (run_string.GetData());
428 run_string.Clear();
Johnny Chen41641f92012-02-29 01:52:13 +0000429
Caroline Tice0aa2e552011-01-14 00:29:16 +0000430 PyObject *sysmod = PyImport_AddModule ("sys");
431 PyObject *sysdict = PyModule_GetDict (sysmod);
Johnny Chen41641f92012-02-29 01:52:13 +0000432
Greg Clayton2fecc452012-01-28 02:11:02 +0000433 if (m_new_sysout && sysmod && sysdict)
434 {
Johnny Chen41641f92012-02-29 01:52:13 +0000435 m_old_sysout = PyDict_GetItemString(sysdict, "stdout");
436 m_old_syserr = PyDict_GetItemString(sysdict, "stderr");
Johnny Chenc65046d2012-03-08 20:53:04 +0000437 if (m_new_sysout)
438 {
439 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
440 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
441 }
Greg Clayton2fecc452012-01-28 02:11:02 +0000442 }
Johnny Chen41641f92012-02-29 01:52:13 +0000443
Caroline Tice0aa2e552011-01-14 00:29:16 +0000444 if (PyErr_Occurred())
445 PyErr_Clear ();
Greg Clayton2fecc452012-01-28 02:11:02 +0000446}
Caroline Tice0aa2e552011-01-14 00:29:16 +0000447
Enrico Granata400105d2012-03-06 23:42:15 +0000448static PyObject*
449FindSessionDictionary (const char* dict_name)
450{
451 static std::map<ConstString,PyObject*> g_dict_map;
452
453 ConstString dict(dict_name);
454
455 std::map<ConstString,PyObject*>::iterator iter = g_dict_map.find(dict);
456
457 if (iter != g_dict_map.end())
458 return iter->second;
459
460 PyObject *main_mod = PyImport_AddModule ("__main__");
461 if (main_mod != NULL)
462 {
463 PyObject *main_dict = PyModule_GetDict (main_mod);
464 if ((main_dict != NULL)
465 && PyDict_Check (main_dict))
466 {
467 // Go through the main dictionary looking for the correct python script interpreter dictionary
468 PyObject *key, *value;
469 Py_ssize_t pos = 0;
470
471 while (PyDict_Next (main_dict, &pos, &key, &value))
472 {
473 // We have stolen references to the key and value objects in the dictionary; we need to increment
474 // them now so that Python's garbage collector doesn't collect them out from under us.
475 Py_INCREF (key);
476 Py_INCREF (value);
477 if (strcmp (PyString_AsString (key), dict_name) == 0)
478 {
479 g_dict_map[dict] = value;
480 return value;
481 }
482 }
483 }
484 }
485 return NULL;
486}
487
488static std::string
489GenerateUniqueName (const char* base_name_wanted,
490 uint32_t& functions_counter,
491 void* name_token = NULL)
492{
493 StreamString sstr;
494
495 if (!base_name_wanted)
496 return std::string();
497
498 if (!name_token)
499 sstr.Printf ("%s_%d", base_name_wanted, functions_counter++);
500 else
501 sstr.Printf ("%s_%p", base_name_wanted, name_token);
502
503 return sstr.GetString();
504}
505
Johnny Chen60dde642010-07-30 22:33:14 +0000506bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000507ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000508{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000509 if (!m_valid_session)
510 return false;
511
Caroline Tice4a461da2011-01-14 21:09:29 +0000512 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
513 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
514 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
515 // method to pass the command string directly down to Python.
516
Enrico Granatafa1f6172011-10-24 17:22:21 +0000517 Locker locker(this,
518 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
519 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000520
521 bool success = false;
522
Greg Clayton63094e02010-06-23 01:19:29 +0000523 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000524 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000525 // Find the correct script interpreter dictionary in the main module.
Enrico Granata400105d2012-03-06 23:42:15 +0000526 PyObject *script_interpreter_dict = FindSessionDictionary(m_dictionary_name.c_str());
527 if (script_interpreter_dict != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000528 {
Enrico Granata400105d2012-03-06 23:42:15 +0000529 PyObject *pfunc = (PyObject*)m_run_one_line;
530 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
531 if (pmod != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000532 {
Enrico Granata400105d2012-03-06 23:42:15 +0000533 PyObject *pmod_dict = PyModule_GetDict (pmod);
534 if ((pmod_dict != NULL)
535 && PyDict_Check (pmod_dict))
Caroline Tice4a461da2011-01-14 21:09:29 +0000536 {
Enrico Granata400105d2012-03-06 23:42:15 +0000537 if (!pfunc)
Caroline Tice4a461da2011-01-14 21:09:29 +0000538 {
539 PyObject *key, *value;
540 Py_ssize_t pos = 0;
541
542 while (PyDict_Next (pmod_dict, &pos, &key, &value))
543 {
544 Py_INCREF (key);
545 Py_INCREF (value);
546 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
547 {
548 pfunc = value;
549 break;
550 }
551 }
Enrico Granata400105d2012-03-06 23:42:15 +0000552 m_run_one_line = pfunc;
553 }
554
555 if (pfunc && PyCallable_Check (pfunc))
556 {
557 PyObject *pargs = Py_BuildValue("(Os)",script_interpreter_dict,command);
558 if (pargs != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000559 {
Enrico Granata400105d2012-03-06 23:42:15 +0000560 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
561 Py_DECREF (pargs);
562 if (pvalue != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000563 {
Enrico Granata400105d2012-03-06 23:42:15 +0000564 Py_DECREF (pvalue);
565 success = true;
566 }
567 else if (PyErr_Occurred ())
568 {
569 PyErr_Print();
570 PyErr_Clear();
Caroline Tice4a461da2011-01-14 21:09:29 +0000571 }
572 }
573 }
574 }
Caroline Tice4a461da2011-01-14 21:09:29 +0000575 }
Enrico Granata400105d2012-03-06 23:42:15 +0000576 Py_INCREF (script_interpreter_dict);
Caroline Tice4a461da2011-01-14 21:09:29 +0000577 }
Greg Clayton63094e02010-06-23 01:19:29 +0000578
Caroline Tice4a461da2011-01-14 21:09:29 +0000579 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000580 return true;
581
582 // The one-liner failed. Append the error message.
583 if (result)
584 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
585 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000586 }
Johnny Chen60dde642010-07-30 22:33:14 +0000587
588 if (result)
589 result->AppendError ("empty command passed to python\n");
590 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000591}
592
Chris Lattner24943d22010-06-08 16:52:24 +0000593size_t
594ScriptInterpreterPython::InputReaderCallback
595(
596 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000597 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000598 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000599 const char *bytes,
600 size_t bytes_len
601)
602{
Caroline Tice2ade6112010-11-10 19:18:14 +0000603 lldb::thread_t embedded_interpreter_thread;
604 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
605
Chris Lattner24943d22010-06-08 16:52:24 +0000606 if (baton == NULL)
607 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000608
609 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000610
Caroline Tice0aa2e552011-01-14 00:29:16 +0000611 if (script_interpreter->m_script_lang != eScriptLanguagePython)
612 return 0;
613
Caroline Tice892fadd2011-06-16 16:27:19 +0000614 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
615 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
616
Chris Lattner24943d22010-06-08 16:52:24 +0000617 switch (notification)
618 {
619 case eInputReaderActivate:
620 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000621 if (!batch_mode)
622 {
623 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
624 out_stream->Flush();
625 }
Greg Clayton58928562011-02-09 01:08:52 +0000626
Chris Lattner24943d22010-06-08 16:52:24 +0000627 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000628 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
629 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000630 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000631
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000632 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000633
Caroline Tice202f6b82011-01-17 21:55:19 +0000634 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000635 ScriptInterpreterPython::Locker locker(script_interpreter,
636 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
637 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000638 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000639
Caroline Tice2ade6112010-11-10 19:18:14 +0000640 char error_str[1024];
641 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
642 sizeof(error_str)))
643 {
644 if (log)
645 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
646 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
647 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
648 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
649 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000650 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000651 {
652 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000653 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000654 Error detach_error;
655 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
656 }
657 else
658 {
659 if (log)
660 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
661 reader.SetIsDone (true);
662 }
663 }
664 else
665 {
666 if (log)
667 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
668 reader.SetIsDone (true);
669 }
Chris Lattner24943d22010-06-08 16:52:24 +0000670 }
671 break;
672
673 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000674 // When another input reader is pushed, don't leave the session...
675 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000676 break;
677
678 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000679 {
Greg Claytona1cec242012-01-06 00:47:38 +0000680 // Don't try and acquire the interpreter lock here because code like
681 // this:
682 //
683 // (lldb) script
684 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
685 //
686 // This will cause the process to run. The interpreter lock is taken
687 // by the input reader for the "script" command. If we try and acquire
688 // the lock here, when the process runs it might deactivate this input
689 // reader (if STDIN is hooked up to the inferior process) and
690 // reactivate it when the process stops which will deadlock.
691 //ScriptInterpreterPython::Locker locker(script_interpreter,
692 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
693 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000694 }
Chris Lattner24943d22010-06-08 16:52:24 +0000695 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000696
Caroline Tice4a348082011-05-02 20:41:46 +0000697 case eInputReaderAsynchronousOutputWritten:
698 break;
699
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000700 case eInputReaderInterrupt:
701 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
702 break;
703
704 case eInputReaderEndOfFile:
705 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
706 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000707
708 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000709 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000710 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000711 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000712 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000713 bytes_len);
714 if (bytes && bytes_len)
715 {
716 if ((int) bytes[0] == 4)
717 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
718 else
719 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
720 }
721 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000722 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000723 else
724 {
725 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000726 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000727 bytes,
728 bytes_len);
729 reader.SetIsDone (true);
730 }
731
Chris Lattner24943d22010-06-08 16:52:24 +0000732 break;
733
734 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000735 script_interpreter->LeaveSession ();
736
Chris Lattner24943d22010-06-08 16:52:24 +0000737 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000738 if (log)
739 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000740
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000741 script_interpreter->RestoreTerminalState ();
742
Caroline Tice2ade6112010-11-10 19:18:14 +0000743 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000744 break;
745 }
746
747 return bytes_len;
748}
749
750
751void
Greg Clayton238c0a12010-09-18 01:14:36 +0000752ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000753{
754 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
755
Caroline Tice0aa2e552011-01-14 00:29:16 +0000756 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000757
758 // At the moment, the only time the debugger does not have an input file handle is when this is called
759 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
760 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
761 // do it.
762
Greg Clayton58928562011-02-09 01:08:52 +0000763 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000764 return;
765
Greg Clayton63094e02010-06-23 01:19:29 +0000766 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000767 if (reader_sp)
768 {
769 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
770 this, // baton
771 eInputReaderGranularityLine, // token size, to pass to callback function
772 NULL, // end token
773 NULL, // prompt
774 true)); // echo input
775
776 if (error.Success())
777 {
Greg Clayton63094e02010-06-23 01:19:29 +0000778 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000779 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000780 }
781 }
782}
783
784bool
785ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000786 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000787 void *ret_value)
788{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000789
Enrico Granatafa1f6172011-10-24 17:22:21 +0000790 Locker locker(this,
791 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
792 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000793
Chris Lattner24943d22010-06-08 16:52:24 +0000794 PyObject *py_return = NULL;
795 PyObject *mainmod = PyImport_AddModule ("__main__");
796 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000797 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000798 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000799 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000800 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000801 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000802
Enrico Granata400105d2012-03-06 23:42:15 +0000803 locals = FindSessionDictionary(m_dictionary_name.c_str());
804
Caroline Tice0aa2e552011-01-14 00:29:16 +0000805 if (locals == NULL)
806 {
807 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
808 should_decrement_locals = true;
809 }
810
811 if (locals == NULL)
812 {
813 locals = globals;
814 should_decrement_locals = false;
815 }
816
817 py_error = PyErr_Occurred();
818 if (py_error != NULL)
819 PyErr_Clear();
820
Chris Lattner24943d22010-06-08 16:52:24 +0000821 if (in_string != NULL)
822 {
823 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
824 if (py_return == NULL)
825 {
826 py_error = PyErr_Occurred ();
827 if (py_error != NULL)
828 PyErr_Clear ();
829
830 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
831 }
832
Caroline Tice0aa2e552011-01-14 00:29:16 +0000833 if (locals != NULL
834 && should_decrement_locals)
835 Py_DECREF (locals);
836
Chris Lattner24943d22010-06-08 16:52:24 +0000837 if (py_return != NULL)
838 {
839 switch (return_type)
840 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000841 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000842 {
843 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000844 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000845 break;
846 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000847 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000848 {
849 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000850 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000851 break;
852 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000853 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000854 {
855 const char format[2] = "b";
856 success = PyArg_Parse (py_return, format, (bool *) ret_value);
857 break;
858 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000859 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000860 {
861 const char format[2] = "h";
862 success = PyArg_Parse (py_return, format, (short *) ret_value);
863 break;
864 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000865 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000866 {
867 const char format[2] = "H";
868 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
869 break;
870 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000871 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000872 {
873 const char format[2] = "i";
874 success = PyArg_Parse (py_return, format, (int *) ret_value);
875 break;
876 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000877 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000878 {
879 const char format[2] = "I";
880 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
881 break;
882 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000883 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000884 {
885 const char format[2] = "l";
886 success = PyArg_Parse (py_return, format, (long *) ret_value);
887 break;
888 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000889 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000890 {
891 const char format[2] = "k";
892 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
893 break;
894 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000895 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000896 {
897 const char format[2] = "L";
898 success = PyArg_Parse (py_return, format, (long long *) ret_value);
899 break;
900 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000901 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000902 {
903 const char format[2] = "K";
904 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
905 break;
906 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000907 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000908 {
909 const char format[2] = "f";
910 success = PyArg_Parse (py_return, format, (float *) ret_value);
911 break;
912 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000913 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000914 {
915 const char format[2] = "d";
916 success = PyArg_Parse (py_return, format, (double *) ret_value);
917 break;
918 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000919 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000920 {
921 const char format[2] = "c";
922 success = PyArg_Parse (py_return, format, (char *) ret_value);
923 break;
924 }
925 default:
926 {}
927 }
928 Py_DECREF (py_return);
929 if (success)
930 ret_success = true;
931 else
932 ret_success = false;
933 }
934 }
935
936 py_error = PyErr_Occurred();
937 if (py_error != NULL)
938 {
939 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
940 PyErr_Print ();
941 PyErr_Clear();
942 ret_success = false;
943 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000944
Chris Lattner24943d22010-06-08 16:52:24 +0000945 return ret_success;
946}
947
948bool
949ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
950{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000951
952
953 Locker locker(this,
954 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
955 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000956
Chris Lattner24943d22010-06-08 16:52:24 +0000957 bool success = false;
958 PyObject *py_return = NULL;
959 PyObject *mainmod = PyImport_AddModule ("__main__");
960 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000961 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000962 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000963 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000964
Enrico Granata400105d2012-03-06 23:42:15 +0000965 locals = FindSessionDictionary(m_dictionary_name.c_str());
966
Caroline Tice0aa2e552011-01-14 00:29:16 +0000967 if (locals == NULL)
968 {
969 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
970 should_decrement_locals = true;
971 }
972
973 if (locals == NULL)
974 {
975 locals = globals;
976 should_decrement_locals = false;
977 }
978
979 py_error = PyErr_Occurred();
980 if (py_error != NULL)
981 PyErr_Clear();
982
Chris Lattner24943d22010-06-08 16:52:24 +0000983 if (in_string != NULL)
984 {
985 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
986 if (compiled_node)
987 {
988 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
989 if (compiled_code)
990 {
991 py_return = PyEval_EvalCode (compiled_code, globals, locals);
992 if (py_return != NULL)
993 {
994 success = true;
995 Py_DECREF (py_return);
996 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000997 if (locals && should_decrement_locals)
998 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000999 }
1000 }
1001 }
1002
1003 py_error = PyErr_Occurred ();
1004 if (py_error != NULL)
1005 {
1006 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1007 PyErr_Print ();
1008 PyErr_Clear();
1009 success = false;
1010 }
1011
1012 return success;
1013}
1014
1015static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1016
1017size_t
1018ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1019(
1020 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001021 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001022 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001023 const char *bytes,
1024 size_t bytes_len
1025)
1026{
Caroline Tice892fadd2011-06-16 16:27:19 +00001027 static StringList commands_in_progress;
1028
1029 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1030 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1031
Chris Lattner24943d22010-06-08 16:52:24 +00001032 switch (notification)
1033 {
1034 case eInputReaderActivate:
1035 {
1036 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +00001037 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +00001038 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001039 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001040 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +00001041 out_stream->Printf ("%s", reader.GetPrompt());
1042 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001043 }
1044 }
1045 break;
1046
1047 case eInputReaderDeactivate:
1048 break;
1049
1050 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001051 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001052 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001053 out_stream->Printf ("%s", reader.GetPrompt());
1054 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001055 }
Chris Lattner24943d22010-06-08 16:52:24 +00001056 break;
1057
Caroline Tice4a348082011-05-02 20:41:46 +00001058 case eInputReaderAsynchronousOutputWritten:
1059 break;
1060
Chris Lattner24943d22010-06-08 16:52:24 +00001061 case eInputReaderGotToken:
1062 {
1063 std::string temp_string (bytes, bytes_len);
1064 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001065 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001066 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001067 out_stream->Printf ("%s", reader.GetPrompt());
1068 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001069 }
Chris Lattner24943d22010-06-08 16:52:24 +00001070 }
1071 break;
1072
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001073 case eInputReaderEndOfFile:
1074 case eInputReaderInterrupt:
1075 // Control-c (SIGINT) & control-d both mean finish & exit.
1076 reader.SetIsDone(true);
1077
1078 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1079 if (notification == eInputReaderInterrupt)
1080 commands_in_progress.Clear();
1081
1082 // Fall through here...
1083
Chris Lattner24943d22010-06-08 16:52:24 +00001084 case eInputReaderDone:
1085 {
1086 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1087 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1088 data_ap->user_source.AppendList (commands_in_progress);
1089 if (data_ap.get())
1090 {
Greg Clayton63094e02010-06-23 01:19:29 +00001091 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001092 if (interpreter)
1093 {
1094 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1095 data_ap->script_source))
1096 {
Enrico Granata400105d2012-03-06 23:42:15 +00001097 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1098 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001099 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001100 else if (!batch_mode)
1101 {
1102 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1103 out_stream->Flush();
1104 }
Chris Lattner24943d22010-06-08 16:52:24 +00001105 }
1106 else
1107 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001108 if (!batch_mode)
1109 {
1110 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1111 out_stream->Flush();
1112 }
Chris Lattner24943d22010-06-08 16:52:24 +00001113 }
1114 }
1115 }
1116 break;
1117
1118 }
1119
1120 return bytes_len;
1121}
1122
1123void
Greg Clayton238c0a12010-09-18 01:14:36 +00001124ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001125 CommandReturnObject &result)
1126{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001127 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1128
Greg Clayton63094e02010-06-23 01:19:29 +00001129 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001130
1131 if (reader_sp)
1132 {
1133 Error err = reader_sp->Initialize (
1134 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1135 bp_options, // baton
1136 eInputReaderGranularityLine, // token size, for feeding data to callback function
1137 "DONE", // end token
1138 "> ", // prompt
1139 true); // echo input
1140
1141 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001142 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001143 else
1144 {
1145 result.AppendError (err.AsCString());
1146 result.SetStatus (eReturnStatusFailed);
1147 }
1148 }
1149 else
1150 {
1151 result.AppendError("out of memory");
1152 result.SetStatus (eReturnStatusFailed);
1153 }
1154}
1155
Johnny Chen3e0571b2010-09-11 00:23:59 +00001156// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001157void
Greg Clayton238c0a12010-09-18 01:14:36 +00001158ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001159 const char *oneliner)
1160{
1161 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1162
1163 // It's necessary to set both user_source and script_source to the oneliner.
1164 // The former is used to generate callback description (as in breakpoint command list)
1165 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001166
Johnny Chend1c2dca2010-09-10 18:21:10 +00001167 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001168
Caroline Tice5136f942010-09-27 21:35:15 +00001169 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1170 {
Enrico Granata400105d2012-03-06 23:42:15 +00001171 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1172 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Caroline Tice5136f942010-09-27 21:35:15 +00001173 }
1174
Johnny Chend1c2dca2010-09-10 18:21:10 +00001175 return;
1176}
1177
Chris Lattner24943d22010-06-08 16:52:24 +00001178bool
1179ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1180{
1181 // Convert StringList to one long, newline delimited, const char *.
Enrico Granata400105d2012-03-06 23:42:15 +00001182 std::string function_def_string(function_def.CopyList());
Chris Lattner24943d22010-06-08 16:52:24 +00001183
1184 return ExecuteMultipleLines (function_def_string.c_str());
1185}
1186
Enrico Granataf7a9b142011-07-15 02:26:42 +00001187bool
Enrico Granata400105d2012-03-06 23:42:15 +00001188ScriptInterpreterPython::GenerateFunction(const char *signature, const StringList &input)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001189{
1190 int num_lines = input.GetSize ();
1191 if (num_lines == 0)
1192 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001193
1194 if (!signature || *signature == 0)
1195 return false;
1196
Enrico Granataf7a9b142011-07-15 02:26:42 +00001197 StreamString sstr;
1198 StringList auto_generated_function;
Enrico Granata400105d2012-03-06 23:42:15 +00001199 auto_generated_function.AppendString (signature);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001200 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1201 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1202 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1203 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1204 // global dictionary.
1205
1206 // Wrap everything up inside the function, increasing the indentation.
1207
1208 for (int i = 0; i < num_lines; ++i)
1209 {
1210 sstr.Clear ();
1211 sstr.Printf (" %s", input.GetStringAtIndex (i));
1212 auto_generated_function.AppendString (sstr.GetData());
1213 }
1214 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1215 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1216 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1217 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1218
1219 // Verify that the results are valid Python.
1220
1221 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1222 return false;
1223
1224 return true;
1225
1226}
1227
Enrico Granataf7a9b142011-07-15 02:26:42 +00001228bool
Enrico Granata400105d2012-03-06 23:42:15 +00001229ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001230{
Enrico Granata400105d2012-03-06 23:42:15 +00001231 static uint32_t num_created_functions = 0;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001232 user_input.RemoveBlankLines ();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001233 StreamString sstr;
1234
1235 // Check to see if we have any data; if not, just return.
1236 if (user_input.GetSize() == 0)
1237 return false;
1238
1239 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1240 // ValueObject as parameter to the function.
1241
Enrico Granata400105d2012-03-06 23:42:15 +00001242 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 +00001243 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
Enrico Granataf7a9b142011-07-15 02:26:42 +00001244
Enrico Granata400105d2012-03-06 23:42:15 +00001245 if (!GenerateFunction(sstr.GetData(), user_input))
Enrico Granataf7a9b142011-07-15 02:26:42 +00001246 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001247
Enrico Granataf7a9b142011-07-15 02:26:42 +00001248 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001249 output.assign(auto_generated_function_name);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001250 return true;
1251}
1252
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001253bool
Enrico Granata400105d2012-03-06 23:42:15 +00001254ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, std::string &output)
Enrico Granatac2a28252011-08-16 16:49:25 +00001255{
Enrico Granata400105d2012-03-06 23:42:15 +00001256 static uint32_t num_created_functions = 0;
Enrico Granatac2a28252011-08-16 16:49:25 +00001257 user_input.RemoveBlankLines ();
Enrico Granatac2a28252011-08-16 16:49:25 +00001258 StreamString sstr;
1259
1260 // Check to see if we have any data; if not, just return.
1261 if (user_input.GetSize() == 0)
1262 return false;
1263
Enrico Granata400105d2012-03-06 23:42:15 +00001264 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_cmd_alias_func", num_created_functions));
1265
Enrico Granata271568f2011-09-09 01:41:30 +00001266 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001267
Enrico Granata400105d2012-03-06 23:42:15 +00001268 if (!GenerateFunction(sstr.GetData(),user_input))
Enrico Granatac2a28252011-08-16 16:49:25 +00001269 return false;
1270
1271 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001272 output.assign(auto_generated_function_name);
Enrico Granatac2a28252011-08-16 16:49:25 +00001273 return true;
1274}
1275
1276
1277bool
Enrico Granata400105d2012-03-06 23:42:15 +00001278ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, std::string &output, void* name_token)
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001279{
Enrico Granata400105d2012-03-06 23:42:15 +00001280 static uint32_t num_created_classes = 0;
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001281 user_input.RemoveBlankLines ();
1282 int num_lines = user_input.GetSize ();
1283 StreamString sstr;
1284
1285 // Check to see if we have any data; if not, just return.
1286 if (user_input.GetSize() == 0)
1287 return false;
1288
1289 // Wrap all user input into a Python class
1290
Enrico Granata400105d2012-03-06 23:42:15 +00001291 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 +00001292
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001293 StringList auto_generated_class;
1294
1295 // Create the function name & definition string.
1296
1297 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1298 auto_generated_class.AppendString (sstr.GetData());
1299
1300 // Wrap everything up inside the class, increasing the indentation.
1301
1302 for (int i = 0; i < num_lines; ++i)
1303 {
1304 sstr.Clear ();
1305 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1306 auto_generated_class.AppendString (sstr.GetData());
1307 }
1308
1309
1310 // Verify that the results are valid Python.
1311 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1312 // (TODO: rename that method to ExportDefinitionToInterpreter)
1313 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1314 return false;
1315
1316 // Store the name of the auto-generated class
1317
Enrico Granata400105d2012-03-06 23:42:15 +00001318 output.assign(auto_generated_class_name);
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001319 return true;
1320}
1321
Enrico Granata400105d2012-03-06 23:42:15 +00001322lldb::ScriptInterpreterObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001323ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1324 lldb::ValueObjectSP valobj)
1325{
1326 if (class_name.empty())
Enrico Granata400105d2012-03-06 23:42:15 +00001327 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001328
1329 if (!valobj.get())
Enrico Granata400105d2012-03-06 23:42:15 +00001330 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001331
Greg Claytonb4d7fc02012-02-17 07:49:44 +00001332 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1333 Target *target = exe_ctx.GetTargetPtr();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001334
1335 if (!target)
Enrico Granata400105d2012-03-06 23:42:15 +00001336 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001337
1338 Debugger &debugger = target->GetDebugger();
1339 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1340 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1341
1342 if (!script_interpreter)
Enrico Granata400105d2012-03-06 23:42:15 +00001343 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001344
1345 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001346
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001347 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001348 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001349 ForceDisableSyntheticChildren no_synthetics(target);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001350 ret_val = g_swig_synthetic_script (class_name,
1351 python_interpreter->m_dictionary_name.c_str(),
1352 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001353 }
1354
Enrico Granata400105d2012-03-06 23:42:15 +00001355 return MakeScriptObject(ret_val);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001356}
1357
Enrico Granataf7a9b142011-07-15 02:26:42 +00001358bool
Enrico Granata400105d2012-03-06 23:42:15 +00001359ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001360{
Enrico Granata16376ed2012-02-15 02:34:21 +00001361 StringList input;
1362 input.SplitIntoLines(oneliner, strlen(oneliner));
1363 return GenerateTypeScriptFunction(input, output, name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001364}
1365
Chris Lattner24943d22010-06-08 16:52:24 +00001366bool
Enrico Granata400105d2012-03-06 23:42:15 +00001367ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, std::string& output, void* name_token)
Enrico Granata16376ed2012-02-15 02:34:21 +00001368{
1369 StringList input;
1370 input.SplitIntoLines(oneliner, strlen(oneliner));
1371 return GenerateTypeSynthClass(input, output, name_token);
1372}
1373
1374
1375bool
Enrico Granata400105d2012-03-06 23:42:15 +00001376ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, std::string& output)
Chris Lattner24943d22010-06-08 16:52:24 +00001377{
Enrico Granata400105d2012-03-06 23:42:15 +00001378 static uint32_t num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001379 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001380 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001381
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001382 if (user_input.GetSize() == 0)
1383 return false;
1384
Enrico Granata400105d2012-03-06 23:42:15 +00001385 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_bp_callback_func_",num_created_functions));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001386 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001387
Enrico Granata400105d2012-03-06 23:42:15 +00001388 if (!GenerateFunction(sstr.GetData(), user_input))
Caroline Ticeb447e842010-09-21 19:25:28 +00001389 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001390
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001391 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001392 output.assign(auto_generated_function_name);
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001393 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001394}
1395
Enrico Granata1328b142012-02-29 03:28:49 +00001396bool
1397ScriptInterpreterPython::GetScriptedSummary (const char *python_function_name,
1398 lldb::ValueObjectSP valobj,
1399 lldb::ScriptInterpreterObjectSP& callee_wrapper_sp,
1400 std::string& retval)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001401{
1402
Enrico Granata1328b142012-02-29 03:28:49 +00001403 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001404
1405 if (!valobj.get())
Enrico Granata1328b142012-02-29 03:28:49 +00001406 {
1407 retval.assign("<no object>");
1408 return false;
1409 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001410
Enrico Granata1328b142012-02-29 03:28:49 +00001411 void* old_callee = (callee_wrapper_sp ? callee_wrapper_sp->GetObject() : NULL);
1412 void* new_callee = old_callee;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001413
Enrico Granata1328b142012-02-29 03:28:49 +00001414 bool ret_val;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001415 if (python_function_name
1416 && *python_function_name)
1417 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001418 {
Enrico Granata1328b142012-02-29 03:28:49 +00001419 Locker py_lock(this);
1420 {
1421 Timer scoped_timer ("g_swig_typescript_callback","g_swig_typescript_callback");
1422 ret_val = g_swig_typescript_callback (python_function_name,
1423 FindSessionDictionary(m_dictionary_name.c_str()),
1424 valobj,
1425 &new_callee,
1426 retval);
1427 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001428 }
1429 }
1430 else
Enrico Granata1328b142012-02-29 03:28:49 +00001431 {
1432 retval.assign("<no function name>");
1433 return false;
1434 }
1435
1436 if (new_callee && old_callee != new_callee)
1437 callee_wrapper_sp = MakeScriptObject(new_callee);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001438
1439 return ret_val;
1440
1441}
1442
Greg Clayton5144f382010-10-07 17:14:24 +00001443bool
1444ScriptInterpreterPython::BreakpointCallbackFunction
1445(
1446 void *baton,
1447 StoppointCallbackContext *context,
1448 user_id_t break_id,
1449 user_id_t break_loc_id
1450)
1451{
1452 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
Enrico Granata400105d2012-03-06 23:42:15 +00001453 const char *python_function_name = bp_option_data->script_source.c_str();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001454
1455 if (!context)
1456 return true;
1457
Greg Claytonf4124de2012-02-21 00:09:25 +00001458 ExecutionContext exe_ctx (context->exe_ctx_ref);
1459 Target *target = exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001460
1461 if (!target)
1462 return true;
1463
1464 Debugger &debugger = target->GetDebugger();
1465 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1466 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1467
1468 if (!script_interpreter)
1469 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001470
1471 if (python_function_name != NULL
1472 && python_function_name[0] != '\0')
1473 {
Greg Claytonf4124de2012-02-21 00:09:25 +00001474 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001475 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001476 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001477 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001478 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1479
1480 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001481 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001482 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001483 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001484 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001485 ret_val = g_swig_breakpoint_callback (python_function_name,
1486 python_interpreter->m_dictionary_name.c_str(),
1487 stop_frame_sp,
1488 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001489 }
1490 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001491 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001492 }
Greg Clayton5144f382010-10-07 17:14:24 +00001493 }
1494 // We currently always true so we stop in case anything goes wrong when
1495 // trying to call the script function
1496 return true;
1497}
Caroline Tice2ade6112010-11-10 19:18:14 +00001498
1499lldb::thread_result_t
1500ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1501{
1502 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1503
1504 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1505
1506 if (log)
1507 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1508
1509 char error_str[1024];
1510 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001511
Enrico Granatafa1f6172011-10-24 17:22:21 +00001512 Locker locker(script_interpreter,
1513 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1514 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1515
1516 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001517 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001518 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001519
Caroline Tice0aa2e552011-01-14 00:29:16 +00001520 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1521 PyRun_SimpleString (run_string.GetData());
1522 run_string.Clear ();
1523
1524 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1525 PyRun_SimpleString (run_string.GetData());
1526 run_string.Clear ();
1527
1528 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1529 PyRun_SimpleString (run_string.GetData());
1530 run_string.Clear ();
1531
1532 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1533 pty_slave_name);
1534 PyRun_SimpleString (run_string.GetData());
1535 run_string.Clear ();
1536
Johnny Chen8054ba32011-03-11 00:28:50 +00001537 // The following call drops into the embedded interpreter loop and stays there until the
1538 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001539
Caroline Ticece207c12011-03-11 00:21:55 +00001540 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001541 // 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 +00001542 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1543
1544 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1545 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1546 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1547 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1548 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1549 // hang (it's happened before).
1550
Caroline Tice9d352ce2011-03-07 23:24:28 +00001551 Py_BEGIN_ALLOW_THREADS
1552 PyGILState_STATE gstate = PyGILState_Ensure();
1553
Caroline Tice0aa2e552011-01-14 00:29:16 +00001554 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1555 PyRun_SimpleString (run_string.GetData());
1556 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001557
Caroline Tice9d352ce2011-03-07 23:24:28 +00001558 PyGILState_Release (gstate);
1559 Py_END_ALLOW_THREADS
1560
Caroline Tice0aa2e552011-01-14 00:29:16 +00001561 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1562 PyRun_SimpleString (run_string.GetData());
1563 run_string.Clear();
1564
1565 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1566 PyRun_SimpleString (run_string.GetData());
1567 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001568
Caroline Tice2ade6112010-11-10 19:18:14 +00001569 }
1570
1571 if (script_interpreter->m_embedded_thread_input_reader_sp)
1572 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1573
1574 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001575
Caroline Tice2ade6112010-11-10 19:18:14 +00001576 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1577 if (log)
1578 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1579
1580
Johnny Chen8054ba32011-03-11 00:28:50 +00001581 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001582 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001583 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1584 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1585 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001586
Caroline Tice2ade6112010-11-10 19:18:14 +00001587 return NULL;
1588}
1589
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001590uint32_t
Enrico Granata400105d2012-03-06 23:42:15 +00001591ScriptInterpreterPython::CalculateNumChildren (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001592{
Enrico Granata400105d2012-03-06 23:42:15 +00001593 if (!implementor_sp)
1594 return 0;
1595
1596 void* implementor = implementor_sp->GetObject();
1597
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001598 if (!implementor)
1599 return 0;
1600
1601 if (!g_swig_calc_children)
1602 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001603
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001604 uint32_t ret_val = 0;
1605
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001606 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001607 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001608 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001609 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001610 }
1611
1612 return ret_val;
1613}
1614
Enrico Granata91544802011-09-06 19:20:51 +00001615lldb::ValueObjectSP
Enrico Granata400105d2012-03-06 23:42:15 +00001616ScriptInterpreterPython::GetChildAtIndex (const lldb::ScriptInterpreterObjectSP& implementor_sp, uint32_t idx)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001617{
Enrico Granata400105d2012-03-06 23:42:15 +00001618 if (!implementor_sp)
1619 return lldb::ValueObjectSP();
1620
1621 void* implementor = implementor_sp->GetObject();
1622
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001623 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001624 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001625
Enrico Granata91544802011-09-06 19:20:51 +00001626 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1627 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001628
Enrico Granata91544802011-09-06 19:20:51 +00001629 void* child_ptr = NULL;
1630 lldb::SBValue* value_sb = NULL;
1631 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001632
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001633 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001634 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001635 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata91544802011-09-06 19:20:51 +00001636 child_ptr = g_swig_get_child_index (implementor,idx);
1637 if (child_ptr != NULL && child_ptr != Py_None)
1638 {
1639 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1640 if (value_sb == NULL)
1641 Py_XDECREF(child_ptr);
1642 else
1643 ret_val = value_sb->get_sp();
1644 }
1645 else
1646 {
1647 Py_XDECREF(child_ptr);
1648 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001649 }
1650
1651 return ret_val;
1652}
1653
1654int
Enrico Granata400105d2012-03-06 23:42:15 +00001655ScriptInterpreterPython::GetIndexOfChildWithName (const lldb::ScriptInterpreterObjectSP& implementor_sp, const char* child_name)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001656{
Enrico Granata400105d2012-03-06 23:42:15 +00001657 if (!implementor_sp)
1658 return UINT32_MAX;
1659
1660 void* implementor = implementor_sp->GetObject();
1661
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001662 if (!implementor)
1663 return UINT32_MAX;
1664
1665 if (!g_swig_get_index_child)
1666 return UINT32_MAX;
1667
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001668 int ret_val = UINT32_MAX;
1669
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001670 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001671 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001672 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001673 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001674 }
1675
1676 return ret_val;
1677}
1678
Enrico Granatacf09f882012-03-19 22:58:49 +00001679bool
Enrico Granata400105d2012-03-06 23:42:15 +00001680ScriptInterpreterPython::UpdateSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata979e20d2011-07-29 19:53:35 +00001681{
Enrico Granatacf09f882012-03-19 22:58:49 +00001682 bool ret_val = false;
1683
Enrico Granata400105d2012-03-06 23:42:15 +00001684 if (!implementor_sp)
Enrico Granatacf09f882012-03-19 22:58:49 +00001685 return ret_val;
Enrico Granata400105d2012-03-06 23:42:15 +00001686
1687 void* implementor = implementor_sp->GetObject();
1688
Enrico Granata979e20d2011-07-29 19:53:35 +00001689 if (!implementor)
Enrico Granatacf09f882012-03-19 22:58:49 +00001690 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001691
1692 if (!g_swig_update_provider)
Enrico Granatacf09f882012-03-19 22:58:49 +00001693 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001694
Enrico Granata979e20d2011-07-29 19:53:35 +00001695 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001696 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001697 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granatacf09f882012-03-19 22:58:49 +00001698 ret_val = g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001699 }
1700
Enrico Granatacf09f882012-03-19 22:58:49 +00001701 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001702}
1703
Enrico Granatac2a28252011-08-16 16:49:25 +00001704bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001705ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00001706 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00001707 lldb_private::Error& error)
1708{
1709 if (!pathname || !pathname[0])
1710 {
1711 error.SetErrorString("invalid pathname");
1712 return false;
1713 }
1714
1715 if (!g_swig_call_module_init)
1716 {
1717 error.SetErrorString("internal helper function missing");
1718 return false;
1719 }
1720
Greg Clayton13d24fb2012-01-29 20:56:30 +00001721 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granatafa1f6172011-10-24 17:22:21 +00001722
Enrico Granata59df36f2011-10-17 21:45:27 +00001723 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001724 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00001725
1726 FileSpec target_file(pathname, true);
1727
1728 // TODO: would we want to reject any other value?
1729 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1730 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1731 {
1732 error.SetErrorString("invalid pathname");
1733 return false;
1734 }
1735
1736 const char* directory = target_file.GetDirectory().GetCString();
1737 std::string basename(target_file.GetFilename().GetCString());
1738
1739 // now make sure that Python has "directory" in the search path
1740 StreamString command_stream;
1741 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1742 directory,
1743 directory);
Enrico Granatafa1f6172011-10-24 17:22:21 +00001744 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData());
Enrico Granata59df36f2011-10-17 21:45:27 +00001745 if (!syspath_retval)
1746 {
1747 error.SetErrorString("Python sys.path handling failed");
1748 return false;
1749 }
1750
1751 // strip .py or .pyc extension
1752 ConstString extension = target_file.GetFileNameExtension();
1753 if (::strcmp(extension.GetCString(), "py") == 0)
1754 basename.resize(basename.length()-3);
1755 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1756 basename.resize(basename.length()-4);
1757
1758 // check if the module is already import-ed
1759 command_stream.Clear();
1760 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1761 int refcount = 0;
1762 // this call will fail if the module does not exist (because the parameter to it is not a string
1763 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00001764 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
1765 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0);
1766 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00001767 {
1768 error.SetErrorString("module already imported");
1769 return false;
1770 }
1771
1772 // now actually do the import
1773 command_stream.Clear();
1774 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafa1f6172011-10-24 17:22:21 +00001775 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL);
Enrico Granata59df36f2011-10-17 21:45:27 +00001776 if (!import_retval)
1777 {
1778 error.SetErrorString("Python import statement failed");
1779 return false;
1780 }
1781
Enrico Granata16376ed2012-02-15 02:34:21 +00001782 // call __lldb_init_module(debugger,dict)
Enrico Granata59df36f2011-10-17 21:45:27 +00001783 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001784 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001785 debugger_sp))
1786 {
Enrico Granata16376ed2012-02-15 02:34:21 +00001787 error.SetErrorString("calling __lldb_init_module failed");
Enrico Granata59df36f2011-10-17 21:45:27 +00001788 return false;
1789 }
1790 return true;
1791 }
1792}
1793
Enrico Granata1328b142012-02-29 03:28:49 +00001794lldb::ScriptInterpreterObjectSP
1795ScriptInterpreterPython::MakeScriptObject (void* object)
1796{
1797 return lldb::ScriptInterpreterObjectSP(new ScriptInterpreterPythonObject(object));
1798}
1799
Enrico Granata6010ace2011-11-07 22:57:04 +00001800ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
1801 ScriptedCommandSynchronicity synchro) :
1802 m_debugger_sp(debugger_sp),
1803 m_synch_wanted(synchro),
1804 m_old_asynch(debugger_sp->GetAsyncExecution())
1805{
1806 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
1807 m_debugger_sp->SetAsyncExecution(false);
1808 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
1809 m_debugger_sp->SetAsyncExecution(true);
1810}
1811
1812ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
1813{
1814 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
1815 m_debugger_sp->SetAsyncExecution(m_old_asynch);
1816}
1817
Enrico Granata59df36f2011-10-17 21:45:27 +00001818bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001819ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1820 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00001821 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001822 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001823 Error& error)
1824{
1825 if (!impl_function)
1826 {
1827 error.SetErrorString("no function to execute");
1828 return false;
1829 }
1830
1831 if (!g_swig_call_command)
1832 {
1833 error.SetErrorString("no helper function to run scripted commands");
1834 return false;
1835 }
1836
Greg Clayton13d24fb2012-01-29 20:56:30 +00001837 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata6010ace2011-11-07 22:57:04 +00001838
1839 if (!debugger_sp.get())
1840 {
1841 error.SetErrorString("invalid Debugger pointer");
1842 return false;
1843 }
Enrico Granatac2a28252011-08-16 16:49:25 +00001844
1845 bool ret_val;
1846
1847 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00001848
Enrico Granatac2a28252011-08-16 16:49:25 +00001849 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001850 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00001851 SynchronicityHandler synch_handler(debugger_sp,
1852 synchronicity);
1853
Enrico Granatac2a28252011-08-16 16:49:25 +00001854 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001855 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00001856 debugger_sp,
1857 args,
1858 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001859 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001860 }
Enrico Granata6010ace2011-11-07 22:57:04 +00001861
Enrico Granatac2a28252011-08-16 16:49:25 +00001862 if (!ret_val)
1863 error.SetErrorString(err_msg.c_str());
1864 else
1865 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00001866
Enrico Granatac2a28252011-08-16 16:49:25 +00001867 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00001868}
1869
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001870// in Python, a special attribute __doc__ contains the docstring
1871// for an object (function, method, class, ...) if any is defined
1872// Otherwise, the attribute's value is None
1873std::string
1874ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1875{
1876 std::string command(item);
1877 command += ".__doc__";
1878
1879 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1880
1881 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001882 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001883 &result_ptr) && result_ptr)
1884 {
1885 return std::string(result_ptr);
1886 }
1887 else
1888 return std::string("");
1889}
Caroline Tice2ade6112010-11-10 19:18:14 +00001890
Caroline Tice0aa2e552011-01-14 00:29:16 +00001891void
Enrico Granata1328b142012-02-29 03:28:49 +00001892ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback)
Greg Claytone86cbb92011-03-22 01:14:58 +00001893{
1894 g_swig_init_callback = python_swig_init_callback;
Enrico Granata1328b142012-02-29 03:28:49 +00001895 g_swig_breakpoint_callback = LLDBSwigPythonBreakpointCallbackFunction;
1896 g_swig_typescript_callback = LLDBSwigPythonCallTypeScript;
1897 g_swig_synthetic_script = LLDBSwigPythonCreateSyntheticProvider;
1898 g_swig_calc_children = LLDBSwigPython_CalculateNumChildren;
1899 g_swig_get_child_index = LLDBSwigPython_GetChildAtIndex;
1900 g_swig_get_index_child = LLDBSwigPython_GetIndexOfChildWithName;
1901 g_swig_cast_to_sbvalue = LLDBSWIGPython_CastPyObjectToSBValue;
1902 g_swig_update_provider = LLDBSwigPython_UpdateSynthProviderInstance;
1903 g_swig_call_command = LLDBSwigPythonCallCommand;
1904 g_swig_call_module_init = LLDBSwigPythonCallModuleInit;
Greg Claytone86cbb92011-03-22 01:14:58 +00001905}
1906
1907void
1908ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001909{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001910 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1911
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001912 // Python will muck with STDIN terminal state, so save off any current TTY
1913 // settings so we can restore them.
1914 TerminalState stdin_tty_state;
1915 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001916
Caroline Tice9d352ce2011-03-07 23:24:28 +00001917 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001918 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001919
Greg Claytone86cbb92011-03-22 01:14:58 +00001920 // Initialize SWIG after setting up python
1921 assert (g_swig_init_callback != NULL);
1922 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001923
1924 // Update the path python uses to search for modules to include the current directory.
1925
Caroline Ticed4d92832011-06-13 21:33:00 +00001926 PyRun_SimpleString ("import sys");
1927 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001928
1929 // Find the module that owns this code and use that path we get to
1930 // set the sys.path appropriately.
1931
1932 FileSpec file_spec;
1933 char python_dir_path[PATH_MAX];
1934 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1935 {
1936 std::string python_path("sys.path.insert(0,\"");
1937 size_t orig_len = python_path.length();
1938 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1939 {
1940 python_path.append (python_dir_path);
1941 python_path.append ("\")");
1942 PyRun_SimpleString (python_path.c_str());
1943 python_path.resize (orig_len);
1944 }
1945
1946 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1947 {
1948 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1949 {
1950 python_path.append (python_dir_path);
1951 python_path.append ("\")");
1952 PyRun_SimpleString (python_path.c_str());
1953 python_path.resize (orig_len);
1954 }
1955 }
1956 }
1957
Jim Ingham4dfa5112011-08-22 19:10:09 +00001958 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001959
Caroline Ticed4d92832011-06-13 21:33:00 +00001960 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001961
Caroline Ticed4d92832011-06-13 21:33:00 +00001962 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1963 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00001964 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001965
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001966 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001967}
1968
Greg Claytone86cbb92011-03-22 01:14:58 +00001969//void
1970//ScriptInterpreterPython::Terminate ()
1971//{
1972// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1973// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1974// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1975// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1976// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1977// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1978// // within Py_Finalize, which results in a seg fault.
1979// //
1980// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1981// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1982// // process exits).
1983// //
1984//// Py_Finalize ();
1985//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00001986
1987#endif // #ifdef LLDB_DISABLE_PYTHON