blob: 89e5cb3cbd2593964028b2d51cbdef7430fcb291 [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 Granataa5c2ce02012-04-25 17:53:41 +0000306 run_string.Printf ("run_one_line (%s, 'import lldb.runtime.objc, lldb.formatters, lldb.formatters.objc, lldb.formatters.cpp')", 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
Johnny Chen2b536952012-05-04 20:37:11 +0000389
390 // rdar://problem/11292882
391 // When the current thread state is NULL, PyThreadState_Get() issues a fatal error.
392 if (PyThreadState_GetDict())
Johnny Chen41641f92012-02-29 01:52:13 +0000393 {
Enrico Granata7aa754c2012-04-04 17:31:29 +0000394 PyObject *sysmod = PyImport_AddModule ("sys");
395 PyObject *sysdict = PyModule_GetDict (sysmod);
396
397 if (m_new_sysout && sysmod && sysdict)
398 {
399 if (m_old_sysout)
400 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_old_sysout);
401 if (m_old_syserr)
402 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_old_syserr);
403 }
Johnny Chen41641f92012-02-29 01:52:13 +0000404 }
405
Caroline Tice0aa2e552011-01-14 00:29:16 +0000406 m_session_is_active = false;
407}
408
409void
410ScriptInterpreterPython::EnterSession ()
411{
412 // If we have already entered the session, without having officially 'left' it, then there is no need to
413 // 'enter' it again.
414
415 if (m_session_is_active)
416 return;
417
418 m_session_is_active = true;
419
Caroline Tice202f6b82011-01-17 21:55:19 +0000420 StreamString run_string;
421
Greg Clayton2fecc452012-01-28 02:11:02 +0000422 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %llu", m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
423 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)", GetCommandInterpreter().GetDebugger().GetID());
424 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
425 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
426 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
427 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
428 // Make sure STDIN is closed since when we run this as an embedded
429 // interpreter we don't want someone to call "line = sys.stdin.readline()"
430 // and lock up. We don't have multiple windows and when the interpreter is
431 // embedded we don't know we should be feeding input to the embedded
432 // interpreter or to the python sys.stdin. We also don't want to let python
433 // play with the real stdin from this process, so we need to close it...
Greg Clayton3eeaf6e2012-02-03 01:30:30 +0000434 //run_string.PutCString ("; sys.stdin.close()");
Greg Clayton2fecc452012-01-28 02:11:02 +0000435 run_string.PutCString ("')");
Caroline Tice0aa2e552011-01-14 00:29:16 +0000436
Caroline Tice6af65cb2011-05-03 21:21:50 +0000437 PyRun_SimpleString (run_string.GetData());
438 run_string.Clear();
Johnny Chen41641f92012-02-29 01:52:13 +0000439
Caroline Tice0aa2e552011-01-14 00:29:16 +0000440 PyObject *sysmod = PyImport_AddModule ("sys");
441 PyObject *sysdict = PyModule_GetDict (sysmod);
Johnny Chen41641f92012-02-29 01:52:13 +0000442
Greg Clayton2fecc452012-01-28 02:11:02 +0000443 if (m_new_sysout && sysmod && sysdict)
444 {
Johnny Chen41641f92012-02-29 01:52:13 +0000445 m_old_sysout = PyDict_GetItemString(sysdict, "stdout");
446 m_old_syserr = PyDict_GetItemString(sysdict, "stderr");
Johnny Chenc65046d2012-03-08 20:53:04 +0000447 if (m_new_sysout)
448 {
449 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
450 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
451 }
Greg Clayton2fecc452012-01-28 02:11:02 +0000452 }
Johnny Chen41641f92012-02-29 01:52:13 +0000453
Caroline Tice0aa2e552011-01-14 00:29:16 +0000454 if (PyErr_Occurred())
455 PyErr_Clear ();
Greg Clayton2fecc452012-01-28 02:11:02 +0000456}
Caroline Tice0aa2e552011-01-14 00:29:16 +0000457
Enrico Granata400105d2012-03-06 23:42:15 +0000458static PyObject*
459FindSessionDictionary (const char* dict_name)
460{
461 static std::map<ConstString,PyObject*> g_dict_map;
462
463 ConstString dict(dict_name);
464
465 std::map<ConstString,PyObject*>::iterator iter = g_dict_map.find(dict);
466
467 if (iter != g_dict_map.end())
468 return iter->second;
469
470 PyObject *main_mod = PyImport_AddModule ("__main__");
471 if (main_mod != NULL)
472 {
473 PyObject *main_dict = PyModule_GetDict (main_mod);
474 if ((main_dict != NULL)
475 && PyDict_Check (main_dict))
476 {
477 // Go through the main dictionary looking for the correct python script interpreter dictionary
478 PyObject *key, *value;
479 Py_ssize_t pos = 0;
480
481 while (PyDict_Next (main_dict, &pos, &key, &value))
482 {
483 // We have stolen references to the key and value objects in the dictionary; we need to increment
484 // them now so that Python's garbage collector doesn't collect them out from under us.
485 Py_INCREF (key);
486 Py_INCREF (value);
487 if (strcmp (PyString_AsString (key), dict_name) == 0)
488 {
489 g_dict_map[dict] = value;
490 return value;
491 }
492 }
493 }
494 }
495 return NULL;
496}
497
498static std::string
499GenerateUniqueName (const char* base_name_wanted,
500 uint32_t& functions_counter,
501 void* name_token = NULL)
502{
503 StreamString sstr;
504
505 if (!base_name_wanted)
506 return std::string();
507
508 if (!name_token)
509 sstr.Printf ("%s_%d", base_name_wanted, functions_counter++);
510 else
511 sstr.Printf ("%s_%p", base_name_wanted, name_token);
512
513 return sstr.GetString();
514}
515
Johnny Chen60dde642010-07-30 22:33:14 +0000516bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000517ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000518{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000519 if (!m_valid_session)
520 return false;
521
Caroline Tice4a461da2011-01-14 21:09:29 +0000522 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
523 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
524 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
525 // method to pass the command string directly down to Python.
526
Enrico Granatafa1f6172011-10-24 17:22:21 +0000527 Locker locker(this,
528 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
529 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000530
531 bool success = false;
532
Greg Clayton63094e02010-06-23 01:19:29 +0000533 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000534 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000535 // Find the correct script interpreter dictionary in the main module.
Enrico Granata400105d2012-03-06 23:42:15 +0000536 PyObject *script_interpreter_dict = FindSessionDictionary(m_dictionary_name.c_str());
537 if (script_interpreter_dict != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000538 {
Enrico Granata400105d2012-03-06 23:42:15 +0000539 PyObject *pfunc = (PyObject*)m_run_one_line;
Greg Clayton6f2f0ab2012-04-25 01:49:50 +0000540 PyObject *pmod = PyImport_AddModule ("lldb.embedded_interpreter");
Enrico Granata400105d2012-03-06 23:42:15 +0000541 if (pmod != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000542 {
Enrico Granata400105d2012-03-06 23:42:15 +0000543 PyObject *pmod_dict = PyModule_GetDict (pmod);
544 if ((pmod_dict != NULL)
545 && PyDict_Check (pmod_dict))
Caroline Tice4a461da2011-01-14 21:09:29 +0000546 {
Enrico Granata400105d2012-03-06 23:42:15 +0000547 if (!pfunc)
Caroline Tice4a461da2011-01-14 21:09:29 +0000548 {
549 PyObject *key, *value;
550 Py_ssize_t pos = 0;
551
552 while (PyDict_Next (pmod_dict, &pos, &key, &value))
553 {
554 Py_INCREF (key);
555 Py_INCREF (value);
556 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
557 {
558 pfunc = value;
559 break;
560 }
561 }
Enrico Granata400105d2012-03-06 23:42:15 +0000562 m_run_one_line = pfunc;
563 }
564
565 if (pfunc && PyCallable_Check (pfunc))
566 {
567 PyObject *pargs = Py_BuildValue("(Os)",script_interpreter_dict,command);
568 if (pargs != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000569 {
Enrico Granata400105d2012-03-06 23:42:15 +0000570 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
571 Py_DECREF (pargs);
572 if (pvalue != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000573 {
Enrico Granata400105d2012-03-06 23:42:15 +0000574 Py_DECREF (pvalue);
575 success = true;
576 }
577 else if (PyErr_Occurred ())
578 {
579 PyErr_Print();
580 PyErr_Clear();
Caroline Tice4a461da2011-01-14 21:09:29 +0000581 }
582 }
583 }
584 }
Caroline Tice4a461da2011-01-14 21:09:29 +0000585 }
Enrico Granata400105d2012-03-06 23:42:15 +0000586 Py_INCREF (script_interpreter_dict);
Caroline Tice4a461da2011-01-14 21:09:29 +0000587 }
Greg Clayton63094e02010-06-23 01:19:29 +0000588
Caroline Tice4a461da2011-01-14 21:09:29 +0000589 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000590 return true;
591
592 // The one-liner failed. Append the error message.
593 if (result)
594 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
595 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000596 }
Johnny Chen60dde642010-07-30 22:33:14 +0000597
598 if (result)
599 result->AppendError ("empty command passed to python\n");
600 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000601}
602
Chris Lattner24943d22010-06-08 16:52:24 +0000603size_t
604ScriptInterpreterPython::InputReaderCallback
605(
606 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000607 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000608 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000609 const char *bytes,
610 size_t bytes_len
611)
612{
Caroline Tice2ade6112010-11-10 19:18:14 +0000613 lldb::thread_t embedded_interpreter_thread;
614 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
615
Chris Lattner24943d22010-06-08 16:52:24 +0000616 if (baton == NULL)
617 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000618
619 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000620
Caroline Tice0aa2e552011-01-14 00:29:16 +0000621 if (script_interpreter->m_script_lang != eScriptLanguagePython)
622 return 0;
623
Caroline Tice892fadd2011-06-16 16:27:19 +0000624 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
625 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
626
Chris Lattner24943d22010-06-08 16:52:24 +0000627 switch (notification)
628 {
629 case eInputReaderActivate:
630 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000631 if (!batch_mode)
632 {
633 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
634 out_stream->Flush();
635 }
Greg Clayton58928562011-02-09 01:08:52 +0000636
Chris Lattner24943d22010-06-08 16:52:24 +0000637 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000638 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
639 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000640 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000641
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000642 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000643
Caroline Tice202f6b82011-01-17 21:55:19 +0000644 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000645 ScriptInterpreterPython::Locker locker(script_interpreter,
646 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
647 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000648 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000649
Caroline Tice2ade6112010-11-10 19:18:14 +0000650 char error_str[1024];
651 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
652 sizeof(error_str)))
653 {
654 if (log)
655 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
656 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
657 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
658 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
659 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000660 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000661 {
662 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000663 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000664 Error detach_error;
665 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
666 }
667 else
668 {
669 if (log)
670 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
671 reader.SetIsDone (true);
672 }
673 }
674 else
675 {
676 if (log)
677 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
678 reader.SetIsDone (true);
679 }
Chris Lattner24943d22010-06-08 16:52:24 +0000680 }
681 break;
682
683 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000684 // When another input reader is pushed, don't leave the session...
685 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000686 break;
687
688 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000689 {
Greg Claytona1cec242012-01-06 00:47:38 +0000690 // Don't try and acquire the interpreter lock here because code like
691 // this:
692 //
693 // (lldb) script
694 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
695 //
696 // This will cause the process to run. The interpreter lock is taken
697 // by the input reader for the "script" command. If we try and acquire
698 // the lock here, when the process runs it might deactivate this input
699 // reader (if STDIN is hooked up to the inferior process) and
700 // reactivate it when the process stops which will deadlock.
701 //ScriptInterpreterPython::Locker locker(script_interpreter,
702 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
703 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000704 }
Chris Lattner24943d22010-06-08 16:52:24 +0000705 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000706
Caroline Tice4a348082011-05-02 20:41:46 +0000707 case eInputReaderAsynchronousOutputWritten:
708 break;
709
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000710 case eInputReaderInterrupt:
711 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
712 break;
713
714 case eInputReaderEndOfFile:
715 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
716 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000717
718 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000719 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000720 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000721 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000722 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000723 bytes_len);
724 if (bytes && bytes_len)
725 {
726 if ((int) bytes[0] == 4)
727 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
728 else
729 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
730 }
731 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000732 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000733 else
734 {
735 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000736 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000737 bytes,
738 bytes_len);
739 reader.SetIsDone (true);
740 }
741
Chris Lattner24943d22010-06-08 16:52:24 +0000742 break;
743
744 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000745 script_interpreter->LeaveSession ();
746
Chris Lattner24943d22010-06-08 16:52:24 +0000747 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000748 if (log)
749 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000750
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000751 script_interpreter->RestoreTerminalState ();
752
Caroline Tice2ade6112010-11-10 19:18:14 +0000753 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000754 break;
755 }
756
757 return bytes_len;
758}
759
760
761void
Greg Clayton238c0a12010-09-18 01:14:36 +0000762ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000763{
764 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
765
Caroline Tice0aa2e552011-01-14 00:29:16 +0000766 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000767
768 // At the moment, the only time the debugger does not have an input file handle is when this is called
769 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
770 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
771 // do it.
772
Greg Clayton58928562011-02-09 01:08:52 +0000773 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000774 return;
775
Greg Clayton63094e02010-06-23 01:19:29 +0000776 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000777 if (reader_sp)
778 {
779 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
780 this, // baton
781 eInputReaderGranularityLine, // token size, to pass to callback function
782 NULL, // end token
783 NULL, // prompt
784 true)); // echo input
785
786 if (error.Success())
787 {
Greg Clayton63094e02010-06-23 01:19:29 +0000788 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000789 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000790 }
791 }
792}
793
794bool
795ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000796 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000797 void *ret_value)
798{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000799
Enrico Granatafa1f6172011-10-24 17:22:21 +0000800 Locker locker(this,
801 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
802 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000803
Chris Lattner24943d22010-06-08 16:52:24 +0000804 PyObject *py_return = NULL;
805 PyObject *mainmod = PyImport_AddModule ("__main__");
806 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000807 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000808 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000809 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000810 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000811 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000812
Enrico Granata400105d2012-03-06 23:42:15 +0000813 locals = FindSessionDictionary(m_dictionary_name.c_str());
814
Caroline Tice0aa2e552011-01-14 00:29:16 +0000815 if (locals == NULL)
816 {
817 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
818 should_decrement_locals = true;
819 }
820
821 if (locals == NULL)
822 {
823 locals = globals;
824 should_decrement_locals = false;
825 }
826
827 py_error = PyErr_Occurred();
828 if (py_error != NULL)
829 PyErr_Clear();
830
Chris Lattner24943d22010-06-08 16:52:24 +0000831 if (in_string != NULL)
832 {
833 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
834 if (py_return == NULL)
835 {
836 py_error = PyErr_Occurred ();
837 if (py_error != NULL)
838 PyErr_Clear ();
839
840 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
841 }
842
Caroline Tice0aa2e552011-01-14 00:29:16 +0000843 if (locals != NULL
844 && should_decrement_locals)
845 Py_DECREF (locals);
846
Chris Lattner24943d22010-06-08 16:52:24 +0000847 if (py_return != NULL)
848 {
849 switch (return_type)
850 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000851 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000852 {
853 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000854 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000855 break;
856 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000857 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000858 {
859 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000860 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000861 break;
862 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000863 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000864 {
865 const char format[2] = "b";
866 success = PyArg_Parse (py_return, format, (bool *) ret_value);
867 break;
868 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000869 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000870 {
871 const char format[2] = "h";
872 success = PyArg_Parse (py_return, format, (short *) ret_value);
873 break;
874 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000875 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000876 {
877 const char format[2] = "H";
878 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
879 break;
880 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000881 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000882 {
883 const char format[2] = "i";
884 success = PyArg_Parse (py_return, format, (int *) ret_value);
885 break;
886 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000887 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000888 {
889 const char format[2] = "I";
890 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
891 break;
892 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000893 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000894 {
895 const char format[2] = "l";
896 success = PyArg_Parse (py_return, format, (long *) ret_value);
897 break;
898 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000899 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000900 {
901 const char format[2] = "k";
902 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
903 break;
904 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000905 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000906 {
907 const char format[2] = "L";
908 success = PyArg_Parse (py_return, format, (long long *) ret_value);
909 break;
910 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000911 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000912 {
913 const char format[2] = "K";
914 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
915 break;
916 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000917 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000918 {
919 const char format[2] = "f";
920 success = PyArg_Parse (py_return, format, (float *) ret_value);
921 break;
922 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000923 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000924 {
925 const char format[2] = "d";
926 success = PyArg_Parse (py_return, format, (double *) ret_value);
927 break;
928 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000929 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000930 {
931 const char format[2] = "c";
932 success = PyArg_Parse (py_return, format, (char *) ret_value);
933 break;
934 }
935 default:
936 {}
937 }
938 Py_DECREF (py_return);
939 if (success)
940 ret_success = true;
941 else
942 ret_success = false;
943 }
944 }
945
946 py_error = PyErr_Occurred();
947 if (py_error != NULL)
948 {
949 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
950 PyErr_Print ();
951 PyErr_Clear();
952 ret_success = false;
953 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000954
Chris Lattner24943d22010-06-08 16:52:24 +0000955 return ret_success;
956}
957
958bool
959ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
960{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000961
962
963 Locker locker(this,
964 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
965 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000966
Chris Lattner24943d22010-06-08 16:52:24 +0000967 bool success = false;
968 PyObject *py_return = NULL;
969 PyObject *mainmod = PyImport_AddModule ("__main__");
970 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000971 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000972 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000973 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000974
Enrico Granata400105d2012-03-06 23:42:15 +0000975 locals = FindSessionDictionary(m_dictionary_name.c_str());
976
Caroline Tice0aa2e552011-01-14 00:29:16 +0000977 if (locals == NULL)
978 {
979 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
980 should_decrement_locals = true;
981 }
982
983 if (locals == NULL)
984 {
985 locals = globals;
986 should_decrement_locals = false;
987 }
988
989 py_error = PyErr_Occurred();
990 if (py_error != NULL)
991 PyErr_Clear();
992
Chris Lattner24943d22010-06-08 16:52:24 +0000993 if (in_string != NULL)
994 {
995 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
996 if (compiled_node)
997 {
998 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
999 if (compiled_code)
1000 {
1001 py_return = PyEval_EvalCode (compiled_code, globals, locals);
1002 if (py_return != NULL)
1003 {
1004 success = true;
1005 Py_DECREF (py_return);
1006 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001007 if (locals && should_decrement_locals)
1008 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +00001009 }
1010 }
1011 }
1012
1013 py_error = PyErr_Occurred ();
1014 if (py_error != NULL)
1015 {
1016 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1017 PyErr_Print ();
1018 PyErr_Clear();
1019 success = false;
1020 }
1021
1022 return success;
1023}
1024
1025static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1026
1027size_t
1028ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1029(
1030 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001031 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001032 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001033 const char *bytes,
1034 size_t bytes_len
1035)
1036{
Caroline Tice892fadd2011-06-16 16:27:19 +00001037 static StringList commands_in_progress;
1038
1039 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1040 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1041
Chris Lattner24943d22010-06-08 16:52:24 +00001042 switch (notification)
1043 {
1044 case eInputReaderActivate:
1045 {
1046 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +00001047 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +00001048 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001049 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001050 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +00001051 out_stream->Printf ("%s", reader.GetPrompt());
1052 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001053 }
1054 }
1055 break;
1056
1057 case eInputReaderDeactivate:
1058 break;
1059
1060 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001061 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001062 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001063 out_stream->Printf ("%s", reader.GetPrompt());
1064 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001065 }
Chris Lattner24943d22010-06-08 16:52:24 +00001066 break;
1067
Caroline Tice4a348082011-05-02 20:41:46 +00001068 case eInputReaderAsynchronousOutputWritten:
1069 break;
1070
Chris Lattner24943d22010-06-08 16:52:24 +00001071 case eInputReaderGotToken:
1072 {
1073 std::string temp_string (bytes, bytes_len);
1074 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001075 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001076 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001077 out_stream->Printf ("%s", reader.GetPrompt());
1078 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001079 }
Chris Lattner24943d22010-06-08 16:52:24 +00001080 }
1081 break;
1082
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001083 case eInputReaderEndOfFile:
1084 case eInputReaderInterrupt:
1085 // Control-c (SIGINT) & control-d both mean finish & exit.
1086 reader.SetIsDone(true);
1087
1088 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1089 if (notification == eInputReaderInterrupt)
1090 commands_in_progress.Clear();
1091
1092 // Fall through here...
1093
Chris Lattner24943d22010-06-08 16:52:24 +00001094 case eInputReaderDone:
1095 {
1096 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1097 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1098 data_ap->user_source.AppendList (commands_in_progress);
1099 if (data_ap.get())
1100 {
Greg Clayton63094e02010-06-23 01:19:29 +00001101 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001102 if (interpreter)
1103 {
1104 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1105 data_ap->script_source))
1106 {
Enrico Granata400105d2012-03-06 23:42:15 +00001107 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1108 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001109 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001110 else if (!batch_mode)
1111 {
1112 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1113 out_stream->Flush();
1114 }
Chris Lattner24943d22010-06-08 16:52:24 +00001115 }
1116 else
1117 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001118 if (!batch_mode)
1119 {
1120 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1121 out_stream->Flush();
1122 }
Chris Lattner24943d22010-06-08 16:52:24 +00001123 }
1124 }
1125 }
1126 break;
1127
1128 }
1129
1130 return bytes_len;
1131}
1132
1133void
Greg Clayton238c0a12010-09-18 01:14:36 +00001134ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001135 CommandReturnObject &result)
1136{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001137 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1138
Greg Clayton63094e02010-06-23 01:19:29 +00001139 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001140
1141 if (reader_sp)
1142 {
1143 Error err = reader_sp->Initialize (
1144 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1145 bp_options, // baton
1146 eInputReaderGranularityLine, // token size, for feeding data to callback function
1147 "DONE", // end token
1148 "> ", // prompt
1149 true); // echo input
1150
1151 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001152 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001153 else
1154 {
1155 result.AppendError (err.AsCString());
1156 result.SetStatus (eReturnStatusFailed);
1157 }
1158 }
1159 else
1160 {
1161 result.AppendError("out of memory");
1162 result.SetStatus (eReturnStatusFailed);
1163 }
1164}
1165
Johnny Chen3e0571b2010-09-11 00:23:59 +00001166// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001167void
Greg Clayton238c0a12010-09-18 01:14:36 +00001168ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001169 const char *oneliner)
1170{
1171 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1172
1173 // It's necessary to set both user_source and script_source to the oneliner.
1174 // The former is used to generate callback description (as in breakpoint command list)
1175 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001176
Johnny Chend1c2dca2010-09-10 18:21:10 +00001177 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001178
Caroline Tice5136f942010-09-27 21:35:15 +00001179 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1180 {
Enrico Granata400105d2012-03-06 23:42:15 +00001181 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1182 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Caroline Tice5136f942010-09-27 21:35:15 +00001183 }
1184
Johnny Chend1c2dca2010-09-10 18:21:10 +00001185 return;
1186}
1187
Chris Lattner24943d22010-06-08 16:52:24 +00001188bool
1189ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1190{
1191 // Convert StringList to one long, newline delimited, const char *.
Enrico Granata400105d2012-03-06 23:42:15 +00001192 std::string function_def_string(function_def.CopyList());
Chris Lattner24943d22010-06-08 16:52:24 +00001193
1194 return ExecuteMultipleLines (function_def_string.c_str());
1195}
1196
Enrico Granataf7a9b142011-07-15 02:26:42 +00001197bool
Enrico Granata400105d2012-03-06 23:42:15 +00001198ScriptInterpreterPython::GenerateFunction(const char *signature, const StringList &input)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001199{
1200 int num_lines = input.GetSize ();
1201 if (num_lines == 0)
1202 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001203
1204 if (!signature || *signature == 0)
1205 return false;
1206
Enrico Granataf7a9b142011-07-15 02:26:42 +00001207 StreamString sstr;
1208 StringList auto_generated_function;
Enrico Granata400105d2012-03-06 23:42:15 +00001209 auto_generated_function.AppendString (signature);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001210 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1211 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1212 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1213 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1214 // global dictionary.
1215
1216 // Wrap everything up inside the function, increasing the indentation.
1217
1218 for (int i = 0; i < num_lines; ++i)
1219 {
1220 sstr.Clear ();
1221 sstr.Printf (" %s", input.GetStringAtIndex (i));
1222 auto_generated_function.AppendString (sstr.GetData());
1223 }
1224 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1225 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1226 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1227 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1228
1229 // Verify that the results are valid Python.
1230
1231 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1232 return false;
1233
1234 return true;
1235
1236}
1237
Enrico Granataf7a9b142011-07-15 02:26:42 +00001238bool
Enrico Granata400105d2012-03-06 23:42:15 +00001239ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001240{
Enrico Granata400105d2012-03-06 23:42:15 +00001241 static uint32_t num_created_functions = 0;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001242 user_input.RemoveBlankLines ();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001243 StreamString sstr;
1244
1245 // Check to see if we have any data; if not, just return.
1246 if (user_input.GetSize() == 0)
1247 return false;
1248
1249 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1250 // ValueObject as parameter to the function.
1251
Enrico Granata400105d2012-03-06 23:42:15 +00001252 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 +00001253 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
Enrico Granataf7a9b142011-07-15 02:26:42 +00001254
Enrico Granata400105d2012-03-06 23:42:15 +00001255 if (!GenerateFunction(sstr.GetData(), user_input))
Enrico Granataf7a9b142011-07-15 02:26:42 +00001256 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001257
Enrico Granataf7a9b142011-07-15 02:26:42 +00001258 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001259 output.assign(auto_generated_function_name);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001260 return true;
1261}
1262
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001263bool
Enrico Granata400105d2012-03-06 23:42:15 +00001264ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, std::string &output)
Enrico Granatac2a28252011-08-16 16:49:25 +00001265{
Enrico Granata400105d2012-03-06 23:42:15 +00001266 static uint32_t num_created_functions = 0;
Enrico Granatac2a28252011-08-16 16:49:25 +00001267 user_input.RemoveBlankLines ();
Enrico Granatac2a28252011-08-16 16:49:25 +00001268 StreamString sstr;
1269
1270 // Check to see if we have any data; if not, just return.
1271 if (user_input.GetSize() == 0)
1272 return false;
1273
Enrico Granata400105d2012-03-06 23:42:15 +00001274 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_cmd_alias_func", num_created_functions));
1275
Enrico Granata271568f2011-09-09 01:41:30 +00001276 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001277
Enrico Granata400105d2012-03-06 23:42:15 +00001278 if (!GenerateFunction(sstr.GetData(),user_input))
Enrico Granatac2a28252011-08-16 16:49:25 +00001279 return false;
1280
1281 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001282 output.assign(auto_generated_function_name);
Enrico Granatac2a28252011-08-16 16:49:25 +00001283 return true;
1284}
1285
1286
1287bool
Enrico Granata400105d2012-03-06 23:42:15 +00001288ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, std::string &output, void* name_token)
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001289{
Enrico Granata400105d2012-03-06 23:42:15 +00001290 static uint32_t num_created_classes = 0;
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001291 user_input.RemoveBlankLines ();
1292 int num_lines = user_input.GetSize ();
1293 StreamString sstr;
1294
1295 // Check to see if we have any data; if not, just return.
1296 if (user_input.GetSize() == 0)
1297 return false;
1298
1299 // Wrap all user input into a Python class
1300
Enrico Granata400105d2012-03-06 23:42:15 +00001301 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 +00001302
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001303 StringList auto_generated_class;
1304
1305 // Create the function name & definition string.
1306
1307 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1308 auto_generated_class.AppendString (sstr.GetData());
1309
1310 // Wrap everything up inside the class, increasing the indentation.
1311
1312 for (int i = 0; i < num_lines; ++i)
1313 {
1314 sstr.Clear ();
1315 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1316 auto_generated_class.AppendString (sstr.GetData());
1317 }
1318
1319
1320 // Verify that the results are valid Python.
1321 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1322 // (TODO: rename that method to ExportDefinitionToInterpreter)
1323 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1324 return false;
1325
1326 // Store the name of the auto-generated class
1327
Enrico Granata400105d2012-03-06 23:42:15 +00001328 output.assign(auto_generated_class_name);
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001329 return true;
1330}
1331
Enrico Granata400105d2012-03-06 23:42:15 +00001332lldb::ScriptInterpreterObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001333ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1334 lldb::ValueObjectSP valobj)
1335{
1336 if (class_name.empty())
Enrico Granata400105d2012-03-06 23:42:15 +00001337 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001338
1339 if (!valobj.get())
Enrico Granata400105d2012-03-06 23:42:15 +00001340 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001341
Greg Claytonb4d7fc02012-02-17 07:49:44 +00001342 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1343 Target *target = exe_ctx.GetTargetPtr();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001344
1345 if (!target)
Enrico Granata400105d2012-03-06 23:42:15 +00001346 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001347
1348 Debugger &debugger = target->GetDebugger();
1349 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1350 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1351
1352 if (!script_interpreter)
Enrico Granata400105d2012-03-06 23:42:15 +00001353 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001354
1355 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001356
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001357 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001358 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001359 ForceDisableSyntheticChildren no_synthetics(target);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001360 ret_val = g_swig_synthetic_script (class_name,
1361 python_interpreter->m_dictionary_name.c_str(),
1362 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001363 }
1364
Enrico Granata400105d2012-03-06 23:42:15 +00001365 return MakeScriptObject(ret_val);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001366}
1367
Enrico Granataf7a9b142011-07-15 02:26:42 +00001368bool
Enrico Granata400105d2012-03-06 23:42:15 +00001369ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001370{
Enrico Granata16376ed2012-02-15 02:34:21 +00001371 StringList input;
1372 input.SplitIntoLines(oneliner, strlen(oneliner));
1373 return GenerateTypeScriptFunction(input, output, name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001374}
1375
Chris Lattner24943d22010-06-08 16:52:24 +00001376bool
Enrico Granata400105d2012-03-06 23:42:15 +00001377ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, std::string& output, void* name_token)
Enrico Granata16376ed2012-02-15 02:34:21 +00001378{
1379 StringList input;
1380 input.SplitIntoLines(oneliner, strlen(oneliner));
1381 return GenerateTypeSynthClass(input, output, name_token);
1382}
1383
1384
1385bool
Enrico Granata400105d2012-03-06 23:42:15 +00001386ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, std::string& output)
Chris Lattner24943d22010-06-08 16:52:24 +00001387{
Enrico Granata400105d2012-03-06 23:42:15 +00001388 static uint32_t num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001389 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001390 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001391
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001392 if (user_input.GetSize() == 0)
1393 return false;
1394
Enrico Granata400105d2012-03-06 23:42:15 +00001395 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_bp_callback_func_",num_created_functions));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001396 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001397
Enrico Granata400105d2012-03-06 23:42:15 +00001398 if (!GenerateFunction(sstr.GetData(), user_input))
Caroline Ticeb447e842010-09-21 19:25:28 +00001399 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001400
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001401 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001402 output.assign(auto_generated_function_name);
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001403 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001404}
1405
Enrico Granata1328b142012-02-29 03:28:49 +00001406bool
1407ScriptInterpreterPython::GetScriptedSummary (const char *python_function_name,
1408 lldb::ValueObjectSP valobj,
1409 lldb::ScriptInterpreterObjectSP& callee_wrapper_sp,
1410 std::string& retval)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001411{
1412
Enrico Granata1328b142012-02-29 03:28:49 +00001413 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001414
1415 if (!valobj.get())
Enrico Granata1328b142012-02-29 03:28:49 +00001416 {
1417 retval.assign("<no object>");
1418 return false;
1419 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001420
Enrico Granata1328b142012-02-29 03:28:49 +00001421 void* old_callee = (callee_wrapper_sp ? callee_wrapper_sp->GetObject() : NULL);
1422 void* new_callee = old_callee;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001423
Enrico Granata1328b142012-02-29 03:28:49 +00001424 bool ret_val;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001425 if (python_function_name
1426 && *python_function_name)
1427 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001428 {
Enrico Granata1328b142012-02-29 03:28:49 +00001429 Locker py_lock(this);
1430 {
1431 Timer scoped_timer ("g_swig_typescript_callback","g_swig_typescript_callback");
1432 ret_val = g_swig_typescript_callback (python_function_name,
1433 FindSessionDictionary(m_dictionary_name.c_str()),
1434 valobj,
1435 &new_callee,
1436 retval);
1437 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001438 }
1439 }
1440 else
Enrico Granata1328b142012-02-29 03:28:49 +00001441 {
1442 retval.assign("<no function name>");
1443 return false;
1444 }
1445
1446 if (new_callee && old_callee != new_callee)
1447 callee_wrapper_sp = MakeScriptObject(new_callee);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001448
1449 return ret_val;
1450
1451}
1452
Greg Clayton5144f382010-10-07 17:14:24 +00001453bool
1454ScriptInterpreterPython::BreakpointCallbackFunction
1455(
1456 void *baton,
1457 StoppointCallbackContext *context,
1458 user_id_t break_id,
1459 user_id_t break_loc_id
1460)
1461{
1462 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
Enrico Granata400105d2012-03-06 23:42:15 +00001463 const char *python_function_name = bp_option_data->script_source.c_str();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001464
1465 if (!context)
1466 return true;
1467
Greg Claytonf4124de2012-02-21 00:09:25 +00001468 ExecutionContext exe_ctx (context->exe_ctx_ref);
1469 Target *target = exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001470
1471 if (!target)
1472 return true;
1473
1474 Debugger &debugger = target->GetDebugger();
1475 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1476 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1477
1478 if (!script_interpreter)
1479 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001480
1481 if (python_function_name != NULL
1482 && python_function_name[0] != '\0')
1483 {
Greg Claytonf4124de2012-02-21 00:09:25 +00001484 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001485 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001486 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001487 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001488 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1489
1490 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001491 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001492 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001493 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001494 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001495 ret_val = g_swig_breakpoint_callback (python_function_name,
1496 python_interpreter->m_dictionary_name.c_str(),
1497 stop_frame_sp,
1498 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001499 }
1500 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001501 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001502 }
Greg Clayton5144f382010-10-07 17:14:24 +00001503 }
1504 // We currently always true so we stop in case anything goes wrong when
1505 // trying to call the script function
1506 return true;
1507}
Caroline Tice2ade6112010-11-10 19:18:14 +00001508
1509lldb::thread_result_t
1510ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1511{
1512 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1513
1514 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1515
1516 if (log)
1517 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1518
1519 char error_str[1024];
1520 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001521
Enrico Granatafa1f6172011-10-24 17:22:21 +00001522 Locker locker(script_interpreter,
1523 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1524 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1525
1526 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001527 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001528 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001529
Caroline Tice0aa2e552011-01-14 00:29:16 +00001530 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1531 PyRun_SimpleString (run_string.GetData());
1532 run_string.Clear ();
1533
1534 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1535 PyRun_SimpleString (run_string.GetData());
1536 run_string.Clear ();
1537
1538 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1539 PyRun_SimpleString (run_string.GetData());
1540 run_string.Clear ();
1541
1542 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1543 pty_slave_name);
1544 PyRun_SimpleString (run_string.GetData());
1545 run_string.Clear ();
1546
Johnny Chen8054ba32011-03-11 00:28:50 +00001547 // The following call drops into the embedded interpreter loop and stays there until the
1548 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001549
Caroline Ticece207c12011-03-11 00:21:55 +00001550 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001551 // 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 +00001552 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1553
1554 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1555 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1556 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1557 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1558 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1559 // hang (it's happened before).
1560
Caroline Tice9d352ce2011-03-07 23:24:28 +00001561 Py_BEGIN_ALLOW_THREADS
1562 PyGILState_STATE gstate = PyGILState_Ensure();
1563
Caroline Tice0aa2e552011-01-14 00:29:16 +00001564 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1565 PyRun_SimpleString (run_string.GetData());
1566 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001567
Caroline Tice9d352ce2011-03-07 23:24:28 +00001568 PyGILState_Release (gstate);
1569 Py_END_ALLOW_THREADS
1570
Caroline Tice0aa2e552011-01-14 00:29:16 +00001571 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1572 PyRun_SimpleString (run_string.GetData());
1573 run_string.Clear();
1574
1575 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1576 PyRun_SimpleString (run_string.GetData());
1577 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001578
Caroline Tice2ade6112010-11-10 19:18:14 +00001579 }
1580
1581 if (script_interpreter->m_embedded_thread_input_reader_sp)
1582 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1583
1584 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001585
Caroline Tice2ade6112010-11-10 19:18:14 +00001586 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1587 if (log)
1588 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1589
1590
Johnny Chen8054ba32011-03-11 00:28:50 +00001591 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001592 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001593 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1594 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1595 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001596
Caroline Tice2ade6112010-11-10 19:18:14 +00001597 return NULL;
1598}
1599
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001600uint32_t
Enrico Granata400105d2012-03-06 23:42:15 +00001601ScriptInterpreterPython::CalculateNumChildren (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001602{
Enrico Granata400105d2012-03-06 23:42:15 +00001603 if (!implementor_sp)
1604 return 0;
1605
1606 void* implementor = implementor_sp->GetObject();
1607
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001608 if (!implementor)
1609 return 0;
1610
1611 if (!g_swig_calc_children)
1612 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001613
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001614 uint32_t ret_val = 0;
1615
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001616 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001617 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001618 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001619 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001620 }
1621
1622 return ret_val;
1623}
1624
Enrico Granata91544802011-09-06 19:20:51 +00001625lldb::ValueObjectSP
Enrico Granata400105d2012-03-06 23:42:15 +00001626ScriptInterpreterPython::GetChildAtIndex (const lldb::ScriptInterpreterObjectSP& implementor_sp, uint32_t idx)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001627{
Enrico Granata400105d2012-03-06 23:42:15 +00001628 if (!implementor_sp)
1629 return lldb::ValueObjectSP();
1630
1631 void* implementor = implementor_sp->GetObject();
1632
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001633 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001634 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001635
Enrico Granata91544802011-09-06 19:20:51 +00001636 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1637 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001638
Enrico Granata91544802011-09-06 19:20:51 +00001639 void* child_ptr = NULL;
1640 lldb::SBValue* value_sb = NULL;
1641 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001642
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001643 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001644 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001645 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata91544802011-09-06 19:20:51 +00001646 child_ptr = g_swig_get_child_index (implementor,idx);
1647 if (child_ptr != NULL && child_ptr != Py_None)
1648 {
1649 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1650 if (value_sb == NULL)
1651 Py_XDECREF(child_ptr);
1652 else
1653 ret_val = value_sb->get_sp();
1654 }
1655 else
1656 {
1657 Py_XDECREF(child_ptr);
1658 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001659 }
1660
1661 return ret_val;
1662}
1663
1664int
Enrico Granata400105d2012-03-06 23:42:15 +00001665ScriptInterpreterPython::GetIndexOfChildWithName (const lldb::ScriptInterpreterObjectSP& implementor_sp, const char* child_name)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001666{
Enrico Granata400105d2012-03-06 23:42:15 +00001667 if (!implementor_sp)
1668 return UINT32_MAX;
1669
1670 void* implementor = implementor_sp->GetObject();
1671
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001672 if (!implementor)
1673 return UINT32_MAX;
1674
1675 if (!g_swig_get_index_child)
1676 return UINT32_MAX;
1677
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001678 int ret_val = UINT32_MAX;
1679
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001680 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001681 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001682 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001683 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001684 }
1685
1686 return ret_val;
1687}
1688
Enrico Granatacf09f882012-03-19 22:58:49 +00001689bool
Enrico Granata400105d2012-03-06 23:42:15 +00001690ScriptInterpreterPython::UpdateSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata979e20d2011-07-29 19:53:35 +00001691{
Enrico Granatacf09f882012-03-19 22:58:49 +00001692 bool ret_val = false;
1693
Enrico Granata400105d2012-03-06 23:42:15 +00001694 if (!implementor_sp)
Enrico Granatacf09f882012-03-19 22:58:49 +00001695 return ret_val;
Enrico Granata400105d2012-03-06 23:42:15 +00001696
1697 void* implementor = implementor_sp->GetObject();
1698
Enrico Granata979e20d2011-07-29 19:53:35 +00001699 if (!implementor)
Enrico Granatacf09f882012-03-19 22:58:49 +00001700 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001701
1702 if (!g_swig_update_provider)
Enrico Granatacf09f882012-03-19 22:58:49 +00001703 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001704
Enrico Granata979e20d2011-07-29 19:53:35 +00001705 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001706 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001707 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granatacf09f882012-03-19 22:58:49 +00001708 ret_val = g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001709 }
1710
Enrico Granatacf09f882012-03-19 22:58:49 +00001711 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001712}
1713
Enrico Granatac2a28252011-08-16 16:49:25 +00001714bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001715ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00001716 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00001717 lldb_private::Error& error)
1718{
1719 if (!pathname || !pathname[0])
1720 {
1721 error.SetErrorString("invalid pathname");
1722 return false;
1723 }
1724
1725 if (!g_swig_call_module_init)
1726 {
1727 error.SetErrorString("internal helper function missing");
1728 return false;
1729 }
1730
Greg Clayton13d24fb2012-01-29 20:56:30 +00001731 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granatafa1f6172011-10-24 17:22:21 +00001732
Enrico Granata59df36f2011-10-17 21:45:27 +00001733 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001734 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00001735
1736 FileSpec target_file(pathname, true);
1737
1738 // TODO: would we want to reject any other value?
1739 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1740 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1741 {
1742 error.SetErrorString("invalid pathname");
1743 return false;
1744 }
1745
1746 const char* directory = target_file.GetDirectory().GetCString();
1747 std::string basename(target_file.GetFilename().GetCString());
1748
1749 // now make sure that Python has "directory" in the search path
1750 StreamString command_stream;
1751 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1752 directory,
1753 directory);
Enrico Granatafa1f6172011-10-24 17:22:21 +00001754 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData());
Enrico Granata59df36f2011-10-17 21:45:27 +00001755 if (!syspath_retval)
1756 {
1757 error.SetErrorString("Python sys.path handling failed");
1758 return false;
1759 }
1760
1761 // strip .py or .pyc extension
1762 ConstString extension = target_file.GetFileNameExtension();
1763 if (::strcmp(extension.GetCString(), "py") == 0)
1764 basename.resize(basename.length()-3);
1765 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1766 basename.resize(basename.length()-4);
1767
1768 // check if the module is already import-ed
1769 command_stream.Clear();
1770 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1771 int refcount = 0;
1772 // this call will fail if the module does not exist (because the parameter to it is not a string
1773 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00001774 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
1775 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0);
1776 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00001777 {
1778 error.SetErrorString("module already imported");
1779 return false;
1780 }
1781
1782 // now actually do the import
1783 command_stream.Clear();
1784 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafa1f6172011-10-24 17:22:21 +00001785 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL);
Enrico Granata59df36f2011-10-17 21:45:27 +00001786 if (!import_retval)
1787 {
1788 error.SetErrorString("Python import statement failed");
1789 return false;
1790 }
1791
Enrico Granata16376ed2012-02-15 02:34:21 +00001792 // call __lldb_init_module(debugger,dict)
Enrico Granata59df36f2011-10-17 21:45:27 +00001793 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001794 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001795 debugger_sp))
1796 {
Enrico Granata16376ed2012-02-15 02:34:21 +00001797 error.SetErrorString("calling __lldb_init_module failed");
Enrico Granata59df36f2011-10-17 21:45:27 +00001798 return false;
1799 }
1800 return true;
1801 }
1802}
1803
Enrico Granata1328b142012-02-29 03:28:49 +00001804lldb::ScriptInterpreterObjectSP
1805ScriptInterpreterPython::MakeScriptObject (void* object)
1806{
1807 return lldb::ScriptInterpreterObjectSP(new ScriptInterpreterPythonObject(object));
1808}
1809
Enrico Granata6010ace2011-11-07 22:57:04 +00001810ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
1811 ScriptedCommandSynchronicity synchro) :
1812 m_debugger_sp(debugger_sp),
1813 m_synch_wanted(synchro),
1814 m_old_asynch(debugger_sp->GetAsyncExecution())
1815{
1816 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
1817 m_debugger_sp->SetAsyncExecution(false);
1818 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
1819 m_debugger_sp->SetAsyncExecution(true);
1820}
1821
1822ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
1823{
1824 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
1825 m_debugger_sp->SetAsyncExecution(m_old_asynch);
1826}
1827
Enrico Granata59df36f2011-10-17 21:45:27 +00001828bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001829ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1830 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00001831 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001832 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001833 Error& error)
1834{
1835 if (!impl_function)
1836 {
1837 error.SetErrorString("no function to execute");
1838 return false;
1839 }
1840
1841 if (!g_swig_call_command)
1842 {
1843 error.SetErrorString("no helper function to run scripted commands");
1844 return false;
1845 }
1846
Greg Clayton13d24fb2012-01-29 20:56:30 +00001847 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata6010ace2011-11-07 22:57:04 +00001848
1849 if (!debugger_sp.get())
1850 {
1851 error.SetErrorString("invalid Debugger pointer");
1852 return false;
1853 }
Enrico Granatac2a28252011-08-16 16:49:25 +00001854
1855 bool ret_val;
1856
1857 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00001858
Enrico Granatac2a28252011-08-16 16:49:25 +00001859 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001860 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00001861 SynchronicityHandler synch_handler(debugger_sp,
1862 synchronicity);
1863
Enrico Granatac2a28252011-08-16 16:49:25 +00001864 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00001865 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00001866 debugger_sp,
1867 args,
1868 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001869 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001870 }
Enrico Granata6010ace2011-11-07 22:57:04 +00001871
Enrico Granatac2a28252011-08-16 16:49:25 +00001872 if (!ret_val)
1873 error.SetErrorString(err_msg.c_str());
1874 else
1875 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00001876
Enrico Granatac2a28252011-08-16 16:49:25 +00001877 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00001878}
1879
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001880// in Python, a special attribute __doc__ contains the docstring
1881// for an object (function, method, class, ...) if any is defined
1882// Otherwise, the attribute's value is None
1883std::string
1884ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1885{
1886 std::string command(item);
1887 command += ".__doc__";
1888
1889 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1890
1891 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001892 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001893 &result_ptr) && result_ptr)
1894 {
1895 return std::string(result_ptr);
1896 }
1897 else
1898 return std::string("");
1899}
Caroline Tice2ade6112010-11-10 19:18:14 +00001900
Caroline Tice0aa2e552011-01-14 00:29:16 +00001901void
Enrico Granata1328b142012-02-29 03:28:49 +00001902ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback)
Greg Claytone86cbb92011-03-22 01:14:58 +00001903{
1904 g_swig_init_callback = python_swig_init_callback;
Enrico Granata1328b142012-02-29 03:28:49 +00001905 g_swig_breakpoint_callback = LLDBSwigPythonBreakpointCallbackFunction;
1906 g_swig_typescript_callback = LLDBSwigPythonCallTypeScript;
1907 g_swig_synthetic_script = LLDBSwigPythonCreateSyntheticProvider;
1908 g_swig_calc_children = LLDBSwigPython_CalculateNumChildren;
1909 g_swig_get_child_index = LLDBSwigPython_GetChildAtIndex;
1910 g_swig_get_index_child = LLDBSwigPython_GetIndexOfChildWithName;
1911 g_swig_cast_to_sbvalue = LLDBSWIGPython_CastPyObjectToSBValue;
1912 g_swig_update_provider = LLDBSwigPython_UpdateSynthProviderInstance;
1913 g_swig_call_command = LLDBSwigPythonCallCommand;
1914 g_swig_call_module_init = LLDBSwigPythonCallModuleInit;
Greg Claytone86cbb92011-03-22 01:14:58 +00001915}
1916
1917void
1918ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001919{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001920 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1921
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001922 // Python will muck with STDIN terminal state, so save off any current TTY
1923 // settings so we can restore them.
1924 TerminalState stdin_tty_state;
1925 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001926
Caroline Tice9d352ce2011-03-07 23:24:28 +00001927 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001928 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001929
Greg Claytone86cbb92011-03-22 01:14:58 +00001930 // Initialize SWIG after setting up python
1931 assert (g_swig_init_callback != NULL);
1932 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001933
1934 // Update the path python uses to search for modules to include the current directory.
1935
Caroline Ticed4d92832011-06-13 21:33:00 +00001936 PyRun_SimpleString ("import sys");
1937 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001938
1939 // Find the module that owns this code and use that path we get to
1940 // set the sys.path appropriately.
1941
1942 FileSpec file_spec;
1943 char python_dir_path[PATH_MAX];
1944 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1945 {
1946 std::string python_path("sys.path.insert(0,\"");
1947 size_t orig_len = python_path.length();
1948 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1949 {
1950 python_path.append (python_dir_path);
1951 python_path.append ("\")");
1952 PyRun_SimpleString (python_path.c_str());
1953 python_path.resize (orig_len);
1954 }
1955
1956 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1957 {
1958 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1959 {
1960 python_path.append (python_dir_path);
1961 python_path.append ("\")");
1962 PyRun_SimpleString (python_path.c_str());
1963 python_path.resize (orig_len);
1964 }
1965 }
1966 }
1967
Greg Clayton4e651b12012-04-25 00:58:03 +00001968 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 +00001969
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001970 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001971}
1972
Greg Claytone86cbb92011-03-22 01:14:58 +00001973//void
1974//ScriptInterpreterPython::Terminate ()
1975//{
1976// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1977// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1978// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1979// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1980// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1981// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1982// // within Py_Finalize, which results in a seg fault.
1983// //
1984// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1985// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1986// // process exits).
1987// //
1988//// Py_Finalize ();
1989//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00001990
1991#endif // #ifdef LLDB_DISABLE_PYTHON