blob: afde01fbebdaa935942b429eea64bb2d80f6f3a7 [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{
Johnny Chen41641f92012-02-29 01:52:13 +0000384 PyObject *sysmod = PyImport_AddModule ("sys");
385 PyObject *sysdict = PyModule_GetDict (sysmod);
386
387 if (m_new_sysout && sysmod && sysdict)
388 {
Johnny Chenc65046d2012-03-08 20:53:04 +0000389 if (m_old_sysout)
390 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_old_sysout);
391 if (m_old_syserr)
392 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_old_syserr);
Johnny Chen41641f92012-02-29 01:52:13 +0000393 }
394
Caroline Tice0aa2e552011-01-14 00:29:16 +0000395 m_session_is_active = false;
396}
397
398void
399ScriptInterpreterPython::EnterSession ()
400{
401 // If we have already entered the session, without having officially 'left' it, then there is no need to
402 // 'enter' it again.
403
404 if (m_session_is_active)
405 return;
406
407 m_session_is_active = true;
408
Caroline Tice202f6b82011-01-17 21:55:19 +0000409 StreamString run_string;
410
Greg Clayton2fecc452012-01-28 02:11:02 +0000411 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %llu", m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
412 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)", GetCommandInterpreter().GetDebugger().GetID());
413 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
414 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
415 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
416 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
417 // Make sure STDIN is closed since when we run this as an embedded
418 // interpreter we don't want someone to call "line = sys.stdin.readline()"
419 // and lock up. We don't have multiple windows and when the interpreter is
420 // embedded we don't know we should be feeding input to the embedded
421 // interpreter or to the python sys.stdin. We also don't want to let python
422 // play with the real stdin from this process, so we need to close it...
Greg Clayton3eeaf6e2012-02-03 01:30:30 +0000423 //run_string.PutCString ("; sys.stdin.close()");
Greg Clayton2fecc452012-01-28 02:11:02 +0000424 run_string.PutCString ("')");
Caroline Tice0aa2e552011-01-14 00:29:16 +0000425
Caroline Tice6af65cb2011-05-03 21:21:50 +0000426 PyRun_SimpleString (run_string.GetData());
427 run_string.Clear();
Johnny Chen41641f92012-02-29 01:52:13 +0000428
Caroline Tice0aa2e552011-01-14 00:29:16 +0000429 PyObject *sysmod = PyImport_AddModule ("sys");
430 PyObject *sysdict = PyModule_GetDict (sysmod);
Johnny Chen41641f92012-02-29 01:52:13 +0000431
Greg Clayton2fecc452012-01-28 02:11:02 +0000432 if (m_new_sysout && sysmod && sysdict)
433 {
Johnny Chen41641f92012-02-29 01:52:13 +0000434 m_old_sysout = PyDict_GetItemString(sysdict, "stdout");
435 m_old_syserr = PyDict_GetItemString(sysdict, "stderr");
Johnny Chenc65046d2012-03-08 20:53:04 +0000436 if (m_new_sysout)
437 {
438 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
439 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
440 }
Greg Clayton2fecc452012-01-28 02:11:02 +0000441 }
Johnny Chen41641f92012-02-29 01:52:13 +0000442
Caroline Tice0aa2e552011-01-14 00:29:16 +0000443 if (PyErr_Occurred())
444 PyErr_Clear ();
Greg Clayton2fecc452012-01-28 02:11:02 +0000445}
Caroline Tice0aa2e552011-01-14 00:29:16 +0000446
Enrico Granata400105d2012-03-06 23:42:15 +0000447static PyObject*
448FindSessionDictionary (const char* dict_name)
449{
450 static std::map<ConstString,PyObject*> g_dict_map;
451
452 ConstString dict(dict_name);
453
454 std::map<ConstString,PyObject*>::iterator iter = g_dict_map.find(dict);
455
456 if (iter != g_dict_map.end())
457 return iter->second;
458
459 PyObject *main_mod = PyImport_AddModule ("__main__");
460 if (main_mod != NULL)
461 {
462 PyObject *main_dict = PyModule_GetDict (main_mod);
463 if ((main_dict != NULL)
464 && PyDict_Check (main_dict))
465 {
466 // Go through the main dictionary looking for the correct python script interpreter dictionary
467 PyObject *key, *value;
468 Py_ssize_t pos = 0;
469
470 while (PyDict_Next (main_dict, &pos, &key, &value))
471 {
472 // We have stolen references to the key and value objects in the dictionary; we need to increment
473 // them now so that Python's garbage collector doesn't collect them out from under us.
474 Py_INCREF (key);
475 Py_INCREF (value);
476 if (strcmp (PyString_AsString (key), dict_name) == 0)
477 {
478 g_dict_map[dict] = value;
479 return value;
480 }
481 }
482 }
483 }
484 return NULL;
485}
486
487static std::string
488GenerateUniqueName (const char* base_name_wanted,
489 uint32_t& functions_counter,
490 void* name_token = NULL)
491{
492 StreamString sstr;
493
494 if (!base_name_wanted)
495 return std::string();
496
497 if (!name_token)
498 sstr.Printf ("%s_%d", base_name_wanted, functions_counter++);
499 else
500 sstr.Printf ("%s_%p", base_name_wanted, name_token);
501
502 return sstr.GetString();
503}
504
Johnny Chen60dde642010-07-30 22:33:14 +0000505bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000506ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000507{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000508 if (!m_valid_session)
509 return false;
510
Caroline Tice4a461da2011-01-14 21:09:29 +0000511 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
512 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
513 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
514 // method to pass the command string directly down to Python.
515
Enrico Granatafa1f6172011-10-24 17:22:21 +0000516 Locker locker(this,
517 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
518 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000519
520 bool success = false;
521
Greg Clayton63094e02010-06-23 01:19:29 +0000522 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000523 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000524 // Find the correct script interpreter dictionary in the main module.
Enrico Granata400105d2012-03-06 23:42:15 +0000525 PyObject *script_interpreter_dict = FindSessionDictionary(m_dictionary_name.c_str());
526 if (script_interpreter_dict != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000527 {
Enrico Granata400105d2012-03-06 23:42:15 +0000528 PyObject *pfunc = (PyObject*)m_run_one_line;
529 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
530 if (pmod != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000531 {
Enrico Granata400105d2012-03-06 23:42:15 +0000532 PyObject *pmod_dict = PyModule_GetDict (pmod);
533 if ((pmod_dict != NULL)
534 && PyDict_Check (pmod_dict))
Caroline Tice4a461da2011-01-14 21:09:29 +0000535 {
Enrico Granata400105d2012-03-06 23:42:15 +0000536 if (!pfunc)
Caroline Tice4a461da2011-01-14 21:09:29 +0000537 {
538 PyObject *key, *value;
539 Py_ssize_t pos = 0;
540
541 while (PyDict_Next (pmod_dict, &pos, &key, &value))
542 {
543 Py_INCREF (key);
544 Py_INCREF (value);
545 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
546 {
547 pfunc = value;
548 break;
549 }
550 }
Enrico Granata400105d2012-03-06 23:42:15 +0000551 m_run_one_line = pfunc;
552 }
553
554 if (pfunc && PyCallable_Check (pfunc))
555 {
556 PyObject *pargs = Py_BuildValue("(Os)",script_interpreter_dict,command);
557 if (pargs != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000558 {
Enrico Granata400105d2012-03-06 23:42:15 +0000559 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
560 Py_DECREF (pargs);
561 if (pvalue != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000562 {
Enrico Granata400105d2012-03-06 23:42:15 +0000563 Py_DECREF (pvalue);
564 success = true;
565 }
566 else if (PyErr_Occurred ())
567 {
568 PyErr_Print();
569 PyErr_Clear();
Caroline Tice4a461da2011-01-14 21:09:29 +0000570 }
571 }
572 }
573 }
Caroline Tice4a461da2011-01-14 21:09:29 +0000574 }
Enrico Granata400105d2012-03-06 23:42:15 +0000575 Py_INCREF (script_interpreter_dict);
Caroline Tice4a461da2011-01-14 21:09:29 +0000576 }
Greg Clayton63094e02010-06-23 01:19:29 +0000577
Caroline Tice4a461da2011-01-14 21:09:29 +0000578 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000579 return true;
580
581 // The one-liner failed. Append the error message.
582 if (result)
583 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
584 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000585 }
Johnny Chen60dde642010-07-30 22:33:14 +0000586
587 if (result)
588 result->AppendError ("empty command passed to python\n");
589 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000590}
591
Chris Lattner24943d22010-06-08 16:52:24 +0000592size_t
593ScriptInterpreterPython::InputReaderCallback
594(
595 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000596 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000597 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000598 const char *bytes,
599 size_t bytes_len
600)
601{
Caroline Tice2ade6112010-11-10 19:18:14 +0000602 lldb::thread_t embedded_interpreter_thread;
603 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
604
Chris Lattner24943d22010-06-08 16:52:24 +0000605 if (baton == NULL)
606 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000607
608 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000609
Caroline Tice0aa2e552011-01-14 00:29:16 +0000610 if (script_interpreter->m_script_lang != eScriptLanguagePython)
611 return 0;
612
Caroline Tice892fadd2011-06-16 16:27:19 +0000613 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
614 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
615
Chris Lattner24943d22010-06-08 16:52:24 +0000616 switch (notification)
617 {
618 case eInputReaderActivate:
619 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000620 if (!batch_mode)
621 {
622 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
623 out_stream->Flush();
624 }
Greg Clayton58928562011-02-09 01:08:52 +0000625
Chris Lattner24943d22010-06-08 16:52:24 +0000626 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000627 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
628 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000629 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000630
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000631 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000632
Caroline Tice202f6b82011-01-17 21:55:19 +0000633 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000634 ScriptInterpreterPython::Locker locker(script_interpreter,
635 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
636 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000637 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000638
Caroline Tice2ade6112010-11-10 19:18:14 +0000639 char error_str[1024];
640 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
641 sizeof(error_str)))
642 {
643 if (log)
644 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
645 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
646 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
647 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
648 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000649 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000650 {
651 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000652 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000653 Error detach_error;
654 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
655 }
656 else
657 {
658 if (log)
659 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
660 reader.SetIsDone (true);
661 }
662 }
663 else
664 {
665 if (log)
666 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
667 reader.SetIsDone (true);
668 }
Chris Lattner24943d22010-06-08 16:52:24 +0000669 }
670 break;
671
672 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000673 // When another input reader is pushed, don't leave the session...
674 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000675 break;
676
677 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000678 {
Greg Claytona1cec242012-01-06 00:47:38 +0000679 // Don't try and acquire the interpreter lock here because code like
680 // this:
681 //
682 // (lldb) script
683 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
684 //
685 // This will cause the process to run. The interpreter lock is taken
686 // by the input reader for the "script" command. If we try and acquire
687 // the lock here, when the process runs it might deactivate this input
688 // reader (if STDIN is hooked up to the inferior process) and
689 // reactivate it when the process stops which will deadlock.
690 //ScriptInterpreterPython::Locker locker(script_interpreter,
691 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
692 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000693 }
Chris Lattner24943d22010-06-08 16:52:24 +0000694 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000695
Caroline Tice4a348082011-05-02 20:41:46 +0000696 case eInputReaderAsynchronousOutputWritten:
697 break;
698
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000699 case eInputReaderInterrupt:
700 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
701 break;
702
703 case eInputReaderEndOfFile:
704 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
705 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000706
707 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000708 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000709 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000710 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000711 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000712 bytes_len);
713 if (bytes && bytes_len)
714 {
715 if ((int) bytes[0] == 4)
716 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
717 else
718 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
719 }
720 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000721 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000722 else
723 {
724 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000725 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000726 bytes,
727 bytes_len);
728 reader.SetIsDone (true);
729 }
730
Chris Lattner24943d22010-06-08 16:52:24 +0000731 break;
732
733 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000734 script_interpreter->LeaveSession ();
735
Chris Lattner24943d22010-06-08 16:52:24 +0000736 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000737 if (log)
738 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000739
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000740 script_interpreter->RestoreTerminalState ();
741
Caroline Tice2ade6112010-11-10 19:18:14 +0000742 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000743 break;
744 }
745
746 return bytes_len;
747}
748
749
750void
Greg Clayton238c0a12010-09-18 01:14:36 +0000751ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000752{
753 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
754
Caroline Tice0aa2e552011-01-14 00:29:16 +0000755 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000756
757 // At the moment, the only time the debugger does not have an input file handle is when this is called
758 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
759 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
760 // do it.
761
Greg Clayton58928562011-02-09 01:08:52 +0000762 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000763 return;
764
Greg Clayton63094e02010-06-23 01:19:29 +0000765 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000766 if (reader_sp)
767 {
768 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
769 this, // baton
770 eInputReaderGranularityLine, // token size, to pass to callback function
771 NULL, // end token
772 NULL, // prompt
773 true)); // echo input
774
775 if (error.Success())
776 {
Greg Clayton63094e02010-06-23 01:19:29 +0000777 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000778 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000779 }
780 }
781}
782
783bool
784ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000785 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000786 void *ret_value)
787{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000788
Enrico Granatafa1f6172011-10-24 17:22:21 +0000789 Locker locker(this,
790 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
791 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000792
Chris Lattner24943d22010-06-08 16:52:24 +0000793 PyObject *py_return = NULL;
794 PyObject *mainmod = PyImport_AddModule ("__main__");
795 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000796 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000797 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000798 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000799 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000800 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000801
Enrico Granata400105d2012-03-06 23:42:15 +0000802 locals = FindSessionDictionary(m_dictionary_name.c_str());
803
Caroline Tice0aa2e552011-01-14 00:29:16 +0000804 if (locals == NULL)
805 {
806 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
807 should_decrement_locals = true;
808 }
809
810 if (locals == NULL)
811 {
812 locals = globals;
813 should_decrement_locals = false;
814 }
815
816 py_error = PyErr_Occurred();
817 if (py_error != NULL)
818 PyErr_Clear();
819
Chris Lattner24943d22010-06-08 16:52:24 +0000820 if (in_string != NULL)
821 {
822 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
823 if (py_return == NULL)
824 {
825 py_error = PyErr_Occurred ();
826 if (py_error != NULL)
827 PyErr_Clear ();
828
829 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
830 }
831
Caroline Tice0aa2e552011-01-14 00:29:16 +0000832 if (locals != NULL
833 && should_decrement_locals)
834 Py_DECREF (locals);
835
Chris Lattner24943d22010-06-08 16:52:24 +0000836 if (py_return != NULL)
837 {
838 switch (return_type)
839 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000840 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000841 {
842 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000843 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000844 break;
845 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000846 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000847 {
848 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000849 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000850 break;
851 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000852 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000853 {
854 const char format[2] = "b";
855 success = PyArg_Parse (py_return, format, (bool *) ret_value);
856 break;
857 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000858 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000859 {
860 const char format[2] = "h";
861 success = PyArg_Parse (py_return, format, (short *) ret_value);
862 break;
863 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000864 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000865 {
866 const char format[2] = "H";
867 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
868 break;
869 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000870 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000871 {
872 const char format[2] = "i";
873 success = PyArg_Parse (py_return, format, (int *) ret_value);
874 break;
875 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000876 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000877 {
878 const char format[2] = "I";
879 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
880 break;
881 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000882 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000883 {
884 const char format[2] = "l";
885 success = PyArg_Parse (py_return, format, (long *) ret_value);
886 break;
887 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000888 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000889 {
890 const char format[2] = "k";
891 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
892 break;
893 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000894 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000895 {
896 const char format[2] = "L";
897 success = PyArg_Parse (py_return, format, (long long *) ret_value);
898 break;
899 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000900 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000901 {
902 const char format[2] = "K";
903 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
904 break;
905 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000906 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000907 {
908 const char format[2] = "f";
909 success = PyArg_Parse (py_return, format, (float *) ret_value);
910 break;
911 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000912 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000913 {
914 const char format[2] = "d";
915 success = PyArg_Parse (py_return, format, (double *) ret_value);
916 break;
917 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000918 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000919 {
920 const char format[2] = "c";
921 success = PyArg_Parse (py_return, format, (char *) ret_value);
922 break;
923 }
924 default:
925 {}
926 }
927 Py_DECREF (py_return);
928 if (success)
929 ret_success = true;
930 else
931 ret_success = false;
932 }
933 }
934
935 py_error = PyErr_Occurred();
936 if (py_error != NULL)
937 {
938 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
939 PyErr_Print ();
940 PyErr_Clear();
941 ret_success = false;
942 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000943
Chris Lattner24943d22010-06-08 16:52:24 +0000944 return ret_success;
945}
946
947bool
948ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
949{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000950
951
952 Locker locker(this,
953 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
954 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000955
Chris Lattner24943d22010-06-08 16:52:24 +0000956 bool success = false;
957 PyObject *py_return = NULL;
958 PyObject *mainmod = PyImport_AddModule ("__main__");
959 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000960 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000961 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000962 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000963
Enrico Granata400105d2012-03-06 23:42:15 +0000964 locals = FindSessionDictionary(m_dictionary_name.c_str());
965
Caroline Tice0aa2e552011-01-14 00:29:16 +0000966 if (locals == NULL)
967 {
968 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
969 should_decrement_locals = true;
970 }
971
972 if (locals == NULL)
973 {
974 locals = globals;
975 should_decrement_locals = false;
976 }
977
978 py_error = PyErr_Occurred();
979 if (py_error != NULL)
980 PyErr_Clear();
981
Chris Lattner24943d22010-06-08 16:52:24 +0000982 if (in_string != NULL)
983 {
984 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
985 if (compiled_node)
986 {
987 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
988 if (compiled_code)
989 {
990 py_return = PyEval_EvalCode (compiled_code, globals, locals);
991 if (py_return != NULL)
992 {
993 success = true;
994 Py_DECREF (py_return);
995 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000996 if (locals && should_decrement_locals)
997 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000998 }
999 }
1000 }
1001
1002 py_error = PyErr_Occurred ();
1003 if (py_error != NULL)
1004 {
1005 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1006 PyErr_Print ();
1007 PyErr_Clear();
1008 success = false;
1009 }
1010
1011 return success;
1012}
1013
1014static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1015
1016size_t
1017ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1018(
1019 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001020 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001021 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001022 const char *bytes,
1023 size_t bytes_len
1024)
1025{
Caroline Tice892fadd2011-06-16 16:27:19 +00001026 static StringList commands_in_progress;
1027
1028 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1029 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1030
Chris Lattner24943d22010-06-08 16:52:24 +00001031 switch (notification)
1032 {
1033 case eInputReaderActivate:
1034 {
1035 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +00001036 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +00001037 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001038 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001039 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +00001040 out_stream->Printf ("%s", reader.GetPrompt());
1041 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001042 }
1043 }
1044 break;
1045
1046 case eInputReaderDeactivate:
1047 break;
1048
1049 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001050 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001051 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001052 out_stream->Printf ("%s", reader.GetPrompt());
1053 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001054 }
Chris Lattner24943d22010-06-08 16:52:24 +00001055 break;
1056
Caroline Tice4a348082011-05-02 20:41:46 +00001057 case eInputReaderAsynchronousOutputWritten:
1058 break;
1059
Chris Lattner24943d22010-06-08 16:52:24 +00001060 case eInputReaderGotToken:
1061 {
1062 std::string temp_string (bytes, bytes_len);
1063 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001064 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001065 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001066 out_stream->Printf ("%s", reader.GetPrompt());
1067 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001068 }
Chris Lattner24943d22010-06-08 16:52:24 +00001069 }
1070 break;
1071
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001072 case eInputReaderEndOfFile:
1073 case eInputReaderInterrupt:
1074 // Control-c (SIGINT) & control-d both mean finish & exit.
1075 reader.SetIsDone(true);
1076
1077 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1078 if (notification == eInputReaderInterrupt)
1079 commands_in_progress.Clear();
1080
1081 // Fall through here...
1082
Chris Lattner24943d22010-06-08 16:52:24 +00001083 case eInputReaderDone:
1084 {
1085 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1086 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1087 data_ap->user_source.AppendList (commands_in_progress);
1088 if (data_ap.get())
1089 {
Greg Clayton63094e02010-06-23 01:19:29 +00001090 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001091 if (interpreter)
1092 {
1093 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1094 data_ap->script_source))
1095 {
Enrico Granata400105d2012-03-06 23:42:15 +00001096 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1097 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001098 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001099 else if (!batch_mode)
1100 {
1101 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1102 out_stream->Flush();
1103 }
Chris Lattner24943d22010-06-08 16:52:24 +00001104 }
1105 else
1106 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001107 if (!batch_mode)
1108 {
1109 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1110 out_stream->Flush();
1111 }
Chris Lattner24943d22010-06-08 16:52:24 +00001112 }
1113 }
1114 }
1115 break;
1116
1117 }
1118
1119 return bytes_len;
1120}
1121
1122void
Greg Clayton238c0a12010-09-18 01:14:36 +00001123ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001124 CommandReturnObject &result)
1125{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001126 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1127
Greg Clayton63094e02010-06-23 01:19:29 +00001128 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001129
1130 if (reader_sp)
1131 {
1132 Error err = reader_sp->Initialize (
1133 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1134 bp_options, // baton
1135 eInputReaderGranularityLine, // token size, for feeding data to callback function
1136 "DONE", // end token
1137 "> ", // prompt
1138 true); // echo input
1139
1140 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001141 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001142 else
1143 {
1144 result.AppendError (err.AsCString());
1145 result.SetStatus (eReturnStatusFailed);
1146 }
1147 }
1148 else
1149 {
1150 result.AppendError("out of memory");
1151 result.SetStatus (eReturnStatusFailed);
1152 }
1153}
1154
Johnny Chen3e0571b2010-09-11 00:23:59 +00001155// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001156void
Greg Clayton238c0a12010-09-18 01:14:36 +00001157ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001158 const char *oneliner)
1159{
1160 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1161
1162 // It's necessary to set both user_source and script_source to the oneliner.
1163 // The former is used to generate callback description (as in breakpoint command list)
1164 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001165
Johnny Chend1c2dca2010-09-10 18:21:10 +00001166 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001167
Caroline Tice5136f942010-09-27 21:35:15 +00001168 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1169 {
Enrico Granata400105d2012-03-06 23:42:15 +00001170 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1171 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Caroline Tice5136f942010-09-27 21:35:15 +00001172 }
1173
Johnny Chend1c2dca2010-09-10 18:21:10 +00001174 return;
1175}
1176
Chris Lattner24943d22010-06-08 16:52:24 +00001177bool
1178ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1179{
1180 // Convert StringList to one long, newline delimited, const char *.
Enrico Granata400105d2012-03-06 23:42:15 +00001181 std::string function_def_string(function_def.CopyList());
Chris Lattner24943d22010-06-08 16:52:24 +00001182
1183 return ExecuteMultipleLines (function_def_string.c_str());
1184}
1185
Enrico Granataf7a9b142011-07-15 02:26:42 +00001186bool
Enrico Granata400105d2012-03-06 23:42:15 +00001187ScriptInterpreterPython::GenerateFunction(const char *signature, const StringList &input)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001188{
1189 int num_lines = input.GetSize ();
1190 if (num_lines == 0)
1191 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001192
1193 if (!signature || *signature == 0)
1194 return false;
1195
Enrico Granataf7a9b142011-07-15 02:26:42 +00001196 StreamString sstr;
1197 StringList auto_generated_function;
Enrico Granata400105d2012-03-06 23:42:15 +00001198 auto_generated_function.AppendString (signature);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001199 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1200 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1201 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1202 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1203 // global dictionary.
1204
1205 // Wrap everything up inside the function, increasing the indentation.
1206
1207 for (int i = 0; i < num_lines; ++i)
1208 {
1209 sstr.Clear ();
1210 sstr.Printf (" %s", input.GetStringAtIndex (i));
1211 auto_generated_function.AppendString (sstr.GetData());
1212 }
1213 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1214 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1215 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1216 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1217
1218 // Verify that the results are valid Python.
1219
1220 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1221 return false;
1222
1223 return true;
1224
1225}
1226
Enrico Granataf7a9b142011-07-15 02:26:42 +00001227bool
Enrico Granata400105d2012-03-06 23:42:15 +00001228ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001229{
Enrico Granata400105d2012-03-06 23:42:15 +00001230 static uint32_t num_created_functions = 0;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001231 user_input.RemoveBlankLines ();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001232 StreamString sstr;
1233
1234 // Check to see if we have any data; if not, just return.
1235 if (user_input.GetSize() == 0)
1236 return false;
1237
1238 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1239 // ValueObject as parameter to the function.
1240
Enrico Granata400105d2012-03-06 23:42:15 +00001241 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 +00001242 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
Enrico Granataf7a9b142011-07-15 02:26:42 +00001243
Enrico Granata400105d2012-03-06 23:42:15 +00001244 if (!GenerateFunction(sstr.GetData(), user_input))
Enrico Granataf7a9b142011-07-15 02:26:42 +00001245 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001246
Enrico Granataf7a9b142011-07-15 02:26:42 +00001247 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001248 output.assign(auto_generated_function_name);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001249 return true;
1250}
1251
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001252bool
Enrico Granata400105d2012-03-06 23:42:15 +00001253ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, std::string &output)
Enrico Granatac2a28252011-08-16 16:49:25 +00001254{
Enrico Granata400105d2012-03-06 23:42:15 +00001255 static uint32_t num_created_functions = 0;
Enrico Granatac2a28252011-08-16 16:49:25 +00001256 user_input.RemoveBlankLines ();
Enrico Granatac2a28252011-08-16 16:49:25 +00001257 StreamString sstr;
1258
1259 // Check to see if we have any data; if not, just return.
1260 if (user_input.GetSize() == 0)
1261 return false;
1262
Enrico Granata400105d2012-03-06 23:42:15 +00001263 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_cmd_alias_func", num_created_functions));
1264
Enrico Granata271568f2011-09-09 01:41:30 +00001265 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001266
Enrico Granata400105d2012-03-06 23:42:15 +00001267 if (!GenerateFunction(sstr.GetData(),user_input))
Enrico Granatac2a28252011-08-16 16:49:25 +00001268 return false;
1269
1270 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001271 output.assign(auto_generated_function_name);
Enrico Granatac2a28252011-08-16 16:49:25 +00001272 return true;
1273}
1274
1275
1276bool
Enrico Granata400105d2012-03-06 23:42:15 +00001277ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, std::string &output, void* name_token)
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001278{
Enrico Granata400105d2012-03-06 23:42:15 +00001279 static uint32_t num_created_classes = 0;
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001280 user_input.RemoveBlankLines ();
1281 int num_lines = user_input.GetSize ();
1282 StreamString sstr;
1283
1284 // Check to see if we have any data; if not, just return.
1285 if (user_input.GetSize() == 0)
1286 return false;
1287
1288 // Wrap all user input into a Python class
1289
Enrico Granata400105d2012-03-06 23:42:15 +00001290 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 +00001291
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001292 StringList auto_generated_class;
1293
1294 // Create the function name & definition string.
1295
1296 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1297 auto_generated_class.AppendString (sstr.GetData());
1298
1299 // Wrap everything up inside the class, increasing the indentation.
1300
1301 for (int i = 0; i < num_lines; ++i)
1302 {
1303 sstr.Clear ();
1304 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1305 auto_generated_class.AppendString (sstr.GetData());
1306 }
1307
1308
1309 // Verify that the results are valid Python.
1310 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1311 // (TODO: rename that method to ExportDefinitionToInterpreter)
1312 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1313 return false;
1314
1315 // Store the name of the auto-generated class
1316
Enrico Granata400105d2012-03-06 23:42:15 +00001317 output.assign(auto_generated_class_name);
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001318 return true;
1319}
1320
Enrico Granata400105d2012-03-06 23:42:15 +00001321lldb::ScriptInterpreterObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001322ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1323 lldb::ValueObjectSP valobj)
1324{
1325 if (class_name.empty())
Enrico Granata400105d2012-03-06 23:42:15 +00001326 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001327
1328 if (!valobj.get())
Enrico Granata400105d2012-03-06 23:42:15 +00001329 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001330
Greg Claytonb4d7fc02012-02-17 07:49:44 +00001331 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1332 Target *target = exe_ctx.GetTargetPtr();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001333
1334 if (!target)
Enrico Granata400105d2012-03-06 23:42:15 +00001335 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001336
1337 Debugger &debugger = target->GetDebugger();
1338 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1339 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1340
1341 if (!script_interpreter)
Enrico Granata400105d2012-03-06 23:42:15 +00001342 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001343
1344 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001345
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001346 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001347 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001348 ForceDisableSyntheticChildren no_synthetics(target);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001349 ret_val = g_swig_synthetic_script (class_name,
1350 python_interpreter->m_dictionary_name.c_str(),
1351 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001352 }
1353
Enrico Granata400105d2012-03-06 23:42:15 +00001354 return MakeScriptObject(ret_val);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001355}
1356
Enrico Granataf7a9b142011-07-15 02:26:42 +00001357bool
Enrico Granata400105d2012-03-06 23:42:15 +00001358ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001359{
Enrico Granata16376ed2012-02-15 02:34:21 +00001360 StringList input;
1361 input.SplitIntoLines(oneliner, strlen(oneliner));
1362 return GenerateTypeScriptFunction(input, output, name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001363}
1364
Chris Lattner24943d22010-06-08 16:52:24 +00001365bool
Enrico Granata400105d2012-03-06 23:42:15 +00001366ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, std::string& output, void* name_token)
Enrico Granata16376ed2012-02-15 02:34:21 +00001367{
1368 StringList input;
1369 input.SplitIntoLines(oneliner, strlen(oneliner));
1370 return GenerateTypeSynthClass(input, output, name_token);
1371}
1372
1373
1374bool
Enrico Granata400105d2012-03-06 23:42:15 +00001375ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, std::string& output)
Chris Lattner24943d22010-06-08 16:52:24 +00001376{
Enrico Granata400105d2012-03-06 23:42:15 +00001377 static uint32_t num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001378 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001379 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001380
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001381 if (user_input.GetSize() == 0)
1382 return false;
1383
Enrico Granata400105d2012-03-06 23:42:15 +00001384 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_bp_callback_func_",num_created_functions));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001385 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001386
Enrico Granata400105d2012-03-06 23:42:15 +00001387 if (!GenerateFunction(sstr.GetData(), user_input))
Caroline Ticeb447e842010-09-21 19:25:28 +00001388 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001389
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001390 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001391 output.assign(auto_generated_function_name);
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001392 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001393}
1394
Enrico Granata1328b142012-02-29 03:28:49 +00001395bool
1396ScriptInterpreterPython::GetScriptedSummary (const char *python_function_name,
1397 lldb::ValueObjectSP valobj,
1398 lldb::ScriptInterpreterObjectSP& callee_wrapper_sp,
1399 std::string& retval)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001400{
1401
Enrico Granata1328b142012-02-29 03:28:49 +00001402 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001403
1404 if (!valobj.get())
Enrico Granata1328b142012-02-29 03:28:49 +00001405 {
1406 retval.assign("<no object>");
1407 return false;
1408 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001409
Enrico Granata1328b142012-02-29 03:28:49 +00001410 void* old_callee = (callee_wrapper_sp ? callee_wrapper_sp->GetObject() : NULL);
1411 void* new_callee = old_callee;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001412
Enrico Granata1328b142012-02-29 03:28:49 +00001413 bool ret_val;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001414 if (python_function_name
1415 && *python_function_name)
1416 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001417 {
Enrico Granata1328b142012-02-29 03:28:49 +00001418 Locker py_lock(this);
1419 {
1420 Timer scoped_timer ("g_swig_typescript_callback","g_swig_typescript_callback");
1421 ret_val = g_swig_typescript_callback (python_function_name,
1422 FindSessionDictionary(m_dictionary_name.c_str()),
1423 valobj,
1424 &new_callee,
1425 retval);
1426 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001427 }
1428 }
1429 else
Enrico Granata1328b142012-02-29 03:28:49 +00001430 {
1431 retval.assign("<no function name>");
1432 return false;
1433 }
1434
1435 if (new_callee && old_callee != new_callee)
1436 callee_wrapper_sp = MakeScriptObject(new_callee);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001437
1438 return ret_val;
1439
1440}
1441
Greg Clayton5144f382010-10-07 17:14:24 +00001442bool
1443ScriptInterpreterPython::BreakpointCallbackFunction
1444(
1445 void *baton,
1446 StoppointCallbackContext *context,
1447 user_id_t break_id,
1448 user_id_t break_loc_id
1449)
1450{
1451 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
Enrico Granata400105d2012-03-06 23:42:15 +00001452 const char *python_function_name = bp_option_data->script_source.c_str();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001453
1454 if (!context)
1455 return true;
1456
Greg Claytonf4124de2012-02-21 00:09:25 +00001457 ExecutionContext exe_ctx (context->exe_ctx_ref);
1458 Target *target = exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001459
1460 if (!target)
1461 return true;
1462
1463 Debugger &debugger = target->GetDebugger();
1464 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1465 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1466
1467 if (!script_interpreter)
1468 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001469
1470 if (python_function_name != NULL
1471 && python_function_name[0] != '\0')
1472 {
Greg Claytonf4124de2012-02-21 00:09:25 +00001473 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001474 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001475 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001476 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001477 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1478
1479 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001480 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001481 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001482 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001483 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001484 ret_val = g_swig_breakpoint_callback (python_function_name,
1485 python_interpreter->m_dictionary_name.c_str(),
1486 stop_frame_sp,
1487 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001488 }
1489 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001490 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001491 }
Greg Clayton5144f382010-10-07 17:14:24 +00001492 }
1493 // We currently always true so we stop in case anything goes wrong when
1494 // trying to call the script function
1495 return true;
1496}
Caroline Tice2ade6112010-11-10 19:18:14 +00001497
1498lldb::thread_result_t
1499ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1500{
1501 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1502
1503 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1504
1505 if (log)
1506 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1507
1508 char error_str[1024];
1509 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001510
Enrico Granatafa1f6172011-10-24 17:22:21 +00001511 Locker locker(script_interpreter,
1512 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1513 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1514
1515 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001516 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001517 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001518
Caroline Tice0aa2e552011-01-14 00:29:16 +00001519 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1520 PyRun_SimpleString (run_string.GetData());
1521 run_string.Clear ();
1522
1523 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1524 PyRun_SimpleString (run_string.GetData());
1525 run_string.Clear ();
1526
1527 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1528 PyRun_SimpleString (run_string.GetData());
1529 run_string.Clear ();
1530
1531 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1532 pty_slave_name);
1533 PyRun_SimpleString (run_string.GetData());
1534 run_string.Clear ();
1535
Johnny Chen8054ba32011-03-11 00:28:50 +00001536 // The following call drops into the embedded interpreter loop and stays there until the
1537 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001538
Caroline Ticece207c12011-03-11 00:21:55 +00001539 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001540 // 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 +00001541 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1542
1543 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1544 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1545 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1546 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1547 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1548 // hang (it's happened before).
1549
Caroline Tice9d352ce2011-03-07 23:24:28 +00001550 Py_BEGIN_ALLOW_THREADS
1551 PyGILState_STATE gstate = PyGILState_Ensure();
1552
Caroline Tice0aa2e552011-01-14 00:29:16 +00001553 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1554 PyRun_SimpleString (run_string.GetData());
1555 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001556
Caroline Tice9d352ce2011-03-07 23:24:28 +00001557 PyGILState_Release (gstate);
1558 Py_END_ALLOW_THREADS
1559
Caroline Tice0aa2e552011-01-14 00:29:16 +00001560 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1561 PyRun_SimpleString (run_string.GetData());
1562 run_string.Clear();
1563
1564 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1565 PyRun_SimpleString (run_string.GetData());
1566 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001567
Caroline Tice2ade6112010-11-10 19:18:14 +00001568 }
1569
1570 if (script_interpreter->m_embedded_thread_input_reader_sp)
1571 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1572
1573 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001574
Caroline Tice2ade6112010-11-10 19:18:14 +00001575 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1576 if (log)
1577 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1578
1579
Johnny Chen8054ba32011-03-11 00:28:50 +00001580 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001581 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001582 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1583 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1584 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001585
Caroline Tice2ade6112010-11-10 19:18:14 +00001586 return NULL;
1587}
1588
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001589uint32_t
Enrico Granata400105d2012-03-06 23:42:15 +00001590ScriptInterpreterPython::CalculateNumChildren (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001591{
Enrico Granata400105d2012-03-06 23:42:15 +00001592 if (!implementor_sp)
1593 return 0;
1594
1595 void* implementor = implementor_sp->GetObject();
1596
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001597 if (!implementor)
1598 return 0;
1599
1600 if (!g_swig_calc_children)
1601 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001602
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001603 uint32_t ret_val = 0;
1604
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001605 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001606 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001607 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001608 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001609 }
1610
1611 return ret_val;
1612}
1613
Enrico Granata91544802011-09-06 19:20:51 +00001614lldb::ValueObjectSP
Enrico Granata400105d2012-03-06 23:42:15 +00001615ScriptInterpreterPython::GetChildAtIndex (const lldb::ScriptInterpreterObjectSP& implementor_sp, uint32_t idx)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001616{
Enrico Granata400105d2012-03-06 23:42:15 +00001617 if (!implementor_sp)
1618 return lldb::ValueObjectSP();
1619
1620 void* implementor = implementor_sp->GetObject();
1621
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001622 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001623 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001624
Enrico Granata91544802011-09-06 19:20:51 +00001625 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1626 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001627
Enrico Granata91544802011-09-06 19:20:51 +00001628 void* child_ptr = NULL;
1629 lldb::SBValue* value_sb = NULL;
1630 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001631
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001632 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001633 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001634 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata91544802011-09-06 19:20:51 +00001635 child_ptr = g_swig_get_child_index (implementor,idx);
1636 if (child_ptr != NULL && child_ptr != Py_None)
1637 {
1638 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1639 if (value_sb == NULL)
1640 Py_XDECREF(child_ptr);
1641 else
1642 ret_val = value_sb->get_sp();
1643 }
1644 else
1645 {
1646 Py_XDECREF(child_ptr);
1647 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001648 }
1649
1650 return ret_val;
1651}
1652
1653int
Enrico Granata400105d2012-03-06 23:42:15 +00001654ScriptInterpreterPython::GetIndexOfChildWithName (const lldb::ScriptInterpreterObjectSP& implementor_sp, const char* child_name)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001655{
Enrico Granata400105d2012-03-06 23:42:15 +00001656 if (!implementor_sp)
1657 return UINT32_MAX;
1658
1659 void* implementor = implementor_sp->GetObject();
1660
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001661 if (!implementor)
1662 return UINT32_MAX;
1663
1664 if (!g_swig_get_index_child)
1665 return UINT32_MAX;
1666
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001667 int ret_val = UINT32_MAX;
1668
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001669 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001670 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001671 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001672 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001673 }
1674
1675 return ret_val;
1676}
1677
Enrico Granatacf09f882012-03-19 22:58:49 +00001678bool
Enrico Granata400105d2012-03-06 23:42:15 +00001679ScriptInterpreterPython::UpdateSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata979e20d2011-07-29 19:53:35 +00001680{
Enrico Granatacf09f882012-03-19 22:58:49 +00001681 bool ret_val = false;
1682
Enrico Granata400105d2012-03-06 23:42:15 +00001683 if (!implementor_sp)
Enrico Granatacf09f882012-03-19 22:58:49 +00001684 return ret_val;
Enrico Granata400105d2012-03-06 23:42:15 +00001685
1686 void* implementor = implementor_sp->GetObject();
1687
Enrico Granata979e20d2011-07-29 19:53:35 +00001688 if (!implementor)
Enrico Granatacf09f882012-03-19 22:58:49 +00001689 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001690
1691 if (!g_swig_update_provider)
Enrico Granatacf09f882012-03-19 22:58:49 +00001692 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001693
Enrico Granata979e20d2011-07-29 19:53:35 +00001694 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001695 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001696 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granatacf09f882012-03-19 22:58:49 +00001697 ret_val = g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001698 }
1699
Enrico Granatacf09f882012-03-19 22:58:49 +00001700 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001701}
1702
Enrico Granatac2a28252011-08-16 16:49:25 +00001703bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001704ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00001705 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00001706 lldb_private::Error& error)
1707{
1708 if (!pathname || !pathname[0])
1709 {
1710 error.SetErrorString("invalid pathname");
1711 return false;
1712 }
1713
1714 if (!g_swig_call_module_init)
1715 {
1716 error.SetErrorString("internal helper function missing");
1717 return false;
1718 }
1719
Greg Clayton13d24fb2012-01-29 20:56:30 +00001720 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granatafa1f6172011-10-24 17:22:21 +00001721
Enrico Granata59df36f2011-10-17 21:45:27 +00001722 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001723 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00001724
1725 FileSpec target_file(pathname, true);
1726
1727 // TODO: would we want to reject any other value?
1728 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1729 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1730 {
1731 error.SetErrorString("invalid pathname");
1732 return false;
1733 }
1734
1735 const char* directory = target_file.GetDirectory().GetCString();
1736 std::string basename(target_file.GetFilename().GetCString());
1737
1738 // now make sure that Python has "directory" in the search path
1739 StreamString command_stream;
1740 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1741 directory,
1742 directory);
Enrico Granatafa1f6172011-10-24 17:22:21 +00001743 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData());
Enrico Granata59df36f2011-10-17 21:45:27 +00001744 if (!syspath_retval)
1745 {
1746 error.SetErrorString("Python sys.path handling failed");
1747 return false;
1748 }
1749
1750 // strip .py or .pyc extension
1751 ConstString extension = target_file.GetFileNameExtension();
1752 if (::strcmp(extension.GetCString(), "py") == 0)
1753 basename.resize(basename.length()-3);
1754 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1755 basename.resize(basename.length()-4);
1756
1757 // check if the module is already import-ed
1758 command_stream.Clear();
1759 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1760 int refcount = 0;
1761 // this call will fail if the module does not exist (because the parameter to it is not a string
1762 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00001763 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
1764 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0);
1765 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00001766 {
1767 error.SetErrorString("module already imported");
1768 return false;
1769 }
1770
1771 // now actually do the import
1772 command_stream.Clear();
1773 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafa1f6172011-10-24 17:22:21 +00001774 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL);
Enrico Granata59df36f2011-10-17 21:45:27 +00001775 if (!import_retval)
1776 {
1777 error.SetErrorString("Python import statement failed");
1778 return false;
1779 }
1780
Enrico Granata16376ed2012-02-15 02:34:21 +00001781 // call __lldb_init_module(debugger,dict)
Enrico Granata59df36f2011-10-17 21:45:27 +00001782 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001783 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001784 debugger_sp))
1785 {
Enrico Granata16376ed2012-02-15 02:34:21 +00001786 error.SetErrorString("calling __lldb_init_module failed");
Enrico Granata59df36f2011-10-17 21:45:27 +00001787 return false;
1788 }
1789 return true;
1790 }
1791}
1792
Enrico Granata1328b142012-02-29 03:28:49 +00001793lldb::ScriptInterpreterObjectSP
1794ScriptInterpreterPython::MakeScriptObject (void* object)
1795{
1796 return lldb::ScriptInterpreterObjectSP(new ScriptInterpreterPythonObject(object));
1797}
1798
Enrico Granata6010ace2011-11-07 22:57:04 +00001799ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
1800 ScriptedCommandSynchronicity synchro) :
1801 m_debugger_sp(debugger_sp),
1802 m_synch_wanted(synchro),
1803 m_old_asynch(debugger_sp->GetAsyncExecution())
1804{
1805 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
1806 m_debugger_sp->SetAsyncExecution(false);
1807 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
1808 m_debugger_sp->SetAsyncExecution(true);
1809}
1810
1811ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
1812{
1813 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
1814 m_debugger_sp->SetAsyncExecution(m_old_asynch);
1815}
1816
Enrico Granata59df36f2011-10-17 21:45:27 +00001817bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001818ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1819 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00001820 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001821 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001822 Error& error)
1823{
1824 if (!impl_function)
1825 {
1826 error.SetErrorString("no function to execute");
1827 return false;
1828 }
1829
1830 if (!g_swig_call_command)
1831 {
1832 error.SetErrorString("no helper function to run scripted commands");
1833 return false;
1834 }
1835
Greg Clayton13d24fb2012-01-29 20:56:30 +00001836 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata6010ace2011-11-07 22:57:04 +00001837
1838 if (!debugger_sp.get())
1839 {
1840 error.SetErrorString("invalid Debugger pointer");
1841 return false;
1842 }
Enrico Granatac2a28252011-08-16 16:49:25 +00001843
1844 bool ret_val;
1845
1846 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00001847
Enrico Granatac2a28252011-08-16 16:49:25 +00001848 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001849 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00001850 SynchronicityHandler synch_handler(debugger_sp,
1851 synchronicity);
1852
Enrico Granatac2a28252011-08-16 16:49:25 +00001853 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001854 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00001855 debugger_sp,
1856 args,
1857 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001858 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001859 }
Enrico Granata6010ace2011-11-07 22:57:04 +00001860
Enrico Granatac2a28252011-08-16 16:49:25 +00001861 if (!ret_val)
1862 error.SetErrorString(err_msg.c_str());
1863 else
1864 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00001865
Enrico Granatac2a28252011-08-16 16:49:25 +00001866 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00001867}
1868
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001869// in Python, a special attribute __doc__ contains the docstring
1870// for an object (function, method, class, ...) if any is defined
1871// Otherwise, the attribute's value is None
1872std::string
1873ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1874{
1875 std::string command(item);
1876 command += ".__doc__";
1877
1878 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1879
1880 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001881 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001882 &result_ptr) && result_ptr)
1883 {
1884 return std::string(result_ptr);
1885 }
1886 else
1887 return std::string("");
1888}
Caroline Tice2ade6112010-11-10 19:18:14 +00001889
Caroline Tice0aa2e552011-01-14 00:29:16 +00001890void
Enrico Granata1328b142012-02-29 03:28:49 +00001891ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback)
Greg Claytone86cbb92011-03-22 01:14:58 +00001892{
1893 g_swig_init_callback = python_swig_init_callback;
Enrico Granata1328b142012-02-29 03:28:49 +00001894 g_swig_breakpoint_callback = LLDBSwigPythonBreakpointCallbackFunction;
1895 g_swig_typescript_callback = LLDBSwigPythonCallTypeScript;
1896 g_swig_synthetic_script = LLDBSwigPythonCreateSyntheticProvider;
1897 g_swig_calc_children = LLDBSwigPython_CalculateNumChildren;
1898 g_swig_get_child_index = LLDBSwigPython_GetChildAtIndex;
1899 g_swig_get_index_child = LLDBSwigPython_GetIndexOfChildWithName;
1900 g_swig_cast_to_sbvalue = LLDBSWIGPython_CastPyObjectToSBValue;
1901 g_swig_update_provider = LLDBSwigPython_UpdateSynthProviderInstance;
1902 g_swig_call_command = LLDBSwigPythonCallCommand;
1903 g_swig_call_module_init = LLDBSwigPythonCallModuleInit;
Greg Claytone86cbb92011-03-22 01:14:58 +00001904}
1905
1906void
1907ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001908{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001909 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1910
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001911 // Python will muck with STDIN terminal state, so save off any current TTY
1912 // settings so we can restore them.
1913 TerminalState stdin_tty_state;
1914 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001915
Caroline Tice9d352ce2011-03-07 23:24:28 +00001916 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001917 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001918
Greg Claytone86cbb92011-03-22 01:14:58 +00001919 // Initialize SWIG after setting up python
1920 assert (g_swig_init_callback != NULL);
1921 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001922
1923 // Update the path python uses to search for modules to include the current directory.
1924
Caroline Ticed4d92832011-06-13 21:33:00 +00001925 PyRun_SimpleString ("import sys");
1926 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001927
1928 // Find the module that owns this code and use that path we get to
1929 // set the sys.path appropriately.
1930
1931 FileSpec file_spec;
1932 char python_dir_path[PATH_MAX];
1933 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1934 {
1935 std::string python_path("sys.path.insert(0,\"");
1936 size_t orig_len = python_path.length();
1937 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1938 {
1939 python_path.append (python_dir_path);
1940 python_path.append ("\")");
1941 PyRun_SimpleString (python_path.c_str());
1942 python_path.resize (orig_len);
1943 }
1944
1945 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1946 {
1947 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1948 {
1949 python_path.append (python_dir_path);
1950 python_path.append ("\")");
1951 PyRun_SimpleString (python_path.c_str());
1952 python_path.resize (orig_len);
1953 }
1954 }
1955 }
1956
Jim Ingham4dfa5112011-08-22 19:10:09 +00001957 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001958
Caroline Ticed4d92832011-06-13 21:33:00 +00001959 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001960
Caroline Ticed4d92832011-06-13 21:33:00 +00001961 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1962 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00001963 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001964
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001965 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001966}
1967
Greg Claytone86cbb92011-03-22 01:14:58 +00001968//void
1969//ScriptInterpreterPython::Terminate ()
1970//{
1971// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1972// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1973// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1974// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1975// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1976// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1977// // within Py_Finalize, which results in a seg fault.
1978// //
1979// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1980// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1981// // process exits).
1982// //
1983//// Py_Finalize ();
1984//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00001985
1986#endif // #ifdef LLDB_DISABLE_PYTHON