blob: 1865a3d3cc62470bc681b9f86706fc70406c0c17 [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
Greg Clayton4e651b12012-04-25 00:58:03 +0000299 run_string.Printf ("run_one_line (%s, 'import copy, os, re, sys, uuid, lldb')", 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();
Greg Clayton4e651b12012-04-25 00:58:03 +0000305 //run_string.Printf ("run_one_line (%s, 'from lldb.formatters import *; from lldb.formatters.objc import *; from lldb.formatters.cpp import *')", m_dictionary_name.c_str());
Enrico Granata0d235d52012-04-25 01:39:27 +0000306 run_string.Printf ("run_one_line (%s, 'import lldb.formatters.cache, lldb.formatters.Logger, lldb.formatters.attrib_fromdict, lldb.formatters.metrics')", m_dictionary_name.c_str());
Enrico Granata8f84cfb2012-02-23 23:10:03 +0000307 PyRun_SimpleString (run_string.GetData());
Greg Claytonb302dff2012-02-01 08:09:32 +0000308
Caroline Tice0aa2e552011-01-14 00:29:16 +0000309 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000310
Caroline Tice0aa2e552011-01-14 00:29:16 +0000311 if (new_count > old_count)
312 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000313
Caroline Tice0aa2e552011-01-14 00:29:16 +0000314 run_string.Clear();
Greg Clayton444e35b2011-10-19 18:09:39 +0000315 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000316 interpreter.GetDebugger().GetID());
317 PyRun_SimpleString (run_string.GetData());
318
319 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000320 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000321 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000322 }
Chris Lattner24943d22010-06-08 16:52:24 +0000323}
324
325ScriptInterpreterPython::~ScriptInterpreterPython ()
326{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000327 Debugger &debugger = GetCommandInterpreter().GetDebugger();
328
329 if (m_embedded_thread_input_reader_sp.get() != NULL)
330 {
331 m_embedded_thread_input_reader_sp->SetIsDone (true);
332 m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000333 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
334 m_embedded_thread_input_reader_sp.reset();
335 debugger.PopInputReader (reader_sp);
336 }
337
338 if (m_new_sysout)
339 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000340 Locker locker(this,
341 ScriptInterpreterPython::Locker::AcquireLock,
342 ScriptInterpreterPython::Locker::FreeLock);
343 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000344 }
Chris Lattner24943d22010-06-08 16:52:24 +0000345}
346
Caroline Tice0aa2e552011-01-14 00:29:16 +0000347void
348ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
349{
350 if (fh == NULL)
351 return;
352
353 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000354
Johnny Chenc65046d2012-03-08 20:53:04 +0000355 Locker locker(this,
356 ScriptInterpreterPython::Locker::AcquireLock,
357 ScriptInterpreterPython::Locker::FreeAcquiredLock);
358
Enrico Granata91544802011-09-06 19:20:51 +0000359 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000360}
361
362void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000363ScriptInterpreterPython::SaveTerminalState (int fd)
364{
365 // Python mucks with the terminal state of STDIN. If we can possibly avoid
366 // this by setting the file handles up correctly prior to entering the
367 // interpreter we should. For now we save and restore the terminal state
368 // on the input file handle.
369 m_terminal_state.Save (fd, false);
370}
371
372void
373ScriptInterpreterPython::RestoreTerminalState ()
374{
375 // Python mucks with the terminal state of STDIN. If we can possibly avoid
376 // this by setting the file handles up correctly prior to entering the
377 // interpreter we should. For now we save and restore the terminal state
378 // on the input file handle.
379 m_terminal_state.Restore();
380}
381
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000382void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000383ScriptInterpreterPython::LeaveSession ()
384{
Enrico Granata7aa754c2012-04-04 17:31:29 +0000385 // checking that we have a valid thread state - since we use our own threading and locking
386 // in some (rare) cases during cleanup Python may end up believing we have no thread state
387 // and PyImport_AddModule will crash if that is the case - since that seems to only happen
388 // when destroying the SBDebugger, we can make do without clearing up stdout and stderr
389 if (PyThreadState_Get())
Johnny Chen41641f92012-02-29 01:52:13 +0000390 {
Enrico Granata7aa754c2012-04-04 17:31:29 +0000391 PyObject *sysmod = PyImport_AddModule ("sys");
392 PyObject *sysdict = PyModule_GetDict (sysmod);
393
394 if (m_new_sysout && sysmod && sysdict)
395 {
396 if (m_old_sysout)
397 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_old_sysout);
398 if (m_old_syserr)
399 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_old_syserr);
400 }
Johnny Chen41641f92012-02-29 01:52:13 +0000401 }
402
Caroline Tice0aa2e552011-01-14 00:29:16 +0000403 m_session_is_active = false;
404}
405
406void
407ScriptInterpreterPython::EnterSession ()
408{
409 // If we have already entered the session, without having officially 'left' it, then there is no need to
410 // 'enter' it again.
411
412 if (m_session_is_active)
413 return;
414
415 m_session_is_active = true;
416
Caroline Tice202f6b82011-01-17 21:55:19 +0000417 StreamString run_string;
418
Greg Clayton2fecc452012-01-28 02:11:02 +0000419 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %llu", m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
420 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)", GetCommandInterpreter().GetDebugger().GetID());
421 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
422 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
423 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
424 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
425 // Make sure STDIN is closed since when we run this as an embedded
426 // interpreter we don't want someone to call "line = sys.stdin.readline()"
427 // and lock up. We don't have multiple windows and when the interpreter is
428 // embedded we don't know we should be feeding input to the embedded
429 // interpreter or to the python sys.stdin. We also don't want to let python
430 // play with the real stdin from this process, so we need to close it...
Greg Clayton3eeaf6e2012-02-03 01:30:30 +0000431 //run_string.PutCString ("; sys.stdin.close()");
Greg Clayton2fecc452012-01-28 02:11:02 +0000432 run_string.PutCString ("')");
Caroline Tice0aa2e552011-01-14 00:29:16 +0000433
Caroline Tice6af65cb2011-05-03 21:21:50 +0000434 PyRun_SimpleString (run_string.GetData());
435 run_string.Clear();
Johnny Chen41641f92012-02-29 01:52:13 +0000436
Caroline Tice0aa2e552011-01-14 00:29:16 +0000437 PyObject *sysmod = PyImport_AddModule ("sys");
438 PyObject *sysdict = PyModule_GetDict (sysmod);
Johnny Chen41641f92012-02-29 01:52:13 +0000439
Greg Clayton2fecc452012-01-28 02:11:02 +0000440 if (m_new_sysout && sysmod && sysdict)
441 {
Johnny Chen41641f92012-02-29 01:52:13 +0000442 m_old_sysout = PyDict_GetItemString(sysdict, "stdout");
443 m_old_syserr = PyDict_GetItemString(sysdict, "stderr");
Johnny Chenc65046d2012-03-08 20:53:04 +0000444 if (m_new_sysout)
445 {
446 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
447 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
448 }
Greg Clayton2fecc452012-01-28 02:11:02 +0000449 }
Johnny Chen41641f92012-02-29 01:52:13 +0000450
Caroline Tice0aa2e552011-01-14 00:29:16 +0000451 if (PyErr_Occurred())
452 PyErr_Clear ();
Greg Clayton2fecc452012-01-28 02:11:02 +0000453}
Caroline Tice0aa2e552011-01-14 00:29:16 +0000454
Enrico Granata400105d2012-03-06 23:42:15 +0000455static PyObject*
456FindSessionDictionary (const char* dict_name)
457{
458 static std::map<ConstString,PyObject*> g_dict_map;
459
460 ConstString dict(dict_name);
461
462 std::map<ConstString,PyObject*>::iterator iter = g_dict_map.find(dict);
463
464 if (iter != g_dict_map.end())
465 return iter->second;
466
467 PyObject *main_mod = PyImport_AddModule ("__main__");
468 if (main_mod != NULL)
469 {
470 PyObject *main_dict = PyModule_GetDict (main_mod);
471 if ((main_dict != NULL)
472 && PyDict_Check (main_dict))
473 {
474 // Go through the main dictionary looking for the correct python script interpreter dictionary
475 PyObject *key, *value;
476 Py_ssize_t pos = 0;
477
478 while (PyDict_Next (main_dict, &pos, &key, &value))
479 {
480 // We have stolen references to the key and value objects in the dictionary; we need to increment
481 // them now so that Python's garbage collector doesn't collect them out from under us.
482 Py_INCREF (key);
483 Py_INCREF (value);
484 if (strcmp (PyString_AsString (key), dict_name) == 0)
485 {
486 g_dict_map[dict] = value;
487 return value;
488 }
489 }
490 }
491 }
492 return NULL;
493}
494
495static std::string
496GenerateUniqueName (const char* base_name_wanted,
497 uint32_t& functions_counter,
498 void* name_token = NULL)
499{
500 StreamString sstr;
501
502 if (!base_name_wanted)
503 return std::string();
504
505 if (!name_token)
506 sstr.Printf ("%s_%d", base_name_wanted, functions_counter++);
507 else
508 sstr.Printf ("%s_%p", base_name_wanted, name_token);
509
510 return sstr.GetString();
511}
512
Johnny Chen60dde642010-07-30 22:33:14 +0000513bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000514ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000515{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000516 if (!m_valid_session)
517 return false;
518
Caroline Tice4a461da2011-01-14 21:09:29 +0000519 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
520 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
521 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
522 // method to pass the command string directly down to Python.
523
Enrico Granatafa1f6172011-10-24 17:22:21 +0000524 Locker locker(this,
525 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
526 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000527
528 bool success = false;
529
Greg Clayton63094e02010-06-23 01:19:29 +0000530 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000531 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000532 // Find the correct script interpreter dictionary in the main module.
Enrico Granata400105d2012-03-06 23:42:15 +0000533 PyObject *script_interpreter_dict = FindSessionDictionary(m_dictionary_name.c_str());
534 if (script_interpreter_dict != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000535 {
Enrico Granata400105d2012-03-06 23:42:15 +0000536 PyObject *pfunc = (PyObject*)m_run_one_line;
Greg Clayton6f2f0ab2012-04-25 01:49:50 +0000537 PyObject *pmod = PyImport_AddModule ("lldb.embedded_interpreter");
Enrico Granata400105d2012-03-06 23:42:15 +0000538 if (pmod != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000539 {
Enrico Granata400105d2012-03-06 23:42:15 +0000540 PyObject *pmod_dict = PyModule_GetDict (pmod);
541 if ((pmod_dict != NULL)
542 && PyDict_Check (pmod_dict))
Caroline Tice4a461da2011-01-14 21:09:29 +0000543 {
Enrico Granata400105d2012-03-06 23:42:15 +0000544 if (!pfunc)
Caroline Tice4a461da2011-01-14 21:09:29 +0000545 {
546 PyObject *key, *value;
547 Py_ssize_t pos = 0;
548
549 while (PyDict_Next (pmod_dict, &pos, &key, &value))
550 {
551 Py_INCREF (key);
552 Py_INCREF (value);
553 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
554 {
555 pfunc = value;
556 break;
557 }
558 }
Enrico Granata400105d2012-03-06 23:42:15 +0000559 m_run_one_line = pfunc;
560 }
561
562 if (pfunc && PyCallable_Check (pfunc))
563 {
564 PyObject *pargs = Py_BuildValue("(Os)",script_interpreter_dict,command);
565 if (pargs != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000566 {
Enrico Granata400105d2012-03-06 23:42:15 +0000567 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
568 Py_DECREF (pargs);
569 if (pvalue != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000570 {
Enrico Granata400105d2012-03-06 23:42:15 +0000571 Py_DECREF (pvalue);
572 success = true;
573 }
574 else if (PyErr_Occurred ())
575 {
576 PyErr_Print();
577 PyErr_Clear();
Caroline Tice4a461da2011-01-14 21:09:29 +0000578 }
579 }
580 }
581 }
Caroline Tice4a461da2011-01-14 21:09:29 +0000582 }
Enrico Granata400105d2012-03-06 23:42:15 +0000583 Py_INCREF (script_interpreter_dict);
Caroline Tice4a461da2011-01-14 21:09:29 +0000584 }
Greg Clayton63094e02010-06-23 01:19:29 +0000585
Caroline Tice4a461da2011-01-14 21:09:29 +0000586 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000587 return true;
588
589 // The one-liner failed. Append the error message.
590 if (result)
591 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
592 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000593 }
Johnny Chen60dde642010-07-30 22:33:14 +0000594
595 if (result)
596 result->AppendError ("empty command passed to python\n");
597 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000598}
599
Chris Lattner24943d22010-06-08 16:52:24 +0000600size_t
601ScriptInterpreterPython::InputReaderCallback
602(
603 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000604 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000605 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000606 const char *bytes,
607 size_t bytes_len
608)
609{
Caroline Tice2ade6112010-11-10 19:18:14 +0000610 lldb::thread_t embedded_interpreter_thread;
611 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
612
Chris Lattner24943d22010-06-08 16:52:24 +0000613 if (baton == NULL)
614 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000615
616 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000617
Caroline Tice0aa2e552011-01-14 00:29:16 +0000618 if (script_interpreter->m_script_lang != eScriptLanguagePython)
619 return 0;
620
Caroline Tice892fadd2011-06-16 16:27:19 +0000621 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
622 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
623
Chris Lattner24943d22010-06-08 16:52:24 +0000624 switch (notification)
625 {
626 case eInputReaderActivate:
627 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000628 if (!batch_mode)
629 {
630 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
631 out_stream->Flush();
632 }
Greg Clayton58928562011-02-09 01:08:52 +0000633
Chris Lattner24943d22010-06-08 16:52:24 +0000634 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000635 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
636 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000637 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000638
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000639 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000640
Caroline Tice202f6b82011-01-17 21:55:19 +0000641 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000642 ScriptInterpreterPython::Locker locker(script_interpreter,
643 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
644 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000645 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000646
Caroline Tice2ade6112010-11-10 19:18:14 +0000647 char error_str[1024];
648 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
649 sizeof(error_str)))
650 {
651 if (log)
652 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
653 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
654 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
655 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
656 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000657 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000658 {
659 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000660 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000661 Error detach_error;
662 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
663 }
664 else
665 {
666 if (log)
667 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
668 reader.SetIsDone (true);
669 }
670 }
671 else
672 {
673 if (log)
674 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
675 reader.SetIsDone (true);
676 }
Chris Lattner24943d22010-06-08 16:52:24 +0000677 }
678 break;
679
680 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000681 // When another input reader is pushed, don't leave the session...
682 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000683 break;
684
685 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000686 {
Greg Claytona1cec242012-01-06 00:47:38 +0000687 // Don't try and acquire the interpreter lock here because code like
688 // this:
689 //
690 // (lldb) script
691 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
692 //
693 // This will cause the process to run. The interpreter lock is taken
694 // by the input reader for the "script" command. If we try and acquire
695 // the lock here, when the process runs it might deactivate this input
696 // reader (if STDIN is hooked up to the inferior process) and
697 // reactivate it when the process stops which will deadlock.
698 //ScriptInterpreterPython::Locker locker(script_interpreter,
699 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
700 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000701 }
Chris Lattner24943d22010-06-08 16:52:24 +0000702 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000703
Caroline Tice4a348082011-05-02 20:41:46 +0000704 case eInputReaderAsynchronousOutputWritten:
705 break;
706
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000707 case eInputReaderInterrupt:
708 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
709 break;
710
711 case eInputReaderEndOfFile:
712 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
713 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000714
715 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000716 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000717 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000718 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000719 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000720 bytes_len);
721 if (bytes && bytes_len)
722 {
723 if ((int) bytes[0] == 4)
724 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
725 else
726 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
727 }
728 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000729 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000730 else
731 {
732 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000733 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000734 bytes,
735 bytes_len);
736 reader.SetIsDone (true);
737 }
738
Chris Lattner24943d22010-06-08 16:52:24 +0000739 break;
740
741 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000742 script_interpreter->LeaveSession ();
743
Chris Lattner24943d22010-06-08 16:52:24 +0000744 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000745 if (log)
746 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000747
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000748 script_interpreter->RestoreTerminalState ();
749
Caroline Tice2ade6112010-11-10 19:18:14 +0000750 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000751 break;
752 }
753
754 return bytes_len;
755}
756
757
758void
Greg Clayton238c0a12010-09-18 01:14:36 +0000759ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000760{
761 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
762
Caroline Tice0aa2e552011-01-14 00:29:16 +0000763 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000764
765 // At the moment, the only time the debugger does not have an input file handle is when this is called
766 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
767 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
768 // do it.
769
Greg Clayton58928562011-02-09 01:08:52 +0000770 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000771 return;
772
Greg Clayton63094e02010-06-23 01:19:29 +0000773 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000774 if (reader_sp)
775 {
776 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
777 this, // baton
778 eInputReaderGranularityLine, // token size, to pass to callback function
779 NULL, // end token
780 NULL, // prompt
781 true)); // echo input
782
783 if (error.Success())
784 {
Greg Clayton63094e02010-06-23 01:19:29 +0000785 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000786 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000787 }
788 }
789}
790
791bool
792ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000793 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000794 void *ret_value)
795{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000796
Enrico Granatafa1f6172011-10-24 17:22:21 +0000797 Locker locker(this,
798 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
799 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000800
Chris Lattner24943d22010-06-08 16:52:24 +0000801 PyObject *py_return = NULL;
802 PyObject *mainmod = PyImport_AddModule ("__main__");
803 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000804 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000805 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000806 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000807 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000808 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000809
Enrico Granata400105d2012-03-06 23:42:15 +0000810 locals = FindSessionDictionary(m_dictionary_name.c_str());
811
Caroline Tice0aa2e552011-01-14 00:29:16 +0000812 if (locals == NULL)
813 {
814 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
815 should_decrement_locals = true;
816 }
817
818 if (locals == NULL)
819 {
820 locals = globals;
821 should_decrement_locals = false;
822 }
823
824 py_error = PyErr_Occurred();
825 if (py_error != NULL)
826 PyErr_Clear();
827
Chris Lattner24943d22010-06-08 16:52:24 +0000828 if (in_string != NULL)
829 {
830 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
831 if (py_return == NULL)
832 {
833 py_error = PyErr_Occurred ();
834 if (py_error != NULL)
835 PyErr_Clear ();
836
837 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
838 }
839
Caroline Tice0aa2e552011-01-14 00:29:16 +0000840 if (locals != NULL
841 && should_decrement_locals)
842 Py_DECREF (locals);
843
Chris Lattner24943d22010-06-08 16:52:24 +0000844 if (py_return != NULL)
845 {
846 switch (return_type)
847 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000848 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000849 {
850 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000851 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000852 break;
853 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000854 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000855 {
856 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000857 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000858 break;
859 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000860 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000861 {
862 const char format[2] = "b";
863 success = PyArg_Parse (py_return, format, (bool *) ret_value);
864 break;
865 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000866 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000867 {
868 const char format[2] = "h";
869 success = PyArg_Parse (py_return, format, (short *) ret_value);
870 break;
871 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000872 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000873 {
874 const char format[2] = "H";
875 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
876 break;
877 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000878 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000879 {
880 const char format[2] = "i";
881 success = PyArg_Parse (py_return, format, (int *) ret_value);
882 break;
883 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000884 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000885 {
886 const char format[2] = "I";
887 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
888 break;
889 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000890 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000891 {
892 const char format[2] = "l";
893 success = PyArg_Parse (py_return, format, (long *) ret_value);
894 break;
895 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000896 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000897 {
898 const char format[2] = "k";
899 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
900 break;
901 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000902 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000903 {
904 const char format[2] = "L";
905 success = PyArg_Parse (py_return, format, (long long *) ret_value);
906 break;
907 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000908 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000909 {
910 const char format[2] = "K";
911 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
912 break;
913 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000914 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000915 {
916 const char format[2] = "f";
917 success = PyArg_Parse (py_return, format, (float *) ret_value);
918 break;
919 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000920 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000921 {
922 const char format[2] = "d";
923 success = PyArg_Parse (py_return, format, (double *) ret_value);
924 break;
925 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000926 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000927 {
928 const char format[2] = "c";
929 success = PyArg_Parse (py_return, format, (char *) ret_value);
930 break;
931 }
932 default:
933 {}
934 }
935 Py_DECREF (py_return);
936 if (success)
937 ret_success = true;
938 else
939 ret_success = false;
940 }
941 }
942
943 py_error = PyErr_Occurred();
944 if (py_error != NULL)
945 {
946 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
947 PyErr_Print ();
948 PyErr_Clear();
949 ret_success = false;
950 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000951
Chris Lattner24943d22010-06-08 16:52:24 +0000952 return ret_success;
953}
954
955bool
956ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
957{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000958
959
960 Locker locker(this,
961 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
962 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000963
Chris Lattner24943d22010-06-08 16:52:24 +0000964 bool success = false;
965 PyObject *py_return = NULL;
966 PyObject *mainmod = PyImport_AddModule ("__main__");
967 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000968 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000969 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000970 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000971
Enrico Granata400105d2012-03-06 23:42:15 +0000972 locals = FindSessionDictionary(m_dictionary_name.c_str());
973
Caroline Tice0aa2e552011-01-14 00:29:16 +0000974 if (locals == NULL)
975 {
976 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
977 should_decrement_locals = true;
978 }
979
980 if (locals == NULL)
981 {
982 locals = globals;
983 should_decrement_locals = false;
984 }
985
986 py_error = PyErr_Occurred();
987 if (py_error != NULL)
988 PyErr_Clear();
989
Chris Lattner24943d22010-06-08 16:52:24 +0000990 if (in_string != NULL)
991 {
992 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
993 if (compiled_node)
994 {
995 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
996 if (compiled_code)
997 {
998 py_return = PyEval_EvalCode (compiled_code, globals, locals);
999 if (py_return != NULL)
1000 {
1001 success = true;
1002 Py_DECREF (py_return);
1003 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001004 if (locals && should_decrement_locals)
1005 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +00001006 }
1007 }
1008 }
1009
1010 py_error = PyErr_Occurred ();
1011 if (py_error != NULL)
1012 {
1013 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1014 PyErr_Print ();
1015 PyErr_Clear();
1016 success = false;
1017 }
1018
1019 return success;
1020}
1021
1022static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1023
1024size_t
1025ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1026(
1027 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001028 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001029 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001030 const char *bytes,
1031 size_t bytes_len
1032)
1033{
Caroline Tice892fadd2011-06-16 16:27:19 +00001034 static StringList commands_in_progress;
1035
1036 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1037 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1038
Chris Lattner24943d22010-06-08 16:52:24 +00001039 switch (notification)
1040 {
1041 case eInputReaderActivate:
1042 {
1043 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +00001044 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +00001045 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001046 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001047 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +00001048 out_stream->Printf ("%s", reader.GetPrompt());
1049 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001050 }
1051 }
1052 break;
1053
1054 case eInputReaderDeactivate:
1055 break;
1056
1057 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001058 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001059 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001060 out_stream->Printf ("%s", reader.GetPrompt());
1061 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001062 }
Chris Lattner24943d22010-06-08 16:52:24 +00001063 break;
1064
Caroline Tice4a348082011-05-02 20:41:46 +00001065 case eInputReaderAsynchronousOutputWritten:
1066 break;
1067
Chris Lattner24943d22010-06-08 16:52:24 +00001068 case eInputReaderGotToken:
1069 {
1070 std::string temp_string (bytes, bytes_len);
1071 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001072 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001073 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001074 out_stream->Printf ("%s", reader.GetPrompt());
1075 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001076 }
Chris Lattner24943d22010-06-08 16:52:24 +00001077 }
1078 break;
1079
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001080 case eInputReaderEndOfFile:
1081 case eInputReaderInterrupt:
1082 // Control-c (SIGINT) & control-d both mean finish & exit.
1083 reader.SetIsDone(true);
1084
1085 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1086 if (notification == eInputReaderInterrupt)
1087 commands_in_progress.Clear();
1088
1089 // Fall through here...
1090
Chris Lattner24943d22010-06-08 16:52:24 +00001091 case eInputReaderDone:
1092 {
1093 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1094 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1095 data_ap->user_source.AppendList (commands_in_progress);
1096 if (data_ap.get())
1097 {
Greg Clayton63094e02010-06-23 01:19:29 +00001098 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001099 if (interpreter)
1100 {
1101 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1102 data_ap->script_source))
1103 {
Enrico Granata400105d2012-03-06 23:42:15 +00001104 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1105 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001106 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001107 else if (!batch_mode)
1108 {
1109 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1110 out_stream->Flush();
1111 }
Chris Lattner24943d22010-06-08 16:52:24 +00001112 }
1113 else
1114 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001115 if (!batch_mode)
1116 {
1117 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1118 out_stream->Flush();
1119 }
Chris Lattner24943d22010-06-08 16:52:24 +00001120 }
1121 }
1122 }
1123 break;
1124
1125 }
1126
1127 return bytes_len;
1128}
1129
1130void
Greg Clayton238c0a12010-09-18 01:14:36 +00001131ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001132 CommandReturnObject &result)
1133{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001134 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1135
Greg Clayton63094e02010-06-23 01:19:29 +00001136 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001137
1138 if (reader_sp)
1139 {
1140 Error err = reader_sp->Initialize (
1141 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1142 bp_options, // baton
1143 eInputReaderGranularityLine, // token size, for feeding data to callback function
1144 "DONE", // end token
1145 "> ", // prompt
1146 true); // echo input
1147
1148 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001149 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001150 else
1151 {
1152 result.AppendError (err.AsCString());
1153 result.SetStatus (eReturnStatusFailed);
1154 }
1155 }
1156 else
1157 {
1158 result.AppendError("out of memory");
1159 result.SetStatus (eReturnStatusFailed);
1160 }
1161}
1162
Johnny Chen3e0571b2010-09-11 00:23:59 +00001163// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001164void
Greg Clayton238c0a12010-09-18 01:14:36 +00001165ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001166 const char *oneliner)
1167{
1168 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1169
1170 // It's necessary to set both user_source and script_source to the oneliner.
1171 // The former is used to generate callback description (as in breakpoint command list)
1172 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001173
Johnny Chend1c2dca2010-09-10 18:21:10 +00001174 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001175
Caroline Tice5136f942010-09-27 21:35:15 +00001176 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1177 {
Enrico Granata400105d2012-03-06 23:42:15 +00001178 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1179 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Caroline Tice5136f942010-09-27 21:35:15 +00001180 }
1181
Johnny Chend1c2dca2010-09-10 18:21:10 +00001182 return;
1183}
1184
Chris Lattner24943d22010-06-08 16:52:24 +00001185bool
1186ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1187{
1188 // Convert StringList to one long, newline delimited, const char *.
Enrico Granata400105d2012-03-06 23:42:15 +00001189 std::string function_def_string(function_def.CopyList());
Chris Lattner24943d22010-06-08 16:52:24 +00001190
1191 return ExecuteMultipleLines (function_def_string.c_str());
1192}
1193
Enrico Granataf7a9b142011-07-15 02:26:42 +00001194bool
Enrico Granata400105d2012-03-06 23:42:15 +00001195ScriptInterpreterPython::GenerateFunction(const char *signature, const StringList &input)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001196{
1197 int num_lines = input.GetSize ();
1198 if (num_lines == 0)
1199 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001200
1201 if (!signature || *signature == 0)
1202 return false;
1203
Enrico Granataf7a9b142011-07-15 02:26:42 +00001204 StreamString sstr;
1205 StringList auto_generated_function;
Enrico Granata400105d2012-03-06 23:42:15 +00001206 auto_generated_function.AppendString (signature);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001207 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1208 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1209 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1210 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1211 // global dictionary.
1212
1213 // Wrap everything up inside the function, increasing the indentation.
1214
1215 for (int i = 0; i < num_lines; ++i)
1216 {
1217 sstr.Clear ();
1218 sstr.Printf (" %s", input.GetStringAtIndex (i));
1219 auto_generated_function.AppendString (sstr.GetData());
1220 }
1221 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1222 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1223 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1224 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1225
1226 // Verify that the results are valid Python.
1227
1228 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1229 return false;
1230
1231 return true;
1232
1233}
1234
Enrico Granataf7a9b142011-07-15 02:26:42 +00001235bool
Enrico Granata400105d2012-03-06 23:42:15 +00001236ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001237{
Enrico Granata400105d2012-03-06 23:42:15 +00001238 static uint32_t num_created_functions = 0;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001239 user_input.RemoveBlankLines ();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001240 StreamString sstr;
1241
1242 // Check to see if we have any data; if not, just return.
1243 if (user_input.GetSize() == 0)
1244 return false;
1245
1246 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1247 // ValueObject as parameter to the function.
1248
Enrico Granata400105d2012-03-06 23:42:15 +00001249 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 +00001250 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
Enrico Granataf7a9b142011-07-15 02:26:42 +00001251
Enrico Granata400105d2012-03-06 23:42:15 +00001252 if (!GenerateFunction(sstr.GetData(), user_input))
Enrico Granataf7a9b142011-07-15 02:26:42 +00001253 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001254
Enrico Granataf7a9b142011-07-15 02:26:42 +00001255 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001256 output.assign(auto_generated_function_name);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001257 return true;
1258}
1259
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001260bool
Enrico Granata400105d2012-03-06 23:42:15 +00001261ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, std::string &output)
Enrico Granatac2a28252011-08-16 16:49:25 +00001262{
Enrico Granata400105d2012-03-06 23:42:15 +00001263 static uint32_t num_created_functions = 0;
Enrico Granatac2a28252011-08-16 16:49:25 +00001264 user_input.RemoveBlankLines ();
Enrico Granatac2a28252011-08-16 16:49:25 +00001265 StreamString sstr;
1266
1267 // Check to see if we have any data; if not, just return.
1268 if (user_input.GetSize() == 0)
1269 return false;
1270
Enrico Granata400105d2012-03-06 23:42:15 +00001271 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_cmd_alias_func", num_created_functions));
1272
Enrico Granata271568f2011-09-09 01:41:30 +00001273 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001274
Enrico Granata400105d2012-03-06 23:42:15 +00001275 if (!GenerateFunction(sstr.GetData(),user_input))
Enrico Granatac2a28252011-08-16 16:49:25 +00001276 return false;
1277
1278 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001279 output.assign(auto_generated_function_name);
Enrico Granatac2a28252011-08-16 16:49:25 +00001280 return true;
1281}
1282
1283
1284bool
Enrico Granata400105d2012-03-06 23:42:15 +00001285ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, std::string &output, void* name_token)
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001286{
Enrico Granata400105d2012-03-06 23:42:15 +00001287 static uint32_t num_created_classes = 0;
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001288 user_input.RemoveBlankLines ();
1289 int num_lines = user_input.GetSize ();
1290 StreamString sstr;
1291
1292 // Check to see if we have any data; if not, just return.
1293 if (user_input.GetSize() == 0)
1294 return false;
1295
1296 // Wrap all user input into a Python class
1297
Enrico Granata400105d2012-03-06 23:42:15 +00001298 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 +00001299
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001300 StringList auto_generated_class;
1301
1302 // Create the function name & definition string.
1303
1304 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1305 auto_generated_class.AppendString (sstr.GetData());
1306
1307 // Wrap everything up inside the class, increasing the indentation.
1308
1309 for (int i = 0; i < num_lines; ++i)
1310 {
1311 sstr.Clear ();
1312 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1313 auto_generated_class.AppendString (sstr.GetData());
1314 }
1315
1316
1317 // Verify that the results are valid Python.
1318 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1319 // (TODO: rename that method to ExportDefinitionToInterpreter)
1320 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1321 return false;
1322
1323 // Store the name of the auto-generated class
1324
Enrico Granata400105d2012-03-06 23:42:15 +00001325 output.assign(auto_generated_class_name);
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001326 return true;
1327}
1328
Enrico Granata400105d2012-03-06 23:42:15 +00001329lldb::ScriptInterpreterObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001330ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1331 lldb::ValueObjectSP valobj)
1332{
1333 if (class_name.empty())
Enrico Granata400105d2012-03-06 23:42:15 +00001334 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001335
1336 if (!valobj.get())
Enrico Granata400105d2012-03-06 23:42:15 +00001337 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001338
Greg Claytonb4d7fc02012-02-17 07:49:44 +00001339 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1340 Target *target = exe_ctx.GetTargetPtr();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001341
1342 if (!target)
Enrico Granata400105d2012-03-06 23:42:15 +00001343 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001344
1345 Debugger &debugger = target->GetDebugger();
1346 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1347 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1348
1349 if (!script_interpreter)
Enrico Granata400105d2012-03-06 23:42:15 +00001350 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001351
1352 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001353
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001354 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001355 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001356 ForceDisableSyntheticChildren no_synthetics(target);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001357 ret_val = g_swig_synthetic_script (class_name,
1358 python_interpreter->m_dictionary_name.c_str(),
1359 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001360 }
1361
Enrico Granata400105d2012-03-06 23:42:15 +00001362 return MakeScriptObject(ret_val);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001363}
1364
Enrico Granataf7a9b142011-07-15 02:26:42 +00001365bool
Enrico Granata400105d2012-03-06 23:42:15 +00001366ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001367{
Enrico Granata16376ed2012-02-15 02:34:21 +00001368 StringList input;
1369 input.SplitIntoLines(oneliner, strlen(oneliner));
1370 return GenerateTypeScriptFunction(input, output, name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001371}
1372
Chris Lattner24943d22010-06-08 16:52:24 +00001373bool
Enrico Granata400105d2012-03-06 23:42:15 +00001374ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, std::string& output, void* name_token)
Enrico Granata16376ed2012-02-15 02:34:21 +00001375{
1376 StringList input;
1377 input.SplitIntoLines(oneliner, strlen(oneliner));
1378 return GenerateTypeSynthClass(input, output, name_token);
1379}
1380
1381
1382bool
Enrico Granata400105d2012-03-06 23:42:15 +00001383ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, std::string& output)
Chris Lattner24943d22010-06-08 16:52:24 +00001384{
Enrico Granata400105d2012-03-06 23:42:15 +00001385 static uint32_t num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001386 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001387 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001388
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001389 if (user_input.GetSize() == 0)
1390 return false;
1391
Enrico Granata400105d2012-03-06 23:42:15 +00001392 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_bp_callback_func_",num_created_functions));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001393 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001394
Enrico Granata400105d2012-03-06 23:42:15 +00001395 if (!GenerateFunction(sstr.GetData(), user_input))
Caroline Ticeb447e842010-09-21 19:25:28 +00001396 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001397
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001398 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001399 output.assign(auto_generated_function_name);
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001400 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001401}
1402
Enrico Granata1328b142012-02-29 03:28:49 +00001403bool
1404ScriptInterpreterPython::GetScriptedSummary (const char *python_function_name,
1405 lldb::ValueObjectSP valobj,
1406 lldb::ScriptInterpreterObjectSP& callee_wrapper_sp,
1407 std::string& retval)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001408{
1409
Enrico Granata1328b142012-02-29 03:28:49 +00001410 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001411
1412 if (!valobj.get())
Enrico Granata1328b142012-02-29 03:28:49 +00001413 {
1414 retval.assign("<no object>");
1415 return false;
1416 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001417
Enrico Granata1328b142012-02-29 03:28:49 +00001418 void* old_callee = (callee_wrapper_sp ? callee_wrapper_sp->GetObject() : NULL);
1419 void* new_callee = old_callee;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001420
Enrico Granata1328b142012-02-29 03:28:49 +00001421 bool ret_val;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001422 if (python_function_name
1423 && *python_function_name)
1424 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001425 {
Enrico Granata1328b142012-02-29 03:28:49 +00001426 Locker py_lock(this);
1427 {
1428 Timer scoped_timer ("g_swig_typescript_callback","g_swig_typescript_callback");
1429 ret_val = g_swig_typescript_callback (python_function_name,
1430 FindSessionDictionary(m_dictionary_name.c_str()),
1431 valobj,
1432 &new_callee,
1433 retval);
1434 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001435 }
1436 }
1437 else
Enrico Granata1328b142012-02-29 03:28:49 +00001438 {
1439 retval.assign("<no function name>");
1440 return false;
1441 }
1442
1443 if (new_callee && old_callee != new_callee)
1444 callee_wrapper_sp = MakeScriptObject(new_callee);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001445
1446 return ret_val;
1447
1448}
1449
Greg Clayton5144f382010-10-07 17:14:24 +00001450bool
1451ScriptInterpreterPython::BreakpointCallbackFunction
1452(
1453 void *baton,
1454 StoppointCallbackContext *context,
1455 user_id_t break_id,
1456 user_id_t break_loc_id
1457)
1458{
1459 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
Enrico Granata400105d2012-03-06 23:42:15 +00001460 const char *python_function_name = bp_option_data->script_source.c_str();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001461
1462 if (!context)
1463 return true;
1464
Greg Claytonf4124de2012-02-21 00:09:25 +00001465 ExecutionContext exe_ctx (context->exe_ctx_ref);
1466 Target *target = exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001467
1468 if (!target)
1469 return true;
1470
1471 Debugger &debugger = target->GetDebugger();
1472 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1473 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1474
1475 if (!script_interpreter)
1476 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001477
1478 if (python_function_name != NULL
1479 && python_function_name[0] != '\0')
1480 {
Greg Claytonf4124de2012-02-21 00:09:25 +00001481 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001482 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001483 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001484 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001485 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1486
1487 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001488 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001489 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001490 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001491 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001492 ret_val = g_swig_breakpoint_callback (python_function_name,
1493 python_interpreter->m_dictionary_name.c_str(),
1494 stop_frame_sp,
1495 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001496 }
1497 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001498 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001499 }
Greg Clayton5144f382010-10-07 17:14:24 +00001500 }
1501 // We currently always true so we stop in case anything goes wrong when
1502 // trying to call the script function
1503 return true;
1504}
Caroline Tice2ade6112010-11-10 19:18:14 +00001505
1506lldb::thread_result_t
1507ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1508{
1509 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1510
1511 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1512
1513 if (log)
1514 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1515
1516 char error_str[1024];
1517 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001518
Enrico Granatafa1f6172011-10-24 17:22:21 +00001519 Locker locker(script_interpreter,
1520 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1521 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1522
1523 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001524 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001525 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001526
Caroline Tice0aa2e552011-01-14 00:29:16 +00001527 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", 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.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1532 PyRun_SimpleString (run_string.GetData());
1533 run_string.Clear ();
1534
1535 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1536 PyRun_SimpleString (run_string.GetData());
1537 run_string.Clear ();
1538
1539 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1540 pty_slave_name);
1541 PyRun_SimpleString (run_string.GetData());
1542 run_string.Clear ();
1543
Johnny Chen8054ba32011-03-11 00:28:50 +00001544 // The following call drops into the embedded interpreter loop and stays there until the
1545 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001546
Caroline Ticece207c12011-03-11 00:21:55 +00001547 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001548 // 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 +00001549 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1550
1551 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1552 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1553 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1554 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1555 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1556 // hang (it's happened before).
1557
Caroline Tice9d352ce2011-03-07 23:24:28 +00001558 Py_BEGIN_ALLOW_THREADS
1559 PyGILState_STATE gstate = PyGILState_Ensure();
1560
Caroline Tice0aa2e552011-01-14 00:29:16 +00001561 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1562 PyRun_SimpleString (run_string.GetData());
1563 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001564
Caroline Tice9d352ce2011-03-07 23:24:28 +00001565 PyGILState_Release (gstate);
1566 Py_END_ALLOW_THREADS
1567
Caroline Tice0aa2e552011-01-14 00:29:16 +00001568 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1569 PyRun_SimpleString (run_string.GetData());
1570 run_string.Clear();
1571
1572 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1573 PyRun_SimpleString (run_string.GetData());
1574 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001575
Caroline Tice2ade6112010-11-10 19:18:14 +00001576 }
1577
1578 if (script_interpreter->m_embedded_thread_input_reader_sp)
1579 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1580
1581 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001582
Caroline Tice2ade6112010-11-10 19:18:14 +00001583 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1584 if (log)
1585 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1586
1587
Johnny Chen8054ba32011-03-11 00:28:50 +00001588 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001589 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001590 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1591 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1592 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001593
Caroline Tice2ade6112010-11-10 19:18:14 +00001594 return NULL;
1595}
1596
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001597uint32_t
Enrico Granata400105d2012-03-06 23:42:15 +00001598ScriptInterpreterPython::CalculateNumChildren (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001599{
Enrico Granata400105d2012-03-06 23:42:15 +00001600 if (!implementor_sp)
1601 return 0;
1602
1603 void* implementor = implementor_sp->GetObject();
1604
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001605 if (!implementor)
1606 return 0;
1607
1608 if (!g_swig_calc_children)
1609 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001610
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001611 uint32_t ret_val = 0;
1612
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001613 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001614 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001615 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001616 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001617 }
1618
1619 return ret_val;
1620}
1621
Enrico Granata91544802011-09-06 19:20:51 +00001622lldb::ValueObjectSP
Enrico Granata400105d2012-03-06 23:42:15 +00001623ScriptInterpreterPython::GetChildAtIndex (const lldb::ScriptInterpreterObjectSP& implementor_sp, uint32_t idx)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001624{
Enrico Granata400105d2012-03-06 23:42:15 +00001625 if (!implementor_sp)
1626 return lldb::ValueObjectSP();
1627
1628 void* implementor = implementor_sp->GetObject();
1629
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001630 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001631 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001632
Enrico Granata91544802011-09-06 19:20:51 +00001633 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1634 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001635
Enrico Granata91544802011-09-06 19:20:51 +00001636 void* child_ptr = NULL;
1637 lldb::SBValue* value_sb = NULL;
1638 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001639
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001640 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001641 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001642 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata91544802011-09-06 19:20:51 +00001643 child_ptr = g_swig_get_child_index (implementor,idx);
1644 if (child_ptr != NULL && child_ptr != Py_None)
1645 {
1646 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1647 if (value_sb == NULL)
1648 Py_XDECREF(child_ptr);
1649 else
1650 ret_val = value_sb->get_sp();
1651 }
1652 else
1653 {
1654 Py_XDECREF(child_ptr);
1655 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001656 }
1657
1658 return ret_val;
1659}
1660
1661int
Enrico Granata400105d2012-03-06 23:42:15 +00001662ScriptInterpreterPython::GetIndexOfChildWithName (const lldb::ScriptInterpreterObjectSP& implementor_sp, const char* child_name)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001663{
Enrico Granata400105d2012-03-06 23:42:15 +00001664 if (!implementor_sp)
1665 return UINT32_MAX;
1666
1667 void* implementor = implementor_sp->GetObject();
1668
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001669 if (!implementor)
1670 return UINT32_MAX;
1671
1672 if (!g_swig_get_index_child)
1673 return UINT32_MAX;
1674
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001675 int ret_val = UINT32_MAX;
1676
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001677 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001678 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001679 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001680 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001681 }
1682
1683 return ret_val;
1684}
1685
Enrico Granatacf09f882012-03-19 22:58:49 +00001686bool
Enrico Granata400105d2012-03-06 23:42:15 +00001687ScriptInterpreterPython::UpdateSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata979e20d2011-07-29 19:53:35 +00001688{
Enrico Granatacf09f882012-03-19 22:58:49 +00001689 bool ret_val = false;
1690
Enrico Granata400105d2012-03-06 23:42:15 +00001691 if (!implementor_sp)
Enrico Granatacf09f882012-03-19 22:58:49 +00001692 return ret_val;
Enrico Granata400105d2012-03-06 23:42:15 +00001693
1694 void* implementor = implementor_sp->GetObject();
1695
Enrico Granata979e20d2011-07-29 19:53:35 +00001696 if (!implementor)
Enrico Granatacf09f882012-03-19 22:58:49 +00001697 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001698
1699 if (!g_swig_update_provider)
Enrico Granatacf09f882012-03-19 22:58:49 +00001700 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001701
Enrico Granata979e20d2011-07-29 19:53:35 +00001702 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001703 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001704 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granatacf09f882012-03-19 22:58:49 +00001705 ret_val = g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001706 }
1707
Enrico Granatacf09f882012-03-19 22:58:49 +00001708 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001709}
1710
Enrico Granatac2a28252011-08-16 16:49:25 +00001711bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001712ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00001713 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00001714 lldb_private::Error& error)
1715{
1716 if (!pathname || !pathname[0])
1717 {
1718 error.SetErrorString("invalid pathname");
1719 return false;
1720 }
1721
1722 if (!g_swig_call_module_init)
1723 {
1724 error.SetErrorString("internal helper function missing");
1725 return false;
1726 }
1727
Greg Clayton13d24fb2012-01-29 20:56:30 +00001728 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granatafa1f6172011-10-24 17:22:21 +00001729
Enrico Granata59df36f2011-10-17 21:45:27 +00001730 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001731 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00001732
1733 FileSpec target_file(pathname, true);
1734
1735 // TODO: would we want to reject any other value?
1736 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1737 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1738 {
1739 error.SetErrorString("invalid pathname");
1740 return false;
1741 }
1742
1743 const char* directory = target_file.GetDirectory().GetCString();
1744 std::string basename(target_file.GetFilename().GetCString());
1745
1746 // now make sure that Python has "directory" in the search path
1747 StreamString command_stream;
1748 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1749 directory,
1750 directory);
Enrico Granatafa1f6172011-10-24 17:22:21 +00001751 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData());
Enrico Granata59df36f2011-10-17 21:45:27 +00001752 if (!syspath_retval)
1753 {
1754 error.SetErrorString("Python sys.path handling failed");
1755 return false;
1756 }
1757
1758 // strip .py or .pyc extension
1759 ConstString extension = target_file.GetFileNameExtension();
1760 if (::strcmp(extension.GetCString(), "py") == 0)
1761 basename.resize(basename.length()-3);
1762 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1763 basename.resize(basename.length()-4);
1764
1765 // check if the module is already import-ed
1766 command_stream.Clear();
1767 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1768 int refcount = 0;
1769 // this call will fail if the module does not exist (because the parameter to it is not a string
1770 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00001771 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
1772 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0);
1773 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00001774 {
1775 error.SetErrorString("module already imported");
1776 return false;
1777 }
1778
1779 // now actually do the import
1780 command_stream.Clear();
1781 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafa1f6172011-10-24 17:22:21 +00001782 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL);
Enrico Granata59df36f2011-10-17 21:45:27 +00001783 if (!import_retval)
1784 {
1785 error.SetErrorString("Python import statement failed");
1786 return false;
1787 }
1788
Enrico Granata16376ed2012-02-15 02:34:21 +00001789 // call __lldb_init_module(debugger,dict)
Enrico Granata59df36f2011-10-17 21:45:27 +00001790 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001791 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001792 debugger_sp))
1793 {
Enrico Granata16376ed2012-02-15 02:34:21 +00001794 error.SetErrorString("calling __lldb_init_module failed");
Enrico Granata59df36f2011-10-17 21:45:27 +00001795 return false;
1796 }
1797 return true;
1798 }
1799}
1800
Enrico Granata1328b142012-02-29 03:28:49 +00001801lldb::ScriptInterpreterObjectSP
1802ScriptInterpreterPython::MakeScriptObject (void* object)
1803{
1804 return lldb::ScriptInterpreterObjectSP(new ScriptInterpreterPythonObject(object));
1805}
1806
Enrico Granata6010ace2011-11-07 22:57:04 +00001807ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
1808 ScriptedCommandSynchronicity synchro) :
1809 m_debugger_sp(debugger_sp),
1810 m_synch_wanted(synchro),
1811 m_old_asynch(debugger_sp->GetAsyncExecution())
1812{
1813 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
1814 m_debugger_sp->SetAsyncExecution(false);
1815 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
1816 m_debugger_sp->SetAsyncExecution(true);
1817}
1818
1819ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
1820{
1821 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
1822 m_debugger_sp->SetAsyncExecution(m_old_asynch);
1823}
1824
Enrico Granata59df36f2011-10-17 21:45:27 +00001825bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001826ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1827 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00001828 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001829 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001830 Error& error)
1831{
1832 if (!impl_function)
1833 {
1834 error.SetErrorString("no function to execute");
1835 return false;
1836 }
1837
1838 if (!g_swig_call_command)
1839 {
1840 error.SetErrorString("no helper function to run scripted commands");
1841 return false;
1842 }
1843
Greg Clayton13d24fb2012-01-29 20:56:30 +00001844 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata6010ace2011-11-07 22:57:04 +00001845
1846 if (!debugger_sp.get())
1847 {
1848 error.SetErrorString("invalid Debugger pointer");
1849 return false;
1850 }
Enrico Granatac2a28252011-08-16 16:49:25 +00001851
1852 bool ret_val;
1853
1854 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00001855
Enrico Granatac2a28252011-08-16 16:49:25 +00001856 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001857 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00001858 SynchronicityHandler synch_handler(debugger_sp,
1859 synchronicity);
1860
Enrico Granatac2a28252011-08-16 16:49:25 +00001861 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001862 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00001863 debugger_sp,
1864 args,
1865 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001866 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001867 }
Enrico Granata6010ace2011-11-07 22:57:04 +00001868
Enrico Granatac2a28252011-08-16 16:49:25 +00001869 if (!ret_val)
1870 error.SetErrorString(err_msg.c_str());
1871 else
1872 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00001873
Enrico Granatac2a28252011-08-16 16:49:25 +00001874 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00001875}
1876
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001877// in Python, a special attribute __doc__ contains the docstring
1878// for an object (function, method, class, ...) if any is defined
1879// Otherwise, the attribute's value is None
1880std::string
1881ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1882{
1883 std::string command(item);
1884 command += ".__doc__";
1885
1886 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1887
1888 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001889 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001890 &result_ptr) && result_ptr)
1891 {
1892 return std::string(result_ptr);
1893 }
1894 else
1895 return std::string("");
1896}
Caroline Tice2ade6112010-11-10 19:18:14 +00001897
Caroline Tice0aa2e552011-01-14 00:29:16 +00001898void
Enrico Granata1328b142012-02-29 03:28:49 +00001899ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback)
Greg Claytone86cbb92011-03-22 01:14:58 +00001900{
1901 g_swig_init_callback = python_swig_init_callback;
Enrico Granata1328b142012-02-29 03:28:49 +00001902 g_swig_breakpoint_callback = LLDBSwigPythonBreakpointCallbackFunction;
1903 g_swig_typescript_callback = LLDBSwigPythonCallTypeScript;
1904 g_swig_synthetic_script = LLDBSwigPythonCreateSyntheticProvider;
1905 g_swig_calc_children = LLDBSwigPython_CalculateNumChildren;
1906 g_swig_get_child_index = LLDBSwigPython_GetChildAtIndex;
1907 g_swig_get_index_child = LLDBSwigPython_GetIndexOfChildWithName;
1908 g_swig_cast_to_sbvalue = LLDBSWIGPython_CastPyObjectToSBValue;
1909 g_swig_update_provider = LLDBSwigPython_UpdateSynthProviderInstance;
1910 g_swig_call_command = LLDBSwigPythonCallCommand;
1911 g_swig_call_module_init = LLDBSwigPythonCallModuleInit;
Greg Claytone86cbb92011-03-22 01:14:58 +00001912}
1913
1914void
1915ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001916{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001917 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1918
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001919 // Python will muck with STDIN terminal state, so save off any current TTY
1920 // settings so we can restore them.
1921 TerminalState stdin_tty_state;
1922 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001923
Caroline Tice9d352ce2011-03-07 23:24:28 +00001924 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001925 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001926
Greg Claytone86cbb92011-03-22 01:14:58 +00001927 // Initialize SWIG after setting up python
1928 assert (g_swig_init_callback != NULL);
1929 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001930
1931 // Update the path python uses to search for modules to include the current directory.
1932
Caroline Ticed4d92832011-06-13 21:33:00 +00001933 PyRun_SimpleString ("import sys");
1934 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001935
1936 // Find the module that owns this code and use that path we get to
1937 // set the sys.path appropriately.
1938
1939 FileSpec file_spec;
1940 char python_dir_path[PATH_MAX];
1941 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1942 {
1943 std::string python_path("sys.path.insert(0,\"");
1944 size_t orig_len = python_path.length();
1945 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1946 {
1947 python_path.append (python_dir_path);
1948 python_path.append ("\")");
1949 PyRun_SimpleString (python_path.c_str());
1950 python_path.resize (orig_len);
1951 }
1952
1953 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1954 {
1955 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1956 {
1957 python_path.append (python_dir_path);
1958 python_path.append ("\")");
1959 PyRun_SimpleString (python_path.c_str());
1960 python_path.resize (orig_len);
1961 }
1962 }
1963 }
1964
Greg Clayton4e651b12012-04-25 00:58:03 +00001965 PyRun_SimpleString ("sys.dont_write_bytecode = 1; import lldb.embedded_interpreter; from lldb.embedded_interpreter import run_python_interpreter; from lldb.embedded_interpreter import run_one_line; from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001966
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001967 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001968}
1969
Greg Claytone86cbb92011-03-22 01:14:58 +00001970//void
1971//ScriptInterpreterPython::Terminate ()
1972//{
1973// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1974// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1975// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1976// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1977// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1978// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1979// // within Py_Finalize, which results in a seg fault.
1980// //
1981// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1982// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1983// // process exits).
1984// //
1985//// Py_Finalize ();
1986//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00001987
1988#endif // #ifdef LLDB_DISABLE_PYTHON