blob: 39c111704fefa1ac88587d80a692da8d1bb07956 [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
Enrico Granata7e202262012-03-29 19:29:45 +0000299 run_string.Printf ("run_one_line (%s, 'import copy, os, re, sys, uuid, lldb, gnu_libstdcpp, libcxx, objc, Logger')", m_dictionary_name.c_str());
Caroline Tice0aa2e552011-01-14 00:29:16 +0000300 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000301
Enrico Granata8f84cfb2012-02-23 23:10:03 +0000302 // WARNING: temporary code that loads Cocoa formatters - this should be done on a per-platform basis rather than loading the whole set
303 // and letting the individual formatter classes exploit APIs to check whether they can/cannot do their task
304 run_string.Clear();
Enrico Granata67812172012-03-27 21:49:20 +0000305 run_string.Printf ("run_one_line (%s, 'import CFString, CFArray, CFDictionary, NSData, NSMachPort, NSSet, NSNotification, NSException, CFBag, CFBinaryHeap, NSURL, NSBundle, NSNumber, NSDate, NSIndexSet, Selector, Class, CFBitVector')", m_dictionary_name.c_str());
Enrico Granata8f84cfb2012-02-23 23:10:03 +0000306 PyRun_SimpleString (run_string.GetData());
Greg Claytonb302dff2012-02-01 08:09:32 +0000307
Caroline Tice0aa2e552011-01-14 00:29:16 +0000308 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000309
Caroline Tice0aa2e552011-01-14 00:29:16 +0000310 if (new_count > old_count)
311 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000312
Caroline Tice0aa2e552011-01-14 00:29:16 +0000313 run_string.Clear();
Greg Clayton444e35b2011-10-19 18:09:39 +0000314 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000315 interpreter.GetDebugger().GetID());
316 PyRun_SimpleString (run_string.GetData());
317
318 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000319 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000320 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000321 }
Chris Lattner24943d22010-06-08 16:52:24 +0000322}
323
324ScriptInterpreterPython::~ScriptInterpreterPython ()
325{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000326 Debugger &debugger = GetCommandInterpreter().GetDebugger();
327
328 if (m_embedded_thread_input_reader_sp.get() != NULL)
329 {
330 m_embedded_thread_input_reader_sp->SetIsDone (true);
331 m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000332 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
333 m_embedded_thread_input_reader_sp.reset();
334 debugger.PopInputReader (reader_sp);
335 }
336
337 if (m_new_sysout)
338 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000339 Locker locker(this,
340 ScriptInterpreterPython::Locker::AcquireLock,
341 ScriptInterpreterPython::Locker::FreeLock);
342 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000343 }
Chris Lattner24943d22010-06-08 16:52:24 +0000344}
345
Caroline Tice0aa2e552011-01-14 00:29:16 +0000346void
347ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
348{
349 if (fh == NULL)
350 return;
351
352 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000353
Johnny Chenc65046d2012-03-08 20:53:04 +0000354 Locker locker(this,
355 ScriptInterpreterPython::Locker::AcquireLock,
356 ScriptInterpreterPython::Locker::FreeAcquiredLock);
357
Enrico Granata91544802011-09-06 19:20:51 +0000358 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000359}
360
361void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000362ScriptInterpreterPython::SaveTerminalState (int fd)
363{
364 // Python mucks with the terminal state of STDIN. If we can possibly avoid
365 // this by setting the file handles up correctly prior to entering the
366 // interpreter we should. For now we save and restore the terminal state
367 // on the input file handle.
368 m_terminal_state.Save (fd, false);
369}
370
371void
372ScriptInterpreterPython::RestoreTerminalState ()
373{
374 // Python mucks with the terminal state of STDIN. If we can possibly avoid
375 // this by setting the file handles up correctly prior to entering the
376 // interpreter we should. For now we save and restore the terminal state
377 // on the input file handle.
378 m_terminal_state.Restore();
379}
380
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000381void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000382ScriptInterpreterPython::LeaveSession ()
383{
Enrico Granata7aa754c2012-04-04 17:31:29 +0000384 // checking that we have a valid thread state - since we use our own threading and locking
385 // in some (rare) cases during cleanup Python may end up believing we have no thread state
386 // and PyImport_AddModule will crash if that is the case - since that seems to only happen
387 // when destroying the SBDebugger, we can make do without clearing up stdout and stderr
388 if (PyThreadState_Get())
Johnny Chen41641f92012-02-29 01:52:13 +0000389 {
Enrico Granata7aa754c2012-04-04 17:31:29 +0000390 PyObject *sysmod = PyImport_AddModule ("sys");
391 PyObject *sysdict = PyModule_GetDict (sysmod);
392
393 if (m_new_sysout && sysmod && sysdict)
394 {
395 if (m_old_sysout)
396 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_old_sysout);
397 if (m_old_syserr)
398 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_old_syserr);
399 }
Johnny Chen41641f92012-02-29 01:52:13 +0000400 }
401
Caroline Tice0aa2e552011-01-14 00:29:16 +0000402 m_session_is_active = false;
403}
404
405void
406ScriptInterpreterPython::EnterSession ()
407{
408 // If we have already entered the session, without having officially 'left' it, then there is no need to
409 // 'enter' it again.
410
411 if (m_session_is_active)
412 return;
413
414 m_session_is_active = true;
415
Caroline Tice202f6b82011-01-17 21:55:19 +0000416 StreamString run_string;
417
Greg Clayton2fecc452012-01-28 02:11:02 +0000418 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %llu", m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
419 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)", GetCommandInterpreter().GetDebugger().GetID());
420 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
421 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
422 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
423 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
424 // Make sure STDIN is closed since when we run this as an embedded
425 // interpreter we don't want someone to call "line = sys.stdin.readline()"
426 // and lock up. We don't have multiple windows and when the interpreter is
427 // embedded we don't know we should be feeding input to the embedded
428 // interpreter or to the python sys.stdin. We also don't want to let python
429 // play with the real stdin from this process, so we need to close it...
Greg Clayton3eeaf6e2012-02-03 01:30:30 +0000430 //run_string.PutCString ("; sys.stdin.close()");
Greg Clayton2fecc452012-01-28 02:11:02 +0000431 run_string.PutCString ("')");
Caroline Tice0aa2e552011-01-14 00:29:16 +0000432
Caroline Tice6af65cb2011-05-03 21:21:50 +0000433 PyRun_SimpleString (run_string.GetData());
434 run_string.Clear();
Johnny Chen41641f92012-02-29 01:52:13 +0000435
Caroline Tice0aa2e552011-01-14 00:29:16 +0000436 PyObject *sysmod = PyImport_AddModule ("sys");
437 PyObject *sysdict = PyModule_GetDict (sysmod);
Johnny Chen41641f92012-02-29 01:52:13 +0000438
Greg Clayton2fecc452012-01-28 02:11:02 +0000439 if (m_new_sysout && sysmod && sysdict)
440 {
Johnny Chen41641f92012-02-29 01:52:13 +0000441 m_old_sysout = PyDict_GetItemString(sysdict, "stdout");
442 m_old_syserr = PyDict_GetItemString(sysdict, "stderr");
Johnny Chenc65046d2012-03-08 20:53:04 +0000443 if (m_new_sysout)
444 {
445 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
446 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
447 }
Greg Clayton2fecc452012-01-28 02:11:02 +0000448 }
Johnny Chen41641f92012-02-29 01:52:13 +0000449
Caroline Tice0aa2e552011-01-14 00:29:16 +0000450 if (PyErr_Occurred())
451 PyErr_Clear ();
Greg Clayton2fecc452012-01-28 02:11:02 +0000452}
Caroline Tice0aa2e552011-01-14 00:29:16 +0000453
Enrico Granata400105d2012-03-06 23:42:15 +0000454static PyObject*
455FindSessionDictionary (const char* dict_name)
456{
457 static std::map<ConstString,PyObject*> g_dict_map;
458
459 ConstString dict(dict_name);
460
461 std::map<ConstString,PyObject*>::iterator iter = g_dict_map.find(dict);
462
463 if (iter != g_dict_map.end())
464 return iter->second;
465
466 PyObject *main_mod = PyImport_AddModule ("__main__");
467 if (main_mod != NULL)
468 {
469 PyObject *main_dict = PyModule_GetDict (main_mod);
470 if ((main_dict != NULL)
471 && PyDict_Check (main_dict))
472 {
473 // Go through the main dictionary looking for the correct python script interpreter dictionary
474 PyObject *key, *value;
475 Py_ssize_t pos = 0;
476
477 while (PyDict_Next (main_dict, &pos, &key, &value))
478 {
479 // We have stolen references to the key and value objects in the dictionary; we need to increment
480 // them now so that Python's garbage collector doesn't collect them out from under us.
481 Py_INCREF (key);
482 Py_INCREF (value);
483 if (strcmp (PyString_AsString (key), dict_name) == 0)
484 {
485 g_dict_map[dict] = value;
486 return value;
487 }
488 }
489 }
490 }
491 return NULL;
492}
493
494static std::string
495GenerateUniqueName (const char* base_name_wanted,
496 uint32_t& functions_counter,
497 void* name_token = NULL)
498{
499 StreamString sstr;
500
501 if (!base_name_wanted)
502 return std::string();
503
504 if (!name_token)
505 sstr.Printf ("%s_%d", base_name_wanted, functions_counter++);
506 else
507 sstr.Printf ("%s_%p", base_name_wanted, name_token);
508
509 return sstr.GetString();
510}
511
Johnny Chen60dde642010-07-30 22:33:14 +0000512bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000513ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000514{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000515 if (!m_valid_session)
516 return false;
517
Caroline Tice4a461da2011-01-14 21:09:29 +0000518 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
519 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
520 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
521 // method to pass the command string directly down to Python.
522
Enrico Granatafa1f6172011-10-24 17:22:21 +0000523 Locker locker(this,
524 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
525 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000526
527 bool success = false;
528
Greg Clayton63094e02010-06-23 01:19:29 +0000529 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000530 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000531 // Find the correct script interpreter dictionary in the main module.
Enrico Granata400105d2012-03-06 23:42:15 +0000532 PyObject *script_interpreter_dict = FindSessionDictionary(m_dictionary_name.c_str());
533 if (script_interpreter_dict != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000534 {
Enrico Granata400105d2012-03-06 23:42:15 +0000535 PyObject *pfunc = (PyObject*)m_run_one_line;
536 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
537 if (pmod != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000538 {
Enrico Granata400105d2012-03-06 23:42:15 +0000539 PyObject *pmod_dict = PyModule_GetDict (pmod);
540 if ((pmod_dict != NULL)
541 && PyDict_Check (pmod_dict))
Caroline Tice4a461da2011-01-14 21:09:29 +0000542 {
Enrico Granata400105d2012-03-06 23:42:15 +0000543 if (!pfunc)
Caroline Tice4a461da2011-01-14 21:09:29 +0000544 {
545 PyObject *key, *value;
546 Py_ssize_t pos = 0;
547
548 while (PyDict_Next (pmod_dict, &pos, &key, &value))
549 {
550 Py_INCREF (key);
551 Py_INCREF (value);
552 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
553 {
554 pfunc = value;
555 break;
556 }
557 }
Enrico Granata400105d2012-03-06 23:42:15 +0000558 m_run_one_line = pfunc;
559 }
560
561 if (pfunc && PyCallable_Check (pfunc))
562 {
563 PyObject *pargs = Py_BuildValue("(Os)",script_interpreter_dict,command);
564 if (pargs != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000565 {
Enrico Granata400105d2012-03-06 23:42:15 +0000566 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
567 Py_DECREF (pargs);
568 if (pvalue != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000569 {
Enrico Granata400105d2012-03-06 23:42:15 +0000570 Py_DECREF (pvalue);
571 success = true;
572 }
573 else if (PyErr_Occurred ())
574 {
575 PyErr_Print();
576 PyErr_Clear();
Caroline Tice4a461da2011-01-14 21:09:29 +0000577 }
578 }
579 }
580 }
Caroline Tice4a461da2011-01-14 21:09:29 +0000581 }
Enrico Granata400105d2012-03-06 23:42:15 +0000582 Py_INCREF (script_interpreter_dict);
Caroline Tice4a461da2011-01-14 21:09:29 +0000583 }
Greg Clayton63094e02010-06-23 01:19:29 +0000584
Caroline Tice4a461da2011-01-14 21:09:29 +0000585 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000586 return true;
587
588 // The one-liner failed. Append the error message.
589 if (result)
590 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
591 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000592 }
Johnny Chen60dde642010-07-30 22:33:14 +0000593
594 if (result)
595 result->AppendError ("empty command passed to python\n");
596 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000597}
598
Chris Lattner24943d22010-06-08 16:52:24 +0000599size_t
600ScriptInterpreterPython::InputReaderCallback
601(
602 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000603 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000604 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000605 const char *bytes,
606 size_t bytes_len
607)
608{
Caroline Tice2ade6112010-11-10 19:18:14 +0000609 lldb::thread_t embedded_interpreter_thread;
610 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
611
Chris Lattner24943d22010-06-08 16:52:24 +0000612 if (baton == NULL)
613 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000614
615 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000616
Caroline Tice0aa2e552011-01-14 00:29:16 +0000617 if (script_interpreter->m_script_lang != eScriptLanguagePython)
618 return 0;
619
Caroline Tice892fadd2011-06-16 16:27:19 +0000620 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
621 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
622
Chris Lattner24943d22010-06-08 16:52:24 +0000623 switch (notification)
624 {
625 case eInputReaderActivate:
626 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000627 if (!batch_mode)
628 {
629 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
630 out_stream->Flush();
631 }
Greg Clayton58928562011-02-09 01:08:52 +0000632
Chris Lattner24943d22010-06-08 16:52:24 +0000633 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000634 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
635 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000636 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000637
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000638 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000639
Caroline Tice202f6b82011-01-17 21:55:19 +0000640 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000641 ScriptInterpreterPython::Locker locker(script_interpreter,
642 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
643 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000644 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000645
Caroline Tice2ade6112010-11-10 19:18:14 +0000646 char error_str[1024];
647 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
648 sizeof(error_str)))
649 {
650 if (log)
651 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
652 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
653 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
654 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
655 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000656 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000657 {
658 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000659 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000660 Error detach_error;
661 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
662 }
663 else
664 {
665 if (log)
666 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
667 reader.SetIsDone (true);
668 }
669 }
670 else
671 {
672 if (log)
673 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
674 reader.SetIsDone (true);
675 }
Chris Lattner24943d22010-06-08 16:52:24 +0000676 }
677 break;
678
679 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000680 // When another input reader is pushed, don't leave the session...
681 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000682 break;
683
684 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000685 {
Greg Claytona1cec242012-01-06 00:47:38 +0000686 // Don't try and acquire the interpreter lock here because code like
687 // this:
688 //
689 // (lldb) script
690 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
691 //
692 // This will cause the process to run. The interpreter lock is taken
693 // by the input reader for the "script" command. If we try and acquire
694 // the lock here, when the process runs it might deactivate this input
695 // reader (if STDIN is hooked up to the inferior process) and
696 // reactivate it when the process stops which will deadlock.
697 //ScriptInterpreterPython::Locker locker(script_interpreter,
698 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
699 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000700 }
Chris Lattner24943d22010-06-08 16:52:24 +0000701 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000702
Caroline Tice4a348082011-05-02 20:41:46 +0000703 case eInputReaderAsynchronousOutputWritten:
704 break;
705
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000706 case eInputReaderInterrupt:
707 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
708 break;
709
710 case eInputReaderEndOfFile:
711 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
712 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000713
714 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000715 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000716 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000717 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000718 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000719 bytes_len);
720 if (bytes && bytes_len)
721 {
722 if ((int) bytes[0] == 4)
723 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
724 else
725 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
726 }
727 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000728 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000729 else
730 {
731 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000732 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000733 bytes,
734 bytes_len);
735 reader.SetIsDone (true);
736 }
737
Chris Lattner24943d22010-06-08 16:52:24 +0000738 break;
739
740 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000741 script_interpreter->LeaveSession ();
742
Chris Lattner24943d22010-06-08 16:52:24 +0000743 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000744 if (log)
745 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000746
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000747 script_interpreter->RestoreTerminalState ();
748
Caroline Tice2ade6112010-11-10 19:18:14 +0000749 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000750 break;
751 }
752
753 return bytes_len;
754}
755
756
757void
Greg Clayton238c0a12010-09-18 01:14:36 +0000758ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000759{
760 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
761
Caroline Tice0aa2e552011-01-14 00:29:16 +0000762 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000763
764 // At the moment, the only time the debugger does not have an input file handle is when this is called
765 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
766 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
767 // do it.
768
Greg Clayton58928562011-02-09 01:08:52 +0000769 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000770 return;
771
Greg Clayton63094e02010-06-23 01:19:29 +0000772 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000773 if (reader_sp)
774 {
775 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
776 this, // baton
777 eInputReaderGranularityLine, // token size, to pass to callback function
778 NULL, // end token
779 NULL, // prompt
780 true)); // echo input
781
782 if (error.Success())
783 {
Greg Clayton63094e02010-06-23 01:19:29 +0000784 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000785 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000786 }
787 }
788}
789
790bool
791ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000792 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000793 void *ret_value)
794{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000795
Enrico Granatafa1f6172011-10-24 17:22:21 +0000796 Locker locker(this,
797 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
798 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000799
Chris Lattner24943d22010-06-08 16:52:24 +0000800 PyObject *py_return = NULL;
801 PyObject *mainmod = PyImport_AddModule ("__main__");
802 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000803 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000804 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000805 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000806 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000807 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000808
Enrico Granata400105d2012-03-06 23:42:15 +0000809 locals = FindSessionDictionary(m_dictionary_name.c_str());
810
Caroline Tice0aa2e552011-01-14 00:29:16 +0000811 if (locals == NULL)
812 {
813 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
814 should_decrement_locals = true;
815 }
816
817 if (locals == NULL)
818 {
819 locals = globals;
820 should_decrement_locals = false;
821 }
822
823 py_error = PyErr_Occurred();
824 if (py_error != NULL)
825 PyErr_Clear();
826
Chris Lattner24943d22010-06-08 16:52:24 +0000827 if (in_string != NULL)
828 {
829 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
830 if (py_return == NULL)
831 {
832 py_error = PyErr_Occurred ();
833 if (py_error != NULL)
834 PyErr_Clear ();
835
836 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
837 }
838
Caroline Tice0aa2e552011-01-14 00:29:16 +0000839 if (locals != NULL
840 && should_decrement_locals)
841 Py_DECREF (locals);
842
Chris Lattner24943d22010-06-08 16:52:24 +0000843 if (py_return != NULL)
844 {
845 switch (return_type)
846 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000847 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000848 {
849 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000850 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000851 break;
852 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000853 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000854 {
855 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000856 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000857 break;
858 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000859 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000860 {
861 const char format[2] = "b";
862 success = PyArg_Parse (py_return, format, (bool *) ret_value);
863 break;
864 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000865 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000866 {
867 const char format[2] = "h";
868 success = PyArg_Parse (py_return, format, (short *) ret_value);
869 break;
870 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000871 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000872 {
873 const char format[2] = "H";
874 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
875 break;
876 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000877 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000878 {
879 const char format[2] = "i";
880 success = PyArg_Parse (py_return, format, (int *) ret_value);
881 break;
882 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000883 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000884 {
885 const char format[2] = "I";
886 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
887 break;
888 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000889 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000890 {
891 const char format[2] = "l";
892 success = PyArg_Parse (py_return, format, (long *) ret_value);
893 break;
894 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000895 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000896 {
897 const char format[2] = "k";
898 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
899 break;
900 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000901 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000902 {
903 const char format[2] = "L";
904 success = PyArg_Parse (py_return, format, (long long *) ret_value);
905 break;
906 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000907 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000908 {
909 const char format[2] = "K";
910 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
911 break;
912 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000913 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000914 {
915 const char format[2] = "f";
916 success = PyArg_Parse (py_return, format, (float *) ret_value);
917 break;
918 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000919 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000920 {
921 const char format[2] = "d";
922 success = PyArg_Parse (py_return, format, (double *) ret_value);
923 break;
924 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000925 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000926 {
927 const char format[2] = "c";
928 success = PyArg_Parse (py_return, format, (char *) ret_value);
929 break;
930 }
931 default:
932 {}
933 }
934 Py_DECREF (py_return);
935 if (success)
936 ret_success = true;
937 else
938 ret_success = false;
939 }
940 }
941
942 py_error = PyErr_Occurred();
943 if (py_error != NULL)
944 {
945 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
946 PyErr_Print ();
947 PyErr_Clear();
948 ret_success = false;
949 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000950
Chris Lattner24943d22010-06-08 16:52:24 +0000951 return ret_success;
952}
953
954bool
955ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
956{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000957
958
959 Locker locker(this,
960 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
961 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000962
Chris Lattner24943d22010-06-08 16:52:24 +0000963 bool success = false;
964 PyObject *py_return = NULL;
965 PyObject *mainmod = PyImport_AddModule ("__main__");
966 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000967 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000968 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000969 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000970
Enrico Granata400105d2012-03-06 23:42:15 +0000971 locals = FindSessionDictionary(m_dictionary_name.c_str());
972
Caroline Tice0aa2e552011-01-14 00:29:16 +0000973 if (locals == NULL)
974 {
975 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
976 should_decrement_locals = true;
977 }
978
979 if (locals == NULL)
980 {
981 locals = globals;
982 should_decrement_locals = false;
983 }
984
985 py_error = PyErr_Occurred();
986 if (py_error != NULL)
987 PyErr_Clear();
988
Chris Lattner24943d22010-06-08 16:52:24 +0000989 if (in_string != NULL)
990 {
991 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
992 if (compiled_node)
993 {
994 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
995 if (compiled_code)
996 {
997 py_return = PyEval_EvalCode (compiled_code, globals, locals);
998 if (py_return != NULL)
999 {
1000 success = true;
1001 Py_DECREF (py_return);
1002 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001003 if (locals && should_decrement_locals)
1004 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +00001005 }
1006 }
1007 }
1008
1009 py_error = PyErr_Occurred ();
1010 if (py_error != NULL)
1011 {
1012 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1013 PyErr_Print ();
1014 PyErr_Clear();
1015 success = false;
1016 }
1017
1018 return success;
1019}
1020
1021static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1022
1023size_t
1024ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1025(
1026 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001027 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001028 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001029 const char *bytes,
1030 size_t bytes_len
1031)
1032{
Caroline Tice892fadd2011-06-16 16:27:19 +00001033 static StringList commands_in_progress;
1034
1035 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1036 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1037
Chris Lattner24943d22010-06-08 16:52:24 +00001038 switch (notification)
1039 {
1040 case eInputReaderActivate:
1041 {
1042 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +00001043 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +00001044 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001045 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001046 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +00001047 out_stream->Printf ("%s", reader.GetPrompt());
1048 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001049 }
1050 }
1051 break;
1052
1053 case eInputReaderDeactivate:
1054 break;
1055
1056 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001057 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001058 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001059 out_stream->Printf ("%s", reader.GetPrompt());
1060 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001061 }
Chris Lattner24943d22010-06-08 16:52:24 +00001062 break;
1063
Caroline Tice4a348082011-05-02 20:41:46 +00001064 case eInputReaderAsynchronousOutputWritten:
1065 break;
1066
Chris Lattner24943d22010-06-08 16:52:24 +00001067 case eInputReaderGotToken:
1068 {
1069 std::string temp_string (bytes, bytes_len);
1070 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001071 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001072 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001073 out_stream->Printf ("%s", reader.GetPrompt());
1074 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001075 }
Chris Lattner24943d22010-06-08 16:52:24 +00001076 }
1077 break;
1078
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001079 case eInputReaderEndOfFile:
1080 case eInputReaderInterrupt:
1081 // Control-c (SIGINT) & control-d both mean finish & exit.
1082 reader.SetIsDone(true);
1083
1084 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1085 if (notification == eInputReaderInterrupt)
1086 commands_in_progress.Clear();
1087
1088 // Fall through here...
1089
Chris Lattner24943d22010-06-08 16:52:24 +00001090 case eInputReaderDone:
1091 {
1092 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1093 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1094 data_ap->user_source.AppendList (commands_in_progress);
1095 if (data_ap.get())
1096 {
Greg Clayton63094e02010-06-23 01:19:29 +00001097 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001098 if (interpreter)
1099 {
1100 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1101 data_ap->script_source))
1102 {
Enrico Granata400105d2012-03-06 23:42:15 +00001103 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1104 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001105 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001106 else if (!batch_mode)
1107 {
1108 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1109 out_stream->Flush();
1110 }
Chris Lattner24943d22010-06-08 16:52:24 +00001111 }
1112 else
1113 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001114 if (!batch_mode)
1115 {
1116 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1117 out_stream->Flush();
1118 }
Chris Lattner24943d22010-06-08 16:52:24 +00001119 }
1120 }
1121 }
1122 break;
1123
1124 }
1125
1126 return bytes_len;
1127}
1128
1129void
Greg Clayton238c0a12010-09-18 01:14:36 +00001130ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001131 CommandReturnObject &result)
1132{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001133 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1134
Greg Clayton63094e02010-06-23 01:19:29 +00001135 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001136
1137 if (reader_sp)
1138 {
1139 Error err = reader_sp->Initialize (
1140 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1141 bp_options, // baton
1142 eInputReaderGranularityLine, // token size, for feeding data to callback function
1143 "DONE", // end token
1144 "> ", // prompt
1145 true); // echo input
1146
1147 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001148 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001149 else
1150 {
1151 result.AppendError (err.AsCString());
1152 result.SetStatus (eReturnStatusFailed);
1153 }
1154 }
1155 else
1156 {
1157 result.AppendError("out of memory");
1158 result.SetStatus (eReturnStatusFailed);
1159 }
1160}
1161
Johnny Chen3e0571b2010-09-11 00:23:59 +00001162// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001163void
Greg Clayton238c0a12010-09-18 01:14:36 +00001164ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001165 const char *oneliner)
1166{
1167 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1168
1169 // It's necessary to set both user_source and script_source to the oneliner.
1170 // The former is used to generate callback description (as in breakpoint command list)
1171 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001172
Johnny Chend1c2dca2010-09-10 18:21:10 +00001173 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001174
Caroline Tice5136f942010-09-27 21:35:15 +00001175 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1176 {
Enrico Granata400105d2012-03-06 23:42:15 +00001177 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1178 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Caroline Tice5136f942010-09-27 21:35:15 +00001179 }
1180
Johnny Chend1c2dca2010-09-10 18:21:10 +00001181 return;
1182}
1183
Chris Lattner24943d22010-06-08 16:52:24 +00001184bool
1185ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1186{
1187 // Convert StringList to one long, newline delimited, const char *.
Enrico Granata400105d2012-03-06 23:42:15 +00001188 std::string function_def_string(function_def.CopyList());
Chris Lattner24943d22010-06-08 16:52:24 +00001189
1190 return ExecuteMultipleLines (function_def_string.c_str());
1191}
1192
Enrico Granataf7a9b142011-07-15 02:26:42 +00001193bool
Enrico Granata400105d2012-03-06 23:42:15 +00001194ScriptInterpreterPython::GenerateFunction(const char *signature, const StringList &input)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001195{
1196 int num_lines = input.GetSize ();
1197 if (num_lines == 0)
1198 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001199
1200 if (!signature || *signature == 0)
1201 return false;
1202
Enrico Granataf7a9b142011-07-15 02:26:42 +00001203 StreamString sstr;
1204 StringList auto_generated_function;
Enrico Granata400105d2012-03-06 23:42:15 +00001205 auto_generated_function.AppendString (signature);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001206 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1207 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1208 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1209 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1210 // global dictionary.
1211
1212 // Wrap everything up inside the function, increasing the indentation.
1213
1214 for (int i = 0; i < num_lines; ++i)
1215 {
1216 sstr.Clear ();
1217 sstr.Printf (" %s", input.GetStringAtIndex (i));
1218 auto_generated_function.AppendString (sstr.GetData());
1219 }
1220 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1221 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1222 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1223 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1224
1225 // Verify that the results are valid Python.
1226
1227 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1228 return false;
1229
1230 return true;
1231
1232}
1233
Enrico Granataf7a9b142011-07-15 02:26:42 +00001234bool
Enrico Granata400105d2012-03-06 23:42:15 +00001235ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001236{
Enrico Granata400105d2012-03-06 23:42:15 +00001237 static uint32_t num_created_functions = 0;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001238 user_input.RemoveBlankLines ();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001239 StreamString sstr;
1240
1241 // Check to see if we have any data; if not, just return.
1242 if (user_input.GetSize() == 0)
1243 return false;
1244
1245 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1246 // ValueObject as parameter to the function.
1247
Enrico Granata400105d2012-03-06 23:42:15 +00001248 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 +00001249 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
Enrico Granataf7a9b142011-07-15 02:26:42 +00001250
Enrico Granata400105d2012-03-06 23:42:15 +00001251 if (!GenerateFunction(sstr.GetData(), user_input))
Enrico Granataf7a9b142011-07-15 02:26:42 +00001252 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001253
Enrico Granataf7a9b142011-07-15 02:26:42 +00001254 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001255 output.assign(auto_generated_function_name);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001256 return true;
1257}
1258
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001259bool
Enrico Granata400105d2012-03-06 23:42:15 +00001260ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, std::string &output)
Enrico Granatac2a28252011-08-16 16:49:25 +00001261{
Enrico Granata400105d2012-03-06 23:42:15 +00001262 static uint32_t num_created_functions = 0;
Enrico Granatac2a28252011-08-16 16:49:25 +00001263 user_input.RemoveBlankLines ();
Enrico Granatac2a28252011-08-16 16:49:25 +00001264 StreamString sstr;
1265
1266 // Check to see if we have any data; if not, just return.
1267 if (user_input.GetSize() == 0)
1268 return false;
1269
Enrico Granata400105d2012-03-06 23:42:15 +00001270 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_cmd_alias_func", num_created_functions));
1271
Enrico Granata271568f2011-09-09 01:41:30 +00001272 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001273
Enrico Granata400105d2012-03-06 23:42:15 +00001274 if (!GenerateFunction(sstr.GetData(),user_input))
Enrico Granatac2a28252011-08-16 16:49:25 +00001275 return false;
1276
1277 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001278 output.assign(auto_generated_function_name);
Enrico Granatac2a28252011-08-16 16:49:25 +00001279 return true;
1280}
1281
1282
1283bool
Enrico Granata400105d2012-03-06 23:42:15 +00001284ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, std::string &output, void* name_token)
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001285{
Enrico Granata400105d2012-03-06 23:42:15 +00001286 static uint32_t num_created_classes = 0;
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001287 user_input.RemoveBlankLines ();
1288 int num_lines = user_input.GetSize ();
1289 StreamString sstr;
1290
1291 // Check to see if we have any data; if not, just return.
1292 if (user_input.GetSize() == 0)
1293 return false;
1294
1295 // Wrap all user input into a Python class
1296
Enrico Granata400105d2012-03-06 23:42:15 +00001297 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 +00001298
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001299 StringList auto_generated_class;
1300
1301 // Create the function name & definition string.
1302
1303 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1304 auto_generated_class.AppendString (sstr.GetData());
1305
1306 // Wrap everything up inside the class, increasing the indentation.
1307
1308 for (int i = 0; i < num_lines; ++i)
1309 {
1310 sstr.Clear ();
1311 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1312 auto_generated_class.AppendString (sstr.GetData());
1313 }
1314
1315
1316 // Verify that the results are valid Python.
1317 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1318 // (TODO: rename that method to ExportDefinitionToInterpreter)
1319 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1320 return false;
1321
1322 // Store the name of the auto-generated class
1323
Enrico Granata400105d2012-03-06 23:42:15 +00001324 output.assign(auto_generated_class_name);
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001325 return true;
1326}
1327
Enrico Granata400105d2012-03-06 23:42:15 +00001328lldb::ScriptInterpreterObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001329ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1330 lldb::ValueObjectSP valobj)
1331{
1332 if (class_name.empty())
Enrico Granata400105d2012-03-06 23:42:15 +00001333 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001334
1335 if (!valobj.get())
Enrico Granata400105d2012-03-06 23:42:15 +00001336 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001337
Greg Claytonb4d7fc02012-02-17 07:49:44 +00001338 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1339 Target *target = exe_ctx.GetTargetPtr();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001340
1341 if (!target)
Enrico Granata400105d2012-03-06 23:42:15 +00001342 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001343
1344 Debugger &debugger = target->GetDebugger();
1345 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1346 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1347
1348 if (!script_interpreter)
Enrico Granata400105d2012-03-06 23:42:15 +00001349 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001350
1351 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001352
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001353 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001354 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001355 ForceDisableSyntheticChildren no_synthetics(target);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001356 ret_val = g_swig_synthetic_script (class_name,
1357 python_interpreter->m_dictionary_name.c_str(),
1358 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001359 }
1360
Enrico Granata400105d2012-03-06 23:42:15 +00001361 return MakeScriptObject(ret_val);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001362}
1363
Enrico Granataf7a9b142011-07-15 02:26:42 +00001364bool
Enrico Granata400105d2012-03-06 23:42:15 +00001365ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001366{
Enrico Granata16376ed2012-02-15 02:34:21 +00001367 StringList input;
1368 input.SplitIntoLines(oneliner, strlen(oneliner));
1369 return GenerateTypeScriptFunction(input, output, name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001370}
1371
Chris Lattner24943d22010-06-08 16:52:24 +00001372bool
Enrico Granata400105d2012-03-06 23:42:15 +00001373ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, std::string& output, void* name_token)
Enrico Granata16376ed2012-02-15 02:34:21 +00001374{
1375 StringList input;
1376 input.SplitIntoLines(oneliner, strlen(oneliner));
1377 return GenerateTypeSynthClass(input, output, name_token);
1378}
1379
1380
1381bool
Enrico Granata400105d2012-03-06 23:42:15 +00001382ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, std::string& output)
Chris Lattner24943d22010-06-08 16:52:24 +00001383{
Enrico Granata400105d2012-03-06 23:42:15 +00001384 static uint32_t num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001385 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001386 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001387
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001388 if (user_input.GetSize() == 0)
1389 return false;
1390
Enrico Granata400105d2012-03-06 23:42:15 +00001391 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_bp_callback_func_",num_created_functions));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001392 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001393
Enrico Granata400105d2012-03-06 23:42:15 +00001394 if (!GenerateFunction(sstr.GetData(), user_input))
Caroline Ticeb447e842010-09-21 19:25:28 +00001395 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001396
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001397 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001398 output.assign(auto_generated_function_name);
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001399 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001400}
1401
Enrico Granata1328b142012-02-29 03:28:49 +00001402bool
1403ScriptInterpreterPython::GetScriptedSummary (const char *python_function_name,
1404 lldb::ValueObjectSP valobj,
1405 lldb::ScriptInterpreterObjectSP& callee_wrapper_sp,
1406 std::string& retval)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001407{
1408
Enrico Granata1328b142012-02-29 03:28:49 +00001409 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001410
1411 if (!valobj.get())
Enrico Granata1328b142012-02-29 03:28:49 +00001412 {
1413 retval.assign("<no object>");
1414 return false;
1415 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001416
Enrico Granata1328b142012-02-29 03:28:49 +00001417 void* old_callee = (callee_wrapper_sp ? callee_wrapper_sp->GetObject() : NULL);
1418 void* new_callee = old_callee;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001419
Enrico Granata1328b142012-02-29 03:28:49 +00001420 bool ret_val;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001421 if (python_function_name
1422 && *python_function_name)
1423 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001424 {
Enrico Granata1328b142012-02-29 03:28:49 +00001425 Locker py_lock(this);
1426 {
1427 Timer scoped_timer ("g_swig_typescript_callback","g_swig_typescript_callback");
1428 ret_val = g_swig_typescript_callback (python_function_name,
1429 FindSessionDictionary(m_dictionary_name.c_str()),
1430 valobj,
1431 &new_callee,
1432 retval);
1433 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001434 }
1435 }
1436 else
Enrico Granata1328b142012-02-29 03:28:49 +00001437 {
1438 retval.assign("<no function name>");
1439 return false;
1440 }
1441
1442 if (new_callee && old_callee != new_callee)
1443 callee_wrapper_sp = MakeScriptObject(new_callee);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001444
1445 return ret_val;
1446
1447}
1448
Greg Clayton5144f382010-10-07 17:14:24 +00001449bool
1450ScriptInterpreterPython::BreakpointCallbackFunction
1451(
1452 void *baton,
1453 StoppointCallbackContext *context,
1454 user_id_t break_id,
1455 user_id_t break_loc_id
1456)
1457{
1458 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
Enrico Granata400105d2012-03-06 23:42:15 +00001459 const char *python_function_name = bp_option_data->script_source.c_str();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001460
1461 if (!context)
1462 return true;
1463
Greg Claytonf4124de2012-02-21 00:09:25 +00001464 ExecutionContext exe_ctx (context->exe_ctx_ref);
1465 Target *target = exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001466
1467 if (!target)
1468 return true;
1469
1470 Debugger &debugger = target->GetDebugger();
1471 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1472 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1473
1474 if (!script_interpreter)
1475 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001476
1477 if (python_function_name != NULL
1478 && python_function_name[0] != '\0')
1479 {
Greg Claytonf4124de2012-02-21 00:09:25 +00001480 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001481 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001482 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001483 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001484 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1485
1486 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001487 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001488 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001489 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001490 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001491 ret_val = g_swig_breakpoint_callback (python_function_name,
1492 python_interpreter->m_dictionary_name.c_str(),
1493 stop_frame_sp,
1494 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001495 }
1496 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001497 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001498 }
Greg Clayton5144f382010-10-07 17:14:24 +00001499 }
1500 // We currently always true so we stop in case anything goes wrong when
1501 // trying to call the script function
1502 return true;
1503}
Caroline Tice2ade6112010-11-10 19:18:14 +00001504
1505lldb::thread_result_t
1506ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1507{
1508 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1509
1510 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1511
1512 if (log)
1513 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1514
1515 char error_str[1024];
1516 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001517
Enrico Granatafa1f6172011-10-24 17:22:21 +00001518 Locker locker(script_interpreter,
1519 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1520 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1521
1522 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001523 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001524 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001525
Caroline Tice0aa2e552011-01-14 00:29:16 +00001526 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1527 PyRun_SimpleString (run_string.GetData());
1528 run_string.Clear ();
1529
1530 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1531 PyRun_SimpleString (run_string.GetData());
1532 run_string.Clear ();
1533
1534 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1535 PyRun_SimpleString (run_string.GetData());
1536 run_string.Clear ();
1537
1538 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1539 pty_slave_name);
1540 PyRun_SimpleString (run_string.GetData());
1541 run_string.Clear ();
1542
Johnny Chen8054ba32011-03-11 00:28:50 +00001543 // The following call drops into the embedded interpreter loop and stays there until the
1544 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001545
Caroline Ticece207c12011-03-11 00:21:55 +00001546 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001547 // 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 +00001548 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1549
1550 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1551 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1552 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1553 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1554 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1555 // hang (it's happened before).
1556
Caroline Tice9d352ce2011-03-07 23:24:28 +00001557 Py_BEGIN_ALLOW_THREADS
1558 PyGILState_STATE gstate = PyGILState_Ensure();
1559
Caroline Tice0aa2e552011-01-14 00:29:16 +00001560 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1561 PyRun_SimpleString (run_string.GetData());
1562 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001563
Caroline Tice9d352ce2011-03-07 23:24:28 +00001564 PyGILState_Release (gstate);
1565 Py_END_ALLOW_THREADS
1566
Caroline Tice0aa2e552011-01-14 00:29:16 +00001567 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1568 PyRun_SimpleString (run_string.GetData());
1569 run_string.Clear();
1570
1571 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1572 PyRun_SimpleString (run_string.GetData());
1573 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001574
Caroline Tice2ade6112010-11-10 19:18:14 +00001575 }
1576
1577 if (script_interpreter->m_embedded_thread_input_reader_sp)
1578 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1579
1580 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001581
Caroline Tice2ade6112010-11-10 19:18:14 +00001582 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1583 if (log)
1584 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1585
1586
Johnny Chen8054ba32011-03-11 00:28:50 +00001587 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001588 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001589 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1590 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1591 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001592
Caroline Tice2ade6112010-11-10 19:18:14 +00001593 return NULL;
1594}
1595
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001596uint32_t
Enrico Granata400105d2012-03-06 23:42:15 +00001597ScriptInterpreterPython::CalculateNumChildren (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001598{
Enrico Granata400105d2012-03-06 23:42:15 +00001599 if (!implementor_sp)
1600 return 0;
1601
1602 void* implementor = implementor_sp->GetObject();
1603
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001604 if (!implementor)
1605 return 0;
1606
1607 if (!g_swig_calc_children)
1608 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001609
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001610 uint32_t ret_val = 0;
1611
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001612 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001613 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001614 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001615 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001616 }
1617
1618 return ret_val;
1619}
1620
Enrico Granata91544802011-09-06 19:20:51 +00001621lldb::ValueObjectSP
Enrico Granata400105d2012-03-06 23:42:15 +00001622ScriptInterpreterPython::GetChildAtIndex (const lldb::ScriptInterpreterObjectSP& implementor_sp, uint32_t idx)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001623{
Enrico Granata400105d2012-03-06 23:42:15 +00001624 if (!implementor_sp)
1625 return lldb::ValueObjectSP();
1626
1627 void* implementor = implementor_sp->GetObject();
1628
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001629 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001630 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001631
Enrico Granata91544802011-09-06 19:20:51 +00001632 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1633 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001634
Enrico Granata91544802011-09-06 19:20:51 +00001635 void* child_ptr = NULL;
1636 lldb::SBValue* value_sb = NULL;
1637 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001638
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001639 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001640 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001641 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata91544802011-09-06 19:20:51 +00001642 child_ptr = g_swig_get_child_index (implementor,idx);
1643 if (child_ptr != NULL && child_ptr != Py_None)
1644 {
1645 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1646 if (value_sb == NULL)
1647 Py_XDECREF(child_ptr);
1648 else
1649 ret_val = value_sb->get_sp();
1650 }
1651 else
1652 {
1653 Py_XDECREF(child_ptr);
1654 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001655 }
1656
1657 return ret_val;
1658}
1659
1660int
Enrico Granata400105d2012-03-06 23:42:15 +00001661ScriptInterpreterPython::GetIndexOfChildWithName (const lldb::ScriptInterpreterObjectSP& implementor_sp, const char* child_name)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001662{
Enrico Granata400105d2012-03-06 23:42:15 +00001663 if (!implementor_sp)
1664 return UINT32_MAX;
1665
1666 void* implementor = implementor_sp->GetObject();
1667
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001668 if (!implementor)
1669 return UINT32_MAX;
1670
1671 if (!g_swig_get_index_child)
1672 return UINT32_MAX;
1673
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001674 int ret_val = UINT32_MAX;
1675
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001676 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001677 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001678 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001679 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001680 }
1681
1682 return ret_val;
1683}
1684
Enrico Granatacf09f882012-03-19 22:58:49 +00001685bool
Enrico Granata400105d2012-03-06 23:42:15 +00001686ScriptInterpreterPython::UpdateSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata979e20d2011-07-29 19:53:35 +00001687{
Enrico Granatacf09f882012-03-19 22:58:49 +00001688 bool ret_val = false;
1689
Enrico Granata400105d2012-03-06 23:42:15 +00001690 if (!implementor_sp)
Enrico Granatacf09f882012-03-19 22:58:49 +00001691 return ret_val;
Enrico Granata400105d2012-03-06 23:42:15 +00001692
1693 void* implementor = implementor_sp->GetObject();
1694
Enrico Granata979e20d2011-07-29 19:53:35 +00001695 if (!implementor)
Enrico Granatacf09f882012-03-19 22:58:49 +00001696 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001697
1698 if (!g_swig_update_provider)
Enrico Granatacf09f882012-03-19 22:58:49 +00001699 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001700
Enrico Granata979e20d2011-07-29 19:53:35 +00001701 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001702 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001703 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granatacf09f882012-03-19 22:58:49 +00001704 ret_val = g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001705 }
1706
Enrico Granatacf09f882012-03-19 22:58:49 +00001707 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001708}
1709
Enrico Granatac2a28252011-08-16 16:49:25 +00001710bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001711ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00001712 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00001713 lldb_private::Error& error)
1714{
1715 if (!pathname || !pathname[0])
1716 {
1717 error.SetErrorString("invalid pathname");
1718 return false;
1719 }
1720
1721 if (!g_swig_call_module_init)
1722 {
1723 error.SetErrorString("internal helper function missing");
1724 return false;
1725 }
1726
Greg Clayton13d24fb2012-01-29 20:56:30 +00001727 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granatafa1f6172011-10-24 17:22:21 +00001728
Enrico Granata59df36f2011-10-17 21:45:27 +00001729 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001730 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00001731
1732 FileSpec target_file(pathname, true);
1733
1734 // TODO: would we want to reject any other value?
1735 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1736 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1737 {
1738 error.SetErrorString("invalid pathname");
1739 return false;
1740 }
1741
1742 const char* directory = target_file.GetDirectory().GetCString();
1743 std::string basename(target_file.GetFilename().GetCString());
1744
1745 // now make sure that Python has "directory" in the search path
1746 StreamString command_stream;
1747 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1748 directory,
1749 directory);
Enrico Granatafa1f6172011-10-24 17:22:21 +00001750 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData());
Enrico Granata59df36f2011-10-17 21:45:27 +00001751 if (!syspath_retval)
1752 {
1753 error.SetErrorString("Python sys.path handling failed");
1754 return false;
1755 }
1756
1757 // strip .py or .pyc extension
1758 ConstString extension = target_file.GetFileNameExtension();
1759 if (::strcmp(extension.GetCString(), "py") == 0)
1760 basename.resize(basename.length()-3);
1761 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1762 basename.resize(basename.length()-4);
1763
1764 // check if the module is already import-ed
1765 command_stream.Clear();
1766 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1767 int refcount = 0;
1768 // this call will fail if the module does not exist (because the parameter to it is not a string
1769 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00001770 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
1771 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0);
1772 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00001773 {
1774 error.SetErrorString("module already imported");
1775 return false;
1776 }
1777
1778 // now actually do the import
1779 command_stream.Clear();
1780 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafa1f6172011-10-24 17:22:21 +00001781 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL);
Enrico Granata59df36f2011-10-17 21:45:27 +00001782 if (!import_retval)
1783 {
1784 error.SetErrorString("Python import statement failed");
1785 return false;
1786 }
1787
Enrico Granata16376ed2012-02-15 02:34:21 +00001788 // call __lldb_init_module(debugger,dict)
Enrico Granata59df36f2011-10-17 21:45:27 +00001789 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001790 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001791 debugger_sp))
1792 {
Enrico Granata16376ed2012-02-15 02:34:21 +00001793 error.SetErrorString("calling __lldb_init_module failed");
Enrico Granata59df36f2011-10-17 21:45:27 +00001794 return false;
1795 }
1796 return true;
1797 }
1798}
1799
Enrico Granata1328b142012-02-29 03:28:49 +00001800lldb::ScriptInterpreterObjectSP
1801ScriptInterpreterPython::MakeScriptObject (void* object)
1802{
1803 return lldb::ScriptInterpreterObjectSP(new ScriptInterpreterPythonObject(object));
1804}
1805
Enrico Granata6010ace2011-11-07 22:57:04 +00001806ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
1807 ScriptedCommandSynchronicity synchro) :
1808 m_debugger_sp(debugger_sp),
1809 m_synch_wanted(synchro),
1810 m_old_asynch(debugger_sp->GetAsyncExecution())
1811{
1812 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
1813 m_debugger_sp->SetAsyncExecution(false);
1814 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
1815 m_debugger_sp->SetAsyncExecution(true);
1816}
1817
1818ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
1819{
1820 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
1821 m_debugger_sp->SetAsyncExecution(m_old_asynch);
1822}
1823
Enrico Granata59df36f2011-10-17 21:45:27 +00001824bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001825ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1826 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00001827 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001828 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001829 Error& error)
1830{
1831 if (!impl_function)
1832 {
1833 error.SetErrorString("no function to execute");
1834 return false;
1835 }
1836
1837 if (!g_swig_call_command)
1838 {
1839 error.SetErrorString("no helper function to run scripted commands");
1840 return false;
1841 }
1842
Greg Clayton13d24fb2012-01-29 20:56:30 +00001843 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata6010ace2011-11-07 22:57:04 +00001844
1845 if (!debugger_sp.get())
1846 {
1847 error.SetErrorString("invalid Debugger pointer");
1848 return false;
1849 }
Enrico Granatac2a28252011-08-16 16:49:25 +00001850
1851 bool ret_val;
1852
1853 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00001854
Enrico Granatac2a28252011-08-16 16:49:25 +00001855 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001856 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00001857 SynchronicityHandler synch_handler(debugger_sp,
1858 synchronicity);
1859
Enrico Granatac2a28252011-08-16 16:49:25 +00001860 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001861 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00001862 debugger_sp,
1863 args,
1864 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001865 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001866 }
Enrico Granata6010ace2011-11-07 22:57:04 +00001867
Enrico Granatac2a28252011-08-16 16:49:25 +00001868 if (!ret_val)
1869 error.SetErrorString(err_msg.c_str());
1870 else
1871 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00001872
Enrico Granatac2a28252011-08-16 16:49:25 +00001873 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00001874}
1875
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001876// in Python, a special attribute __doc__ contains the docstring
1877// for an object (function, method, class, ...) if any is defined
1878// Otherwise, the attribute's value is None
1879std::string
1880ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1881{
1882 std::string command(item);
1883 command += ".__doc__";
1884
1885 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1886
1887 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001888 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001889 &result_ptr) && result_ptr)
1890 {
1891 return std::string(result_ptr);
1892 }
1893 else
1894 return std::string("");
1895}
Caroline Tice2ade6112010-11-10 19:18:14 +00001896
Caroline Tice0aa2e552011-01-14 00:29:16 +00001897void
Enrico Granata1328b142012-02-29 03:28:49 +00001898ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback)
Greg Claytone86cbb92011-03-22 01:14:58 +00001899{
1900 g_swig_init_callback = python_swig_init_callback;
Enrico Granata1328b142012-02-29 03:28:49 +00001901 g_swig_breakpoint_callback = LLDBSwigPythonBreakpointCallbackFunction;
1902 g_swig_typescript_callback = LLDBSwigPythonCallTypeScript;
1903 g_swig_synthetic_script = LLDBSwigPythonCreateSyntheticProvider;
1904 g_swig_calc_children = LLDBSwigPython_CalculateNumChildren;
1905 g_swig_get_child_index = LLDBSwigPython_GetChildAtIndex;
1906 g_swig_get_index_child = LLDBSwigPython_GetIndexOfChildWithName;
1907 g_swig_cast_to_sbvalue = LLDBSWIGPython_CastPyObjectToSBValue;
1908 g_swig_update_provider = LLDBSwigPython_UpdateSynthProviderInstance;
1909 g_swig_call_command = LLDBSwigPythonCallCommand;
1910 g_swig_call_module_init = LLDBSwigPythonCallModuleInit;
Greg Claytone86cbb92011-03-22 01:14:58 +00001911}
1912
1913void
1914ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001915{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001916 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1917
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001918 // Python will muck with STDIN terminal state, so save off any current TTY
1919 // settings so we can restore them.
1920 TerminalState stdin_tty_state;
1921 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001922
Caroline Tice9d352ce2011-03-07 23:24:28 +00001923 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001924 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001925
Greg Claytone86cbb92011-03-22 01:14:58 +00001926 // Initialize SWIG after setting up python
1927 assert (g_swig_init_callback != NULL);
1928 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001929
1930 // Update the path python uses to search for modules to include the current directory.
1931
Caroline Ticed4d92832011-06-13 21:33:00 +00001932 PyRun_SimpleString ("import sys");
1933 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001934
1935 // Find the module that owns this code and use that path we get to
1936 // set the sys.path appropriately.
1937
1938 FileSpec file_spec;
1939 char python_dir_path[PATH_MAX];
1940 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1941 {
1942 std::string python_path("sys.path.insert(0,\"");
1943 size_t orig_len = python_path.length();
1944 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1945 {
1946 python_path.append (python_dir_path);
1947 python_path.append ("\")");
1948 PyRun_SimpleString (python_path.c_str());
1949 python_path.resize (orig_len);
1950 }
1951
1952 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1953 {
1954 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1955 {
1956 python_path.append (python_dir_path);
1957 python_path.append ("\")");
1958 PyRun_SimpleString (python_path.c_str());
1959 python_path.resize (orig_len);
1960 }
1961 }
1962 }
1963
Jim Ingham4dfa5112011-08-22 19:10:09 +00001964 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001965
Caroline Ticed4d92832011-06-13 21:33:00 +00001966 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001967
Caroline Ticed4d92832011-06-13 21:33:00 +00001968 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1969 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00001970 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001971
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001972 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001973}
1974
Greg Claytone86cbb92011-03-22 01:14:58 +00001975//void
1976//ScriptInterpreterPython::Terminate ()
1977//{
1978// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1979// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1980// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1981// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1982// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1983// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1984// // within Py_Finalize, which results in a seg fault.
1985// //
1986// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1987// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1988// // process exits).
1989// //
1990//// Py_Finalize ();
1991//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00001992
1993#endif // #ifdef LLDB_DISABLE_PYTHON