blob: 79089c56648e8aeb7b09041aaa9c822f7425fd1e [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"
Johnny Chenf3ec4612012-08-09 23:09:42 +000034#include "lldb/Breakpoint/WatchpointOptions.h"
Chris Lattner24943d22010-06-08 16:52:24 +000035#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000036#include "lldb/Core/Timer.h"
37#include "lldb/Host/Host.h"
38#include "lldb/Interpreter/CommandInterpreter.h"
39#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton5144f382010-10-07 17:14:24 +000040#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000041
Chris Lattner24943d22010-06-08 16:52:24 +000042using namespace lldb;
43using namespace lldb_private;
44
Greg Claytone86cbb92011-03-22 01:14:58 +000045
46static ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL;
47static ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL;
Johnny Chenf3ec4612012-08-09 23:09:42 +000048static ScriptInterpreter::SWIGWatchpointCallbackFunction g_swig_watchpoint_callback = NULL;
Enrico Granataf7a9b142011-07-15 02:26:42 +000049static ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL;
Enrico Granata9ae7cef2011-07-24 00:14:56 +000050static ScriptInterpreter::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = NULL;
51static ScriptInterpreter::SWIGPythonCalculateNumChildren g_swig_calc_children = NULL;
52static ScriptInterpreter::SWIGPythonGetChildAtIndex g_swig_get_child_index = NULL;
53static ScriptInterpreter::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = NULL;
54static ScriptInterpreter::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = NULL;
Enrico Granata979e20d2011-07-29 19:53:35 +000055static ScriptInterpreter::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = NULL;
Enrico Granatac2a28252011-08-16 16:49:25 +000056static ScriptInterpreter::SWIGPythonCallCommand g_swig_call_command = NULL;
Enrico Granata59df36f2011-10-17 21:45:27 +000057static ScriptInterpreter::SWIGPythonCallModuleInit g_swig_call_module_init = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +000058
Enrico Granata1328b142012-02-29 03:28:49 +000059// these are the Pythonic implementations of the required callbacks
60// these are scripting-language specific, which is why they belong here
61// we still need to use function pointers to them instead of relying
62// on linkage-time resolution because the SWIG stuff and this file
63// get built at different times
64extern "C" bool
65LLDBSwigPythonBreakpointCallbackFunction
66(
67 const char *python_function_name,
68 const char *session_dictionary_name,
69 const lldb::StackFrameSP& sb_frame,
70 const lldb::BreakpointLocationSP& sb_bp_loc
71 );
72
73extern "C" bool
Johnny Chenf3ec4612012-08-09 23:09:42 +000074LLDBSwigPythonWatchpointCallbackFunction
75(
76 const char *python_function_name,
77 const char *session_dictionary_name,
78 const lldb::StackFrameSP& sb_frame,
79 const lldb::WatchpointSP& sb_wp
80 );
81
82extern "C" bool
Enrico Granata1328b142012-02-29 03:28:49 +000083LLDBSwigPythonCallTypeScript
84(
85 const char *python_function_name,
86 void *session_dictionary,
87 const lldb::ValueObjectSP& valobj_sp,
88 void** pyfunct_wrapper,
89 std::string& retval
90 );
91
92extern "C" void*
93LLDBSwigPythonCreateSyntheticProvider
94(
95 const std::string python_class_name,
96 const char *session_dictionary_name,
97 const lldb::ValueObjectSP& valobj_sp
98 );
99
100
101extern "C" uint32_t LLDBSwigPython_CalculateNumChildren (void *implementor);
102extern "C" void* LLDBSwigPython_GetChildAtIndex (void *implementor, uint32_t idx);
103extern "C" int LLDBSwigPython_GetIndexOfChildWithName (void *implementor, const char* child_name);
104extern "C" void* LLDBSWIGPython_CastPyObjectToSBValue (void* data);
Enrico Granatacf09f882012-03-19 22:58:49 +0000105extern "C" bool LLDBSwigPython_UpdateSynthProviderInstance (void* implementor);
Enrico Granata1328b142012-02-29 03:28:49 +0000106
107extern "C" bool LLDBSwigPythonCallCommand
108(
109 const char *python_function_name,
110 const char *session_dictionary_name,
111 lldb::DebuggerSP& debugger,
112 const char* args,
113 std::string& err_msg,
114 lldb_private::CommandReturnObject& cmd_retobj
115 );
116
117extern "C" bool LLDBSwigPythonCallModuleInit
118(
119 const std::string python_module_name,
120 const char *session_dictionary_name,
121 lldb::DebuggerSP& debugger
122 );
123
Chris Lattner24943d22010-06-08 16:52:24 +0000124static int
125_check_and_flush (FILE *stream)
126{
127 int prev_fail = ferror (stream);
128 return fflush (stream) || prev_fail ? EOF : 0;
129}
130
Enrico Granatafa1f6172011-10-24 17:22:21 +0000131ScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *py_interpreter,
132 uint16_t on_entry,
133 uint16_t on_leave,
134 FILE* wait_msg_handle) :
135 m_need_session( (on_leave & TearDownSession) == TearDownSession ),
Enrico Granatafa1f6172011-10-24 17:22:21 +0000136 m_python_interpreter(py_interpreter),
137 m_tmp_fh(wait_msg_handle)
Enrico Granata91544802011-09-06 19:20:51 +0000138{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000139 if (m_python_interpreter && !m_tmp_fh)
140 m_tmp_fh = (m_python_interpreter->m_dbg_stdout ? m_python_interpreter->m_dbg_stdout : stdout);
Johnny Chen8165d432012-08-18 04:14:54 +0000141
142 DoAcquireLock();
Enrico Granatafa1f6172011-10-24 17:22:21 +0000143 if ( (on_entry & InitSession) == InitSession )
144 DoInitSession();
145}
146
147bool
148ScriptInterpreterPython::Locker::DoAcquireLock()
149{
Johnny Chen8165d432012-08-18 04:14:54 +0000150 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE));
151 m_GILState = PyGILState_Ensure();
152 if (log)
153 log->Printf("Ensured PyGILState. Previous state = %slocked\n", m_GILState == PyGILState_UNLOCKED ? "un" : "");
Enrico Granatafa1f6172011-10-24 17:22:21 +0000154 return true;
155}
156
157bool
158ScriptInterpreterPython::Locker::DoInitSession()
159{
160 if (!m_python_interpreter)
161 return false;
162 m_python_interpreter->EnterSession ();
163 return true;
164}
165
166bool
167ScriptInterpreterPython::Locker::DoFreeLock()
168{
Johnny Chen8165d432012-08-18 04:14:54 +0000169 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE));
170 if (log)
171 log->Printf("Releasing PyGILState. Returning to state = %slocked\n", m_GILState == PyGILState_UNLOCKED ? "un" : "");
172 PyGILState_Release(m_GILState);
Enrico Granatafa1f6172011-10-24 17:22:21 +0000173 return true;
174}
175
176bool
177ScriptInterpreterPython::Locker::DoTearDownSession()
178{
179 if (!m_python_interpreter)
180 return false;
181 m_python_interpreter->LeaveSession ();
182 return true;
Enrico Granata91544802011-09-06 19:20:51 +0000183}
184
185ScriptInterpreterPython::Locker::~Locker()
186{
187 if (m_need_session)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000188 DoTearDownSession();
Johnny Chen8165d432012-08-18 04:14:54 +0000189 DoFreeLock();
Enrico Granata91544802011-09-06 19:20:51 +0000190}
191
Enrico Granatadba1de82012-03-27 02:35:13 +0000192class ForceDisableSyntheticChildren
193{
194public:
195 ForceDisableSyntheticChildren (Target* target) :
196 m_target(target)
197 {
198 m_old_value = target->GetSuppressSyntheticValue();
199 target->SetSuppressSyntheticValue(true);
200 }
201 ~ForceDisableSyntheticChildren ()
202 {
203 m_target->SetSuppressSyntheticValue(m_old_value);
204 }
205private:
206 Target* m_target;
207 bool m_old_value;
208};
209
Enrico Granataa1ba3142012-06-07 00:17:18 +0000210ScriptInterpreterPython::PythonInputReaderManager::PythonInputReaderManager (ScriptInterpreterPython *interpreter) :
211m_interpreter(interpreter),
212m_debugger_sp(),
213m_reader_sp(),
214m_error(false)
215{
216 if (m_interpreter == NULL)
217 {
218 m_error = true;
219 return;
220 }
221
222 m_debugger_sp = m_interpreter->GetCommandInterpreter().GetDebugger().shared_from_this();
223
224 if (!m_debugger_sp)
225 {
226 m_error = true;
227 return;
228 }
229
230 m_reader_sp = InputReaderSP(new InputReader(*m_debugger_sp.get()));
231
232 if (!m_reader_sp)
233 {
234 m_error = true;
235 return;
236 }
237
238 Error error (m_reader_sp->Initialize (ScriptInterpreterPython::PythonInputReaderManager::InputReaderCallback,
239 m_interpreter, // baton
240 eInputReaderGranularityLine, // token size, to pass to callback function
241 NULL, // end token
242 NULL, // prompt
243 true)); // echo input
244 if (error.Fail())
245 m_error = true;
246 else
247 {
248 m_debugger_sp->PushInputReader (m_reader_sp);
249 m_interpreter->m_embedded_thread_input_reader_sp = m_reader_sp;
250 }
251}
252
253ScriptInterpreterPython::PythonInputReaderManager::~PythonInputReaderManager()
254{
Johnny Chen8121d7a2012-08-17 23:44:35 +0000255 // Nothing to do if either m_interpreter or m_reader_sp is invalid.
256 if (!m_interpreter || !m_reader_sp)
257 return;
258
259 m_reader_sp->SetIsDone (true);
260 if (m_debugger_sp)
261 m_debugger_sp->PopInputReader(m_reader_sp);
262
263 // Only mess with m_interpreter's counterpart if, indeed, they are the same object.
264 if (m_reader_sp.get() == m_interpreter->m_embedded_thread_input_reader_sp.get())
Enrico Granataa1ba3142012-06-07 00:17:18 +0000265 {
Johnny Chen8121d7a2012-08-17 23:44:35 +0000266 m_interpreter->m_embedded_thread_pty.CloseSlaveFileDescriptor();
Enrico Granataa1ba3142012-06-07 00:17:18 +0000267 m_interpreter->m_embedded_thread_input_reader_sp.reset();
Johnny Chen8121d7a2012-08-17 23:44:35 +0000268 }
Enrico Granataa1ba3142012-06-07 00:17:18 +0000269}
270
271size_t
272ScriptInterpreterPython::PythonInputReaderManager::InputReaderCallback
273(
274 void *baton,
275 InputReader &reader,
276 InputReaderAction notification,
277 const char *bytes,
278 size_t bytes_len
279 )
280{
281 lldb::thread_t embedded_interpreter_thread;
282 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
283
284 if (baton == NULL)
285 return 0;
286
287 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
288
289 if (script_interpreter->m_script_lang != eScriptLanguagePython)
290 return 0;
291
292 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
293
294 switch (notification)
295 {
296 case eInputReaderActivate:
297 {
298 // Save terminal settings if we can
299 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
300 if (input_fd == File::kInvalidDescriptor)
301 input_fd = STDIN_FILENO;
302
303 script_interpreter->SaveTerminalState(input_fd);
Johnny Chen8165d432012-08-18 04:14:54 +0000304
Enrico Granataa1ba3142012-06-07 00:17:18 +0000305 char error_str[1024];
Johnny Chen8121d7a2012-08-17 23:44:35 +0000306 if (script_interpreter->m_embedded_thread_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
Enrico Granataa1ba3142012-06-07 00:17:18 +0000307 sizeof(error_str)))
308 {
309 if (log)
310 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
Johnny Chen8121d7a2012-08-17 23:44:35 +0000311 script_interpreter->m_embedded_thread_pty.GetMasterFileDescriptor());
Enrico Granataa1ba3142012-06-07 00:17:18 +0000312 {
313 StreamString run_string;
314 char error_str[1024];
Johnny Chen8121d7a2012-08-17 23:44:35 +0000315 const char *pty_slave_name = script_interpreter->m_embedded_thread_pty.GetSlaveName (error_str, sizeof (error_str));
Enrico Granataca2c7072012-07-31 16:58:12 +0000316 if (pty_slave_name != NULL && PyThreadState_GetDict() != NULL)
Enrico Granataa1ba3142012-06-07 00:17:18 +0000317 {
Johnny Chen8165d432012-08-18 04:14:54 +0000318 ScriptInterpreterPython::Locker locker(script_interpreter,
319 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
320 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Enrico Granataa1ba3142012-06-07 00:17:18 +0000321 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
322 PyRun_SimpleString (run_string.GetData());
323 run_string.Clear ();
324
325 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
326 PyRun_SimpleString (run_string.GetData());
327 run_string.Clear ();
328
329 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
330 PyRun_SimpleString (run_string.GetData());
331 run_string.Clear ();
332
333 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
334 pty_slave_name);
335 PyRun_SimpleString (run_string.GetData());
336 run_string.Clear ();
337 }
338 }
339 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.noninteractive-python>",
340 ScriptInterpreterPython::PythonInputReaderManager::RunPythonInputReader,
341 script_interpreter, NULL);
342 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
343 {
344 if (log)
345 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
346 Error detach_error;
347 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
348 }
349 else
350 {
351 if (log)
352 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, failed in creating thread");
353 reader.SetIsDone (true);
354 }
355 }
356 else
357 {
358 if (log)
359 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, failed to open master pty ");
360 reader.SetIsDone (true);
361 }
362 }
363 break;
364
365 case eInputReaderDeactivate:
366 // When another input reader is pushed, don't leave the session...
367 //script_interpreter->LeaveSession ();
368 break;
369
370 case eInputReaderReactivate:
371 {
Johnny Chen8165d432012-08-18 04:14:54 +0000372 ScriptInterpreterPython::Locker locker(script_interpreter,
373 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
374 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Enrico Granataa1ba3142012-06-07 00:17:18 +0000375 }
376 break;
377
378 case eInputReaderAsynchronousOutputWritten:
379 break;
380
381 case eInputReaderInterrupt:
382 reader.SetIsDone(true);
383 break;
384
385 case eInputReaderEndOfFile:
386 reader.SetIsDone(true);
387 break;
388
389 case eInputReaderGotToken:
Johnny Chen8121d7a2012-08-17 23:44:35 +0000390 if (script_interpreter->m_embedded_thread_pty.GetMasterFileDescriptor() != -1)
Enrico Granataa1ba3142012-06-07 00:17:18 +0000391 {
392 if (log)
393 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
394 bytes_len);
395 if (bytes && bytes_len)
Johnny Chen8121d7a2012-08-17 23:44:35 +0000396 ::write (script_interpreter->m_embedded_thread_pty.GetMasterFileDescriptor(), bytes, bytes_len);
397 ::write (script_interpreter->m_embedded_thread_pty.GetMasterFileDescriptor(), "\n", 1);
Enrico Granataa1ba3142012-06-07 00:17:18 +0000398 }
399 else
400 {
401 if (log)
402 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
403 bytes,
404 bytes_len);
405 reader.SetIsDone (true);
406 }
407
408 break;
409
410 case eInputReaderDone:
411 {
412 StreamString run_string;
413 char error_str[1024];
Johnny Chen8121d7a2012-08-17 23:44:35 +0000414 const char *pty_slave_name = script_interpreter->m_embedded_thread_pty.GetSlaveName (error_str, sizeof (error_str));
Enrico Granataca2c7072012-07-31 16:58:12 +0000415 if (pty_slave_name != NULL && PyThreadState_GetDict() != NULL)
Enrico Granataa1ba3142012-06-07 00:17:18 +0000416 {
Johnny Chen8165d432012-08-18 04:14:54 +0000417 ScriptInterpreterPython::Locker locker(script_interpreter,
418 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
419 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Enrico Granataa1ba3142012-06-07 00:17:18 +0000420 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
421 PyRun_SimpleString (run_string.GetData());
422 run_string.Clear();
423
424 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
425 PyRun_SimpleString (run_string.GetData());
426 run_string.Clear();
427 }
428 }
429
430 // Restore terminal settings if they were validly saved
431 if (log)
432 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Done, closing down input reader.");
433
434 script_interpreter->RestoreTerminalState ();
435
Johnny Chen8121d7a2012-08-17 23:44:35 +0000436 script_interpreter->m_embedded_thread_pty.CloseMasterFileDescriptor();
Enrico Granataa1ba3142012-06-07 00:17:18 +0000437 break;
438 }
439
440 return bytes_len;
441}
442
Greg Clayton63094e02010-06-23 01:19:29 +0000443ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000444 ScriptInterpreter (interpreter, eScriptLanguagePython),
Johnny Chen8121d7a2012-08-17 23:44:35 +0000445 m_embedded_thread_pty (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000446 m_embedded_python_pty (),
447 m_embedded_thread_input_reader_sp (),
Johnny Chen8121d7a2012-08-17 23:44:35 +0000448 m_embedded_python_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +0000449 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000450 m_new_sysout (NULL),
Johnny Chenc65046d2012-03-08 20:53:04 +0000451 m_old_sysout (NULL),
452 m_old_syserr (NULL),
Enrico Granata400105d2012-03-06 23:42:15 +0000453 m_run_one_line (NULL),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000454 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000455 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000456 m_session_is_active (false),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000457 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000458{
459
Greg Clayton7c330d62011-01-27 01:01:10 +0000460 static int g_initialized = false;
461
462 if (!g_initialized)
463 {
464 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000465 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000466 }
467
Caroline Tice0aa2e552011-01-14 00:29:16 +0000468 m_dictionary_name.append("_dict");
469 StreamString run_string;
470 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
Johnny Chen8165d432012-08-18 04:14:54 +0000471
472 Locker locker(this,
473 ScriptInterpreterPython::Locker::AcquireLock,
474 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000475 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000476
Caroline Tice0aa2e552011-01-14 00:29:16 +0000477 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000478
479 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
480 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
481 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
482 // call to Debugger::Terminate is made, the ref-count has the correct value.
483 //
484 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
485 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000486
Caroline Tice0aa2e552011-01-14 00:29:16 +0000487 int old_count = Debugger::TestDebuggerRefCount();
Greg Claytonb302dff2012-02-01 08:09:32 +0000488
Greg Clayton4e651b12012-04-25 00:58:03 +0000489 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 +0000490 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000491
Enrico Granata8f84cfb2012-02-23 23:10:03 +0000492 // WARNING: temporary code that loads Cocoa formatters - this should be done on a per-platform basis rather than loading the whole set
493 // and letting the individual formatter classes exploit APIs to check whether they can/cannot do their task
494 run_string.Clear();
Greg Clayton4e651b12012-04-25 00:58:03 +0000495 //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 +0000496 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 +0000497 PyRun_SimpleString (run_string.GetData());
Greg Claytonb302dff2012-02-01 08:09:32 +0000498
Caroline Tice0aa2e552011-01-14 00:29:16 +0000499 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000500
Caroline Tice0aa2e552011-01-14 00:29:16 +0000501 if (new_count > old_count)
502 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000503
Caroline Tice0aa2e552011-01-14 00:29:16 +0000504 run_string.Clear();
Greg Clayton444e35b2011-10-19 18:09:39 +0000505 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000506 interpreter.GetDebugger().GetID());
507 PyRun_SimpleString (run_string.GetData());
508
509 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000510 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000511 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000512 }
Chris Lattner24943d22010-06-08 16:52:24 +0000513}
514
515ScriptInterpreterPython::~ScriptInterpreterPython ()
516{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000517 Debugger &debugger = GetCommandInterpreter().GetDebugger();
518
519 if (m_embedded_thread_input_reader_sp.get() != NULL)
520 {
521 m_embedded_thread_input_reader_sp->SetIsDone (true);
Johnny Chen8121d7a2012-08-17 23:44:35 +0000522 m_embedded_thread_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000523 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000524 debugger.PopInputReader (reader_sp);
Johnny Chen8121d7a2012-08-17 23:44:35 +0000525 m_embedded_thread_input_reader_sp.reset();
526 }
527
528 if (m_embedded_python_input_reader_sp.get() != NULL)
529 {
530 m_embedded_python_input_reader_sp->SetIsDone (true);
531 m_embedded_python_pty.CloseSlaveFileDescriptor();
532 const InputReaderSP reader_sp = m_embedded_python_input_reader_sp;
533 debugger.PopInputReader (reader_sp);
534 m_embedded_python_input_reader_sp.reset();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000535 }
536
537 if (m_new_sysout)
538 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000539 Locker locker(this,
540 ScriptInterpreterPython::Locker::AcquireLock,
541 ScriptInterpreterPython::Locker::FreeLock);
542 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000543 }
Chris Lattner24943d22010-06-08 16:52:24 +0000544}
545
Caroline Tice0aa2e552011-01-14 00:29:16 +0000546void
547ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
548{
549 if (fh == NULL)
550 return;
551
552 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000553
Johnny Chenc65046d2012-03-08 20:53:04 +0000554 Locker locker(this,
555 ScriptInterpreterPython::Locker::AcquireLock,
556 ScriptInterpreterPython::Locker::FreeAcquiredLock);
557
Enrico Granata91544802011-09-06 19:20:51 +0000558 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000559}
560
561void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000562ScriptInterpreterPython::SaveTerminalState (int fd)
563{
564 // Python mucks with the terminal state of STDIN. If we can possibly avoid
565 // this by setting the file handles up correctly prior to entering the
566 // interpreter we should. For now we save and restore the terminal state
567 // on the input file handle.
568 m_terminal_state.Save (fd, false);
569}
570
571void
572ScriptInterpreterPython::RestoreTerminalState ()
573{
574 // Python mucks with the terminal state of STDIN. If we can possibly avoid
575 // this by setting the file handles up correctly prior to entering the
576 // interpreter we should. For now we save and restore the terminal state
577 // on the input file handle.
578 m_terminal_state.Restore();
579}
580
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000581void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000582ScriptInterpreterPython::LeaveSession ()
583{
Enrico Granata7aa754c2012-04-04 17:31:29 +0000584 // checking that we have a valid thread state - since we use our own threading and locking
585 // in some (rare) cases during cleanup Python may end up believing we have no thread state
586 // and PyImport_AddModule will crash if that is the case - since that seems to only happen
587 // when destroying the SBDebugger, we can make do without clearing up stdout and stderr
Johnny Chen2b536952012-05-04 20:37:11 +0000588
589 // rdar://problem/11292882
590 // When the current thread state is NULL, PyThreadState_Get() issues a fatal error.
591 if (PyThreadState_GetDict())
Johnny Chen41641f92012-02-29 01:52:13 +0000592 {
Enrico Granata7aa754c2012-04-04 17:31:29 +0000593 PyObject *sysmod = PyImport_AddModule ("sys");
594 PyObject *sysdict = PyModule_GetDict (sysmod);
595
596 if (m_new_sysout && sysmod && sysdict)
597 {
598 if (m_old_sysout)
599 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_old_sysout);
600 if (m_old_syserr)
601 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_old_syserr);
602 }
Johnny Chen41641f92012-02-29 01:52:13 +0000603 }
604
Caroline Tice0aa2e552011-01-14 00:29:16 +0000605 m_session_is_active = false;
606}
607
608void
609ScriptInterpreterPython::EnterSession ()
610{
611 // If we have already entered the session, without having officially 'left' it, then there is no need to
612 // 'enter' it again.
613
614 if (m_session_is_active)
615 return;
616
617 m_session_is_active = true;
618
Caroline Tice202f6b82011-01-17 21:55:19 +0000619 StreamString run_string;
620
Greg Clayton2fecc452012-01-28 02:11:02 +0000621 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %llu", m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
622 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)", GetCommandInterpreter().GetDebugger().GetID());
623 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
624 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
625 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
626 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
627 // Make sure STDIN is closed since when we run this as an embedded
628 // interpreter we don't want someone to call "line = sys.stdin.readline()"
629 // and lock up. We don't have multiple windows and when the interpreter is
630 // embedded we don't know we should be feeding input to the embedded
631 // interpreter or to the python sys.stdin. We also don't want to let python
632 // play with the real stdin from this process, so we need to close it...
Greg Clayton3eeaf6e2012-02-03 01:30:30 +0000633 //run_string.PutCString ("; sys.stdin.close()");
Greg Clayton2fecc452012-01-28 02:11:02 +0000634 run_string.PutCString ("')");
Caroline Tice0aa2e552011-01-14 00:29:16 +0000635
Caroline Tice6af65cb2011-05-03 21:21:50 +0000636 PyRun_SimpleString (run_string.GetData());
637 run_string.Clear();
Johnny Chen41641f92012-02-29 01:52:13 +0000638
Caroline Tice0aa2e552011-01-14 00:29:16 +0000639 PyObject *sysmod = PyImport_AddModule ("sys");
640 PyObject *sysdict = PyModule_GetDict (sysmod);
Johnny Chen41641f92012-02-29 01:52:13 +0000641
Greg Clayton2fecc452012-01-28 02:11:02 +0000642 if (m_new_sysout && sysmod && sysdict)
643 {
Johnny Chen41641f92012-02-29 01:52:13 +0000644 m_old_sysout = PyDict_GetItemString(sysdict, "stdout");
645 m_old_syserr = PyDict_GetItemString(sysdict, "stderr");
Johnny Chenc65046d2012-03-08 20:53:04 +0000646 if (m_new_sysout)
647 {
648 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
649 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
650 }
Greg Clayton2fecc452012-01-28 02:11:02 +0000651 }
Johnny Chen41641f92012-02-29 01:52:13 +0000652
Caroline Tice0aa2e552011-01-14 00:29:16 +0000653 if (PyErr_Occurred())
654 PyErr_Clear ();
Greg Clayton2fecc452012-01-28 02:11:02 +0000655}
Caroline Tice0aa2e552011-01-14 00:29:16 +0000656
Enrico Granata400105d2012-03-06 23:42:15 +0000657static PyObject*
658FindSessionDictionary (const char* dict_name)
659{
660 static std::map<ConstString,PyObject*> g_dict_map;
661
662 ConstString dict(dict_name);
663
664 std::map<ConstString,PyObject*>::iterator iter = g_dict_map.find(dict);
665
666 if (iter != g_dict_map.end())
667 return iter->second;
668
669 PyObject *main_mod = PyImport_AddModule ("__main__");
670 if (main_mod != NULL)
671 {
672 PyObject *main_dict = PyModule_GetDict (main_mod);
673 if ((main_dict != NULL)
674 && PyDict_Check (main_dict))
675 {
676 // Go through the main dictionary looking for the correct python script interpreter dictionary
677 PyObject *key, *value;
678 Py_ssize_t pos = 0;
679
680 while (PyDict_Next (main_dict, &pos, &key, &value))
681 {
682 // We have stolen references to the key and value objects in the dictionary; we need to increment
683 // them now so that Python's garbage collector doesn't collect them out from under us.
684 Py_INCREF (key);
685 Py_INCREF (value);
686 if (strcmp (PyString_AsString (key), dict_name) == 0)
687 {
688 g_dict_map[dict] = value;
689 return value;
690 }
691 }
692 }
693 }
694 return NULL;
695}
696
697static std::string
698GenerateUniqueName (const char* base_name_wanted,
699 uint32_t& functions_counter,
700 void* name_token = NULL)
701{
702 StreamString sstr;
703
704 if (!base_name_wanted)
705 return std::string();
706
707 if (!name_token)
708 sstr.Printf ("%s_%d", base_name_wanted, functions_counter++);
709 else
710 sstr.Printf ("%s_%p", base_name_wanted, name_token);
711
712 return sstr.GetString();
713}
714
Johnny Chen60dde642010-07-30 22:33:14 +0000715bool
Enrico Granataa1ba3142012-06-07 00:17:18 +0000716ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result, bool enable_io)
Chris Lattner24943d22010-06-08 16:52:24 +0000717{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000718 if (!m_valid_session)
719 return false;
720
Caroline Tice4a461da2011-01-14 21:09:29 +0000721 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
722 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
723 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
724 // method to pass the command string directly down to Python.
725
Enrico Granatafa1f6172011-10-24 17:22:21 +0000726 Locker locker(this,
727 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
728 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000729
730 bool success = false;
731
Greg Clayton63094e02010-06-23 01:19:29 +0000732 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000733 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000734 // Find the correct script interpreter dictionary in the main module.
Enrico Granata400105d2012-03-06 23:42:15 +0000735 PyObject *script_interpreter_dict = FindSessionDictionary(m_dictionary_name.c_str());
736 if (script_interpreter_dict != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000737 {
Enrico Granata400105d2012-03-06 23:42:15 +0000738 PyObject *pfunc = (PyObject*)m_run_one_line;
Greg Clayton6f2f0ab2012-04-25 01:49:50 +0000739 PyObject *pmod = PyImport_AddModule ("lldb.embedded_interpreter");
Enrico Granata400105d2012-03-06 23:42:15 +0000740 if (pmod != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000741 {
Enrico Granata400105d2012-03-06 23:42:15 +0000742 PyObject *pmod_dict = PyModule_GetDict (pmod);
743 if ((pmod_dict != NULL)
744 && PyDict_Check (pmod_dict))
Caroline Tice4a461da2011-01-14 21:09:29 +0000745 {
Enrico Granata400105d2012-03-06 23:42:15 +0000746 if (!pfunc)
Caroline Tice4a461da2011-01-14 21:09:29 +0000747 {
748 PyObject *key, *value;
749 Py_ssize_t pos = 0;
750
751 while (PyDict_Next (pmod_dict, &pos, &key, &value))
752 {
753 Py_INCREF (key);
754 Py_INCREF (value);
755 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
756 {
757 pfunc = value;
758 break;
759 }
760 }
Enrico Granata400105d2012-03-06 23:42:15 +0000761 m_run_one_line = pfunc;
762 }
763
764 if (pfunc && PyCallable_Check (pfunc))
765 {
766 PyObject *pargs = Py_BuildValue("(Os)",script_interpreter_dict,command);
767 if (pargs != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000768 {
Enrico Granataa1ba3142012-06-07 00:17:18 +0000769 PyObject *pvalue = NULL;
770 { // scope for PythonInputReaderManager
771 PythonInputReaderManager py_input(enable_io ? this : NULL);
772 pvalue = PyObject_CallObject (pfunc, pargs);
773 }
Enrico Granata400105d2012-03-06 23:42:15 +0000774 Py_DECREF (pargs);
775 if (pvalue != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000776 {
Enrico Granata400105d2012-03-06 23:42:15 +0000777 Py_DECREF (pvalue);
778 success = true;
779 }
780 else if (PyErr_Occurred ())
781 {
782 PyErr_Print();
783 PyErr_Clear();
Caroline Tice4a461da2011-01-14 21:09:29 +0000784 }
785 }
786 }
787 }
Caroline Tice4a461da2011-01-14 21:09:29 +0000788 }
Enrico Granata400105d2012-03-06 23:42:15 +0000789 Py_INCREF (script_interpreter_dict);
Caroline Tice4a461da2011-01-14 21:09:29 +0000790 }
Greg Clayton63094e02010-06-23 01:19:29 +0000791
Caroline Tice4a461da2011-01-14 21:09:29 +0000792 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000793 return true;
794
795 // The one-liner failed. Append the error message.
796 if (result)
797 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
798 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000799 }
Johnny Chen60dde642010-07-30 22:33:14 +0000800
801 if (result)
802 result->AppendError ("empty command passed to python\n");
803 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000804}
805
Chris Lattner24943d22010-06-08 16:52:24 +0000806size_t
807ScriptInterpreterPython::InputReaderCallback
808(
809 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000810 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000811 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000812 const char *bytes,
813 size_t bytes_len
814)
815{
Caroline Tice2ade6112010-11-10 19:18:14 +0000816 lldb::thread_t embedded_interpreter_thread;
817 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
818
Chris Lattner24943d22010-06-08 16:52:24 +0000819 if (baton == NULL)
820 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000821
822 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000823
Caroline Tice0aa2e552011-01-14 00:29:16 +0000824 if (script_interpreter->m_script_lang != eScriptLanguagePython)
825 return 0;
826
Caroline Tice892fadd2011-06-16 16:27:19 +0000827 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
828 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
829
Chris Lattner24943d22010-06-08 16:52:24 +0000830 switch (notification)
831 {
832 case eInputReaderActivate:
833 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000834 if (!batch_mode)
835 {
836 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
837 out_stream->Flush();
838 }
Greg Clayton58928562011-02-09 01:08:52 +0000839
Chris Lattner24943d22010-06-08 16:52:24 +0000840 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000841 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
842 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000843 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000844
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000845 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000846
Caroline Tice202f6b82011-01-17 21:55:19 +0000847 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000848 ScriptInterpreterPython::Locker locker(script_interpreter,
849 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
850 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000851 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000852
Caroline Tice2ade6112010-11-10 19:18:14 +0000853 char error_str[1024];
854 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
855 sizeof(error_str)))
856 {
857 if (log)
858 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
859 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
860 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
861 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
862 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000863 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000864 {
865 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000866 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000867 Error detach_error;
868 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
869 }
870 else
871 {
872 if (log)
873 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
874 reader.SetIsDone (true);
875 }
876 }
877 else
878 {
879 if (log)
880 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
881 reader.SetIsDone (true);
882 }
Chris Lattner24943d22010-06-08 16:52:24 +0000883 }
884 break;
885
886 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000887 // When another input reader is pushed, don't leave the session...
888 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000889 break;
890
891 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000892 {
Johnny Chen8165d432012-08-18 04:14:54 +0000893 ScriptInterpreterPython::Locker locker(script_interpreter,
894 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
895 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000896 }
Chris Lattner24943d22010-06-08 16:52:24 +0000897 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000898
Caroline Tice4a348082011-05-02 20:41:46 +0000899 case eInputReaderAsynchronousOutputWritten:
900 break;
901
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000902 case eInputReaderInterrupt:
903 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
904 break;
905
906 case eInputReaderEndOfFile:
907 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
908 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000909
910 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000911 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000912 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000913 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000914 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000915 bytes_len);
916 if (bytes && bytes_len)
917 {
918 if ((int) bytes[0] == 4)
919 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
920 else
921 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
922 }
923 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000924 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000925 else
926 {
927 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000928 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000929 bytes,
930 bytes_len);
931 reader.SetIsDone (true);
932 }
933
Chris Lattner24943d22010-06-08 16:52:24 +0000934 break;
935
936 case eInputReaderDone:
Johnny Chen8165d432012-08-18 04:14:54 +0000937 {
938 Locker locker(script_interpreter,
939 ScriptInterpreterPython::Locker::AcquireLock,
940 ScriptInterpreterPython::Locker::FreeAcquiredLock);
941 script_interpreter->LeaveSession ();
942 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000943
Chris Lattner24943d22010-06-08 16:52:24 +0000944 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000945 if (log)
946 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000947
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000948 script_interpreter->RestoreTerminalState ();
949
Caroline Tice2ade6112010-11-10 19:18:14 +0000950 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000951 break;
952 }
953
954 return bytes_len;
955}
956
957
958void
Greg Clayton238c0a12010-09-18 01:14:36 +0000959ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000960{
961 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
962
Caroline Tice0aa2e552011-01-14 00:29:16 +0000963 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000964
965 // At the moment, the only time the debugger does not have an input file handle is when this is called
966 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
967 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
968 // do it.
969
Greg Clayton58928562011-02-09 01:08:52 +0000970 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000971 return;
972
Greg Clayton63094e02010-06-23 01:19:29 +0000973 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000974 if (reader_sp)
975 {
976 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
977 this, // baton
978 eInputReaderGranularityLine, // token size, to pass to callback function
979 NULL, // end token
980 NULL, // prompt
981 true)); // echo input
982
983 if (error.Success())
984 {
Greg Clayton63094e02010-06-23 01:19:29 +0000985 debugger.PushInputReader (reader_sp);
Johnny Chen8121d7a2012-08-17 23:44:35 +0000986 m_embedded_python_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000987 }
988 }
989}
990
991bool
992ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000993 ScriptInterpreter::ScriptReturnType return_type,
Enrico Granataa1ba3142012-06-07 00:17:18 +0000994 void *ret_value,
995 bool enable_io)
Chris Lattner24943d22010-06-08 16:52:24 +0000996{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000997
Enrico Granatafa1f6172011-10-24 17:22:21 +0000998 Locker locker(this,
999 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1000 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001001
Chris Lattner24943d22010-06-08 16:52:24 +00001002 PyObject *py_return = NULL;
1003 PyObject *mainmod = PyImport_AddModule ("__main__");
1004 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001005 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001006 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +00001007 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001008 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001009 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001010
Enrico Granata400105d2012-03-06 23:42:15 +00001011 locals = FindSessionDictionary(m_dictionary_name.c_str());
1012
Caroline Tice0aa2e552011-01-14 00:29:16 +00001013 if (locals == NULL)
1014 {
1015 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
1016 should_decrement_locals = true;
1017 }
1018
1019 if (locals == NULL)
1020 {
1021 locals = globals;
1022 should_decrement_locals = false;
1023 }
1024
1025 py_error = PyErr_Occurred();
1026 if (py_error != NULL)
1027 PyErr_Clear();
1028
Chris Lattner24943d22010-06-08 16:52:24 +00001029 if (in_string != NULL)
1030 {
Enrico Granataa1ba3142012-06-07 00:17:18 +00001031 { // scope for PythonInputReaderManager
1032 PythonInputReaderManager py_input(enable_io ? this : NULL);
1033 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
1034 if (py_return == NULL)
1035 {
1036 py_error = PyErr_Occurred ();
1037 if (py_error != NULL)
1038 PyErr_Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +00001039
Enrico Granataa1ba3142012-06-07 00:17:18 +00001040 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
1041 }
Chris Lattner24943d22010-06-08 16:52:24 +00001042 }
1043
Caroline Tice0aa2e552011-01-14 00:29:16 +00001044 if (locals != NULL
1045 && should_decrement_locals)
1046 Py_DECREF (locals);
1047
Chris Lattner24943d22010-06-08 16:52:24 +00001048 if (py_return != NULL)
1049 {
1050 switch (return_type)
1051 {
Enrico Granata59df36f2011-10-17 21:45:27 +00001052 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +00001053 {
1054 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001055 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +00001056 break;
1057 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001058 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +00001059 {
1060 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001061 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +00001062 break;
1063 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001064 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +00001065 {
1066 const char format[2] = "b";
1067 success = PyArg_Parse (py_return, format, (bool *) ret_value);
1068 break;
1069 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001070 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +00001071 {
1072 const char format[2] = "h";
1073 success = PyArg_Parse (py_return, format, (short *) ret_value);
1074 break;
1075 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001076 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001077 {
1078 const char format[2] = "H";
1079 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
1080 break;
1081 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001082 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +00001083 {
1084 const char format[2] = "i";
1085 success = PyArg_Parse (py_return, format, (int *) ret_value);
1086 break;
1087 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001088 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001089 {
1090 const char format[2] = "I";
1091 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
1092 break;
1093 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001094 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +00001095 {
1096 const char format[2] = "l";
1097 success = PyArg_Parse (py_return, format, (long *) ret_value);
1098 break;
1099 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001100 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001101 {
1102 const char format[2] = "k";
1103 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
1104 break;
1105 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001106 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +00001107 {
1108 const char format[2] = "L";
1109 success = PyArg_Parse (py_return, format, (long long *) ret_value);
1110 break;
1111 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001112 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001113 {
1114 const char format[2] = "K";
1115 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
1116 break;
1117 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001118 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +00001119 {
1120 const char format[2] = "f";
1121 success = PyArg_Parse (py_return, format, (float *) ret_value);
1122 break;
1123 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001124 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +00001125 {
1126 const char format[2] = "d";
1127 success = PyArg_Parse (py_return, format, (double *) ret_value);
1128 break;
1129 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001130 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +00001131 {
1132 const char format[2] = "c";
1133 success = PyArg_Parse (py_return, format, (char *) ret_value);
1134 break;
1135 }
1136 default:
1137 {}
1138 }
1139 Py_DECREF (py_return);
1140 if (success)
1141 ret_success = true;
1142 else
1143 ret_success = false;
1144 }
1145 }
1146
1147 py_error = PyErr_Occurred();
1148 if (py_error != NULL)
1149 {
1150 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1151 PyErr_Print ();
1152 PyErr_Clear();
1153 ret_success = false;
1154 }
Caroline Tice202f6b82011-01-17 21:55:19 +00001155
Chris Lattner24943d22010-06-08 16:52:24 +00001156 return ret_success;
1157}
1158
1159bool
Enrico Granataa1ba3142012-06-07 00:17:18 +00001160ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string, bool enable_io)
Chris Lattner24943d22010-06-08 16:52:24 +00001161{
Enrico Granatafa1f6172011-10-24 17:22:21 +00001162
1163
1164 Locker locker(this,
1165 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1166 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001167
Chris Lattner24943d22010-06-08 16:52:24 +00001168 bool success = false;
1169 PyObject *py_return = NULL;
1170 PyObject *mainmod = PyImport_AddModule ("__main__");
1171 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001172 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001173 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001174 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001175
Enrico Granata400105d2012-03-06 23:42:15 +00001176 locals = FindSessionDictionary(m_dictionary_name.c_str());
1177
Caroline Tice0aa2e552011-01-14 00:29:16 +00001178 if (locals == NULL)
1179 {
1180 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
1181 should_decrement_locals = true;
1182 }
1183
1184 if (locals == NULL)
1185 {
1186 locals = globals;
1187 should_decrement_locals = false;
1188 }
1189
1190 py_error = PyErr_Occurred();
1191 if (py_error != NULL)
1192 PyErr_Clear();
1193
Chris Lattner24943d22010-06-08 16:52:24 +00001194 if (in_string != NULL)
1195 {
1196 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
1197 if (compiled_node)
1198 {
1199 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
1200 if (compiled_code)
1201 {
Enrico Granataa1ba3142012-06-07 00:17:18 +00001202 { // scope for PythonInputReaderManager
1203 PythonInputReaderManager py_input(enable_io ? this : NULL);
1204 py_return = PyEval_EvalCode (compiled_code, globals, locals);
1205 }
Chris Lattner24943d22010-06-08 16:52:24 +00001206 if (py_return != NULL)
1207 {
1208 success = true;
1209 Py_DECREF (py_return);
1210 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001211 if (locals && should_decrement_locals)
1212 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +00001213 }
1214 }
1215 }
1216
1217 py_error = PyErr_Occurred ();
1218 if (py_error != NULL)
1219 {
1220 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1221 PyErr_Print ();
1222 PyErr_Clear();
1223 success = false;
1224 }
1225
1226 return success;
1227}
1228
1229static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1230
1231size_t
1232ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1233(
1234 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001235 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001236 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001237 const char *bytes,
1238 size_t bytes_len
1239)
1240{
Caroline Tice892fadd2011-06-16 16:27:19 +00001241 static StringList commands_in_progress;
1242
1243 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1244 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1245
Chris Lattner24943d22010-06-08 16:52:24 +00001246 switch (notification)
1247 {
1248 case eInputReaderActivate:
1249 {
1250 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +00001251 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +00001252 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001253 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001254 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +00001255 out_stream->Printf ("%s", reader.GetPrompt());
1256 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001257 }
1258 }
1259 break;
1260
1261 case eInputReaderDeactivate:
1262 break;
1263
1264 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001265 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001266 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001267 out_stream->Printf ("%s", reader.GetPrompt());
1268 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001269 }
Chris Lattner24943d22010-06-08 16:52:24 +00001270 break;
1271
Caroline Tice4a348082011-05-02 20:41:46 +00001272 case eInputReaderAsynchronousOutputWritten:
1273 break;
1274
Chris Lattner24943d22010-06-08 16:52:24 +00001275 case eInputReaderGotToken:
1276 {
1277 std::string temp_string (bytes, bytes_len);
1278 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001279 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001280 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001281 out_stream->Printf ("%s", reader.GetPrompt());
1282 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001283 }
Chris Lattner24943d22010-06-08 16:52:24 +00001284 }
1285 break;
1286
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001287 case eInputReaderEndOfFile:
1288 case eInputReaderInterrupt:
1289 // Control-c (SIGINT) & control-d both mean finish & exit.
1290 reader.SetIsDone(true);
1291
1292 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1293 if (notification == eInputReaderInterrupt)
1294 commands_in_progress.Clear();
1295
1296 // Fall through here...
1297
Chris Lattner24943d22010-06-08 16:52:24 +00001298 case eInputReaderDone:
1299 {
1300 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1301 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1302 data_ap->user_source.AppendList (commands_in_progress);
1303 if (data_ap.get())
1304 {
Greg Clayton63094e02010-06-23 01:19:29 +00001305 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001306 if (interpreter)
1307 {
1308 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1309 data_ap->script_source))
1310 {
Enrico Granata400105d2012-03-06 23:42:15 +00001311 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1312 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001313 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001314 else if (!batch_mode)
1315 {
1316 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1317 out_stream->Flush();
1318 }
Chris Lattner24943d22010-06-08 16:52:24 +00001319 }
1320 else
1321 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001322 if (!batch_mode)
1323 {
1324 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1325 out_stream->Flush();
1326 }
Chris Lattner24943d22010-06-08 16:52:24 +00001327 }
1328 }
1329 }
1330 break;
1331
1332 }
1333
1334 return bytes_len;
1335}
1336
Johnny Chenf3ec4612012-08-09 23:09:42 +00001337size_t
1338ScriptInterpreterPython::GenerateWatchpointOptionsCommandCallback
1339(
1340 void *baton,
1341 InputReader &reader,
1342 InputReaderAction notification,
1343 const char *bytes,
1344 size_t bytes_len
1345)
1346{
1347 static StringList commands_in_progress;
1348
1349 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1350 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1351
1352 switch (notification)
1353 {
1354 case eInputReaderActivate:
1355 {
1356 commands_in_progress.Clear();
1357 if (!batch_mode)
1358 {
1359 out_stream->Printf ("%s\n", g_reader_instructions);
1360 if (reader.GetPrompt())
1361 out_stream->Printf ("%s", reader.GetPrompt());
1362 out_stream->Flush ();
1363 }
1364 }
1365 break;
1366
1367 case eInputReaderDeactivate:
1368 break;
1369
1370 case eInputReaderReactivate:
1371 if (reader.GetPrompt() && !batch_mode)
1372 {
1373 out_stream->Printf ("%s", reader.GetPrompt());
1374 out_stream->Flush ();
1375 }
1376 break;
1377
1378 case eInputReaderAsynchronousOutputWritten:
1379 break;
1380
1381 case eInputReaderGotToken:
1382 {
1383 std::string temp_string (bytes, bytes_len);
1384 commands_in_progress.AppendString (temp_string.c_str());
1385 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
1386 {
1387 out_stream->Printf ("%s", reader.GetPrompt());
1388 out_stream->Flush ();
1389 }
1390 }
1391 break;
1392
1393 case eInputReaderEndOfFile:
1394 case eInputReaderInterrupt:
1395 // Control-c (SIGINT) & control-d both mean finish & exit.
1396 reader.SetIsDone(true);
1397
1398 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1399 if (notification == eInputReaderInterrupt)
1400 commands_in_progress.Clear();
1401
1402 // Fall through here...
1403
1404 case eInputReaderDone:
1405 {
1406 WatchpointOptions *wp_options = (WatchpointOptions *)baton;
1407 std::auto_ptr<WatchpointOptions::CommandData> data_ap(new WatchpointOptions::CommandData());
1408 data_ap->user_source.AppendList (commands_in_progress);
1409 if (data_ap.get())
1410 {
1411 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
1412 if (interpreter)
1413 {
1414 if (interpreter->GenerateWatchpointCommandCallbackData (data_ap->user_source,
1415 data_ap->script_source))
1416 {
1417 BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release()));
1418 wp_options->SetCallback (ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp);
1419 }
1420 else if (!batch_mode)
1421 {
1422 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1423 out_stream->Flush();
1424 }
1425 }
1426 else
1427 {
1428 if (!batch_mode)
1429 {
1430 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1431 out_stream->Flush();
1432 }
1433 }
1434 }
1435 }
1436 break;
1437
1438 }
1439
1440 return bytes_len;
1441}
1442
Chris Lattner24943d22010-06-08 16:52:24 +00001443void
Greg Clayton238c0a12010-09-18 01:14:36 +00001444ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001445 CommandReturnObject &result)
1446{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001447 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1448
Greg Clayton63094e02010-06-23 01:19:29 +00001449 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001450
1451 if (reader_sp)
1452 {
1453 Error err = reader_sp->Initialize (
1454 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1455 bp_options, // baton
1456 eInputReaderGranularityLine, // token size, for feeding data to callback function
1457 "DONE", // end token
1458 "> ", // prompt
1459 true); // echo input
1460
1461 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001462 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001463 else
1464 {
1465 result.AppendError (err.AsCString());
1466 result.SetStatus (eReturnStatusFailed);
1467 }
1468 }
1469 else
1470 {
1471 result.AppendError("out of memory");
1472 result.SetStatus (eReturnStatusFailed);
1473 }
1474}
1475
Johnny Chenf3ec4612012-08-09 23:09:42 +00001476void
1477ScriptInterpreterPython::CollectDataForWatchpointCommandCallback (WatchpointOptions *wp_options,
1478 CommandReturnObject &result)
1479{
1480 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1481
1482 InputReaderSP reader_sp (new InputReader (debugger));
1483
1484 if (reader_sp)
1485 {
1486 Error err = reader_sp->Initialize (
1487 ScriptInterpreterPython::GenerateWatchpointOptionsCommandCallback,
1488 wp_options, // baton
1489 eInputReaderGranularityLine, // token size, for feeding data to callback function
1490 "DONE", // end token
1491 "> ", // prompt
1492 true); // echo input
1493
1494 if (err.Success())
1495 debugger.PushInputReader (reader_sp);
1496 else
1497 {
1498 result.AppendError (err.AsCString());
1499 result.SetStatus (eReturnStatusFailed);
1500 }
1501 }
1502 else
1503 {
1504 result.AppendError("out of memory");
1505 result.SetStatus (eReturnStatusFailed);
1506 }
1507}
1508
Johnny Chen3e0571b2010-09-11 00:23:59 +00001509// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001510void
Greg Clayton238c0a12010-09-18 01:14:36 +00001511ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001512 const char *oneliner)
1513{
1514 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1515
1516 // It's necessary to set both user_source and script_source to the oneliner.
1517 // The former is used to generate callback description (as in breakpoint command list)
1518 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001519
Johnny Chend1c2dca2010-09-10 18:21:10 +00001520 data_ap->user_source.AppendString (oneliner);
Johnny Chenf3ec4612012-08-09 23:09:42 +00001521 data_ap->script_source.assign (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001522
Caroline Tice5136f942010-09-27 21:35:15 +00001523 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1524 {
Enrico Granata400105d2012-03-06 23:42:15 +00001525 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1526 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Caroline Tice5136f942010-09-27 21:35:15 +00001527 }
1528
Johnny Chend1c2dca2010-09-10 18:21:10 +00001529 return;
1530}
1531
Johnny Chenf3ec4612012-08-09 23:09:42 +00001532// Set a Python one-liner as the callback for the watchpoint.
1533void
1534ScriptInterpreterPython::SetWatchpointCommandCallback (WatchpointOptions *wp_options,
1535 const char *oneliner)
1536{
1537 std::auto_ptr<WatchpointOptions::CommandData> data_ap(new WatchpointOptions::CommandData());
1538
1539 // It's necessary to set both user_source and script_source to the oneliner.
1540 // The former is used to generate callback description (as in watchpoint command list)
1541 // while the latter is used for Python to interpret during the actual callback.
1542
1543 data_ap->user_source.AppendString (oneliner);
1544 data_ap->script_source.assign (oneliner);
1545
1546 if (GenerateWatchpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1547 {
1548 BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release()));
1549 wp_options->SetCallback (ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp);
1550 }
1551
1552 return;
1553}
1554
Chris Lattner24943d22010-06-08 16:52:24 +00001555bool
1556ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1557{
1558 // Convert StringList to one long, newline delimited, const char *.
Enrico Granata400105d2012-03-06 23:42:15 +00001559 std::string function_def_string(function_def.CopyList());
Chris Lattner24943d22010-06-08 16:52:24 +00001560
Enrico Granataa1ba3142012-06-07 00:17:18 +00001561 return ExecuteMultipleLines (function_def_string.c_str(), false);
Chris Lattner24943d22010-06-08 16:52:24 +00001562}
1563
Enrico Granataf7a9b142011-07-15 02:26:42 +00001564bool
Enrico Granata400105d2012-03-06 23:42:15 +00001565ScriptInterpreterPython::GenerateFunction(const char *signature, const StringList &input)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001566{
1567 int num_lines = input.GetSize ();
1568 if (num_lines == 0)
1569 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001570
1571 if (!signature || *signature == 0)
1572 return false;
1573
Enrico Granataf7a9b142011-07-15 02:26:42 +00001574 StreamString sstr;
1575 StringList auto_generated_function;
Enrico Granata400105d2012-03-06 23:42:15 +00001576 auto_generated_function.AppendString (signature);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001577 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001578 auto_generated_function.AppendString (" new_keys = internal_dict.keys()"); // Make a list of keys in the session dict
Enrico Granataf7a9b142011-07-15 02:26:42 +00001579 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001580 auto_generated_function.AppendString (" global_dict.update (internal_dict)"); // Add the session dictionary to the
Enrico Granataf7a9b142011-07-15 02:26:42 +00001581 // global dictionary.
1582
1583 // Wrap everything up inside the function, increasing the indentation.
1584
1585 for (int i = 0; i < num_lines; ++i)
1586 {
1587 sstr.Clear ();
1588 sstr.Printf (" %s", input.GetStringAtIndex (i));
1589 auto_generated_function.AppendString (sstr.GetData());
1590 }
1591 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001592 auto_generated_function.AppendString (" internal_dict[key] = global_dict[key]"); // Update session dict values
Enrico Granataf7a9b142011-07-15 02:26:42 +00001593 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1594 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1595
1596 // Verify that the results are valid Python.
1597
1598 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1599 return false;
1600
1601 return true;
1602
1603}
1604
Enrico Granataf7a9b142011-07-15 02:26:42 +00001605bool
Enrico Granata400105d2012-03-06 23:42:15 +00001606ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001607{
Enrico Granata400105d2012-03-06 23:42:15 +00001608 static uint32_t num_created_functions = 0;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001609 user_input.RemoveBlankLines ();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001610 StreamString sstr;
1611
1612 // Check to see if we have any data; if not, just return.
1613 if (user_input.GetSize() == 0)
1614 return false;
1615
1616 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1617 // ValueObject as parameter to the function.
1618
Enrico Granata400105d2012-03-06 23:42:15 +00001619 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_type_print_func", num_created_functions, name_token));
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001620 sstr.Printf ("def %s (valobj, internal_dict):", auto_generated_function_name.c_str());
Enrico Granataf7a9b142011-07-15 02:26:42 +00001621
Enrico Granata400105d2012-03-06 23:42:15 +00001622 if (!GenerateFunction(sstr.GetData(), user_input))
Enrico Granataf7a9b142011-07-15 02:26:42 +00001623 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001624
Enrico Granataf7a9b142011-07-15 02:26:42 +00001625 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001626 output.assign(auto_generated_function_name);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001627 return true;
1628}
1629
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001630bool
Enrico Granata400105d2012-03-06 23:42:15 +00001631ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, std::string &output)
Enrico Granatac2a28252011-08-16 16:49:25 +00001632{
Enrico Granata400105d2012-03-06 23:42:15 +00001633 static uint32_t num_created_functions = 0;
Enrico Granatac2a28252011-08-16 16:49:25 +00001634 user_input.RemoveBlankLines ();
Enrico Granatac2a28252011-08-16 16:49:25 +00001635 StreamString sstr;
1636
1637 // Check to see if we have any data; if not, just return.
1638 if (user_input.GetSize() == 0)
1639 return false;
1640
Enrico Granata400105d2012-03-06 23:42:15 +00001641 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_cmd_alias_func", num_created_functions));
1642
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001643 sstr.Printf ("def %s (debugger, args, result, internal_dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001644
Enrico Granata400105d2012-03-06 23:42:15 +00001645 if (!GenerateFunction(sstr.GetData(),user_input))
Enrico Granatac2a28252011-08-16 16:49:25 +00001646 return false;
1647
1648 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001649 output.assign(auto_generated_function_name);
Enrico Granatac2a28252011-08-16 16:49:25 +00001650 return true;
1651}
1652
1653
1654bool
Enrico Granata400105d2012-03-06 23:42:15 +00001655ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, std::string &output, void* name_token)
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001656{
Enrico Granata400105d2012-03-06 23:42:15 +00001657 static uint32_t num_created_classes = 0;
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001658 user_input.RemoveBlankLines ();
1659 int num_lines = user_input.GetSize ();
1660 StreamString sstr;
1661
1662 // Check to see if we have any data; if not, just return.
1663 if (user_input.GetSize() == 0)
1664 return false;
1665
1666 // Wrap all user input into a Python class
1667
Enrico Granata400105d2012-03-06 23:42:15 +00001668 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 +00001669
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001670 StringList auto_generated_class;
1671
1672 // Create the function name & definition string.
1673
1674 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1675 auto_generated_class.AppendString (sstr.GetData());
1676
1677 // Wrap everything up inside the class, increasing the indentation.
1678
1679 for (int i = 0; i < num_lines; ++i)
1680 {
1681 sstr.Clear ();
1682 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1683 auto_generated_class.AppendString (sstr.GetData());
1684 }
1685
1686
1687 // Verify that the results are valid Python.
1688 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1689 // (TODO: rename that method to ExportDefinitionToInterpreter)
1690 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1691 return false;
1692
1693 // Store the name of the auto-generated class
1694
Enrico Granata400105d2012-03-06 23:42:15 +00001695 output.assign(auto_generated_class_name);
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001696 return true;
1697}
1698
Enrico Granata400105d2012-03-06 23:42:15 +00001699lldb::ScriptInterpreterObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001700ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1701 lldb::ValueObjectSP valobj)
1702{
1703 if (class_name.empty())
Enrico Granata400105d2012-03-06 23:42:15 +00001704 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001705
1706 if (!valobj.get())
Enrico Granata400105d2012-03-06 23:42:15 +00001707 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001708
Greg Claytonb4d7fc02012-02-17 07:49:44 +00001709 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1710 Target *target = exe_ctx.GetTargetPtr();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001711
1712 if (!target)
Enrico Granata400105d2012-03-06 23:42:15 +00001713 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001714
1715 Debugger &debugger = target->GetDebugger();
1716 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1717 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1718
1719 if (!script_interpreter)
Enrico Granata400105d2012-03-06 23:42:15 +00001720 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001721
1722 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001723
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001724 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001725 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001726 ForceDisableSyntheticChildren no_synthetics(target);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001727 ret_val = g_swig_synthetic_script (class_name,
1728 python_interpreter->m_dictionary_name.c_str(),
1729 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001730 }
1731
Enrico Granata400105d2012-03-06 23:42:15 +00001732 return MakeScriptObject(ret_val);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001733}
1734
Enrico Granataf7a9b142011-07-15 02:26:42 +00001735bool
Enrico Granata400105d2012-03-06 23:42:15 +00001736ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001737{
Enrico Granata16376ed2012-02-15 02:34:21 +00001738 StringList input;
1739 input.SplitIntoLines(oneliner, strlen(oneliner));
1740 return GenerateTypeScriptFunction(input, output, name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001741}
1742
Chris Lattner24943d22010-06-08 16:52:24 +00001743bool
Enrico Granata400105d2012-03-06 23:42:15 +00001744ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, std::string& output, void* name_token)
Enrico Granata16376ed2012-02-15 02:34:21 +00001745{
1746 StringList input;
1747 input.SplitIntoLines(oneliner, strlen(oneliner));
1748 return GenerateTypeSynthClass(input, output, name_token);
1749}
1750
1751
1752bool
Enrico Granata400105d2012-03-06 23:42:15 +00001753ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, std::string& output)
Chris Lattner24943d22010-06-08 16:52:24 +00001754{
Enrico Granata400105d2012-03-06 23:42:15 +00001755 static uint32_t num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001756 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001757 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001758
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001759 if (user_input.GetSize() == 0)
1760 return false;
1761
Enrico Granata400105d2012-03-06 23:42:15 +00001762 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_bp_callback_func_",num_created_functions));
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001763 sstr.Printf ("def %s (frame, bp_loc, internal_dict):", auto_generated_function_name.c_str());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001764
Enrico Granata400105d2012-03-06 23:42:15 +00001765 if (!GenerateFunction(sstr.GetData(), user_input))
Caroline Ticeb447e842010-09-21 19:25:28 +00001766 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001767
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001768 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001769 output.assign(auto_generated_function_name);
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001770 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001771}
1772
Enrico Granata1328b142012-02-29 03:28:49 +00001773bool
Johnny Chenf3ec4612012-08-09 23:09:42 +00001774ScriptInterpreterPython::GenerateWatchpointCommandCallbackData (StringList &user_input, std::string& output)
1775{
1776 static uint32_t num_created_functions = 0;
1777 user_input.RemoveBlankLines ();
1778 StreamString sstr;
1779
1780 if (user_input.GetSize() == 0)
1781 return false;
1782
1783 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_wp_callback_func_",num_created_functions));
1784 sstr.Printf ("def %s (frame, wp, internal_dict):", auto_generated_function_name.c_str());
1785
1786 if (!GenerateFunction(sstr.GetData(), user_input))
1787 return false;
1788
1789 // Store the name of the auto-generated function to be called.
1790 output.assign(auto_generated_function_name);
1791 return true;
1792}
1793
1794bool
Enrico Granata1328b142012-02-29 03:28:49 +00001795ScriptInterpreterPython::GetScriptedSummary (const char *python_function_name,
1796 lldb::ValueObjectSP valobj,
1797 lldb::ScriptInterpreterObjectSP& callee_wrapper_sp,
1798 std::string& retval)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001799{
1800
Enrico Granata1328b142012-02-29 03:28:49 +00001801 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001802
1803 if (!valobj.get())
Enrico Granata1328b142012-02-29 03:28:49 +00001804 {
1805 retval.assign("<no object>");
1806 return false;
1807 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001808
Enrico Granata1328b142012-02-29 03:28:49 +00001809 void* old_callee = (callee_wrapper_sp ? callee_wrapper_sp->GetObject() : NULL);
1810 void* new_callee = old_callee;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001811
Enrico Granata1328b142012-02-29 03:28:49 +00001812 bool ret_val;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001813 if (python_function_name
1814 && *python_function_name)
1815 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001816 {
Enrico Granata1328b142012-02-29 03:28:49 +00001817 Locker py_lock(this);
1818 {
1819 Timer scoped_timer ("g_swig_typescript_callback","g_swig_typescript_callback");
1820 ret_val = g_swig_typescript_callback (python_function_name,
1821 FindSessionDictionary(m_dictionary_name.c_str()),
1822 valobj,
1823 &new_callee,
1824 retval);
1825 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001826 }
1827 }
1828 else
Enrico Granata1328b142012-02-29 03:28:49 +00001829 {
1830 retval.assign("<no function name>");
1831 return false;
1832 }
1833
1834 if (new_callee && old_callee != new_callee)
1835 callee_wrapper_sp = MakeScriptObject(new_callee);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001836
1837 return ret_val;
1838
1839}
1840
Greg Clayton5144f382010-10-07 17:14:24 +00001841bool
1842ScriptInterpreterPython::BreakpointCallbackFunction
1843(
1844 void *baton,
1845 StoppointCallbackContext *context,
1846 user_id_t break_id,
1847 user_id_t break_loc_id
1848)
1849{
1850 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
Enrico Granata400105d2012-03-06 23:42:15 +00001851 const char *python_function_name = bp_option_data->script_source.c_str();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001852
1853 if (!context)
1854 return true;
1855
Greg Claytonf4124de2012-02-21 00:09:25 +00001856 ExecutionContext exe_ctx (context->exe_ctx_ref);
1857 Target *target = exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001858
1859 if (!target)
1860 return true;
1861
1862 Debugger &debugger = target->GetDebugger();
1863 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1864 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1865
1866 if (!script_interpreter)
1867 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001868
1869 if (python_function_name != NULL
1870 && python_function_name[0] != '\0')
1871 {
Greg Claytonf4124de2012-02-21 00:09:25 +00001872 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001873 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001874 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001875 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001876 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1877
1878 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001879 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001880 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001881 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001882 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001883 ret_val = g_swig_breakpoint_callback (python_function_name,
1884 python_interpreter->m_dictionary_name.c_str(),
1885 stop_frame_sp,
1886 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001887 }
1888 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001889 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001890 }
Greg Clayton5144f382010-10-07 17:14:24 +00001891 }
1892 // We currently always true so we stop in case anything goes wrong when
1893 // trying to call the script function
1894 return true;
1895}
Caroline Tice2ade6112010-11-10 19:18:14 +00001896
Johnny Chenf3ec4612012-08-09 23:09:42 +00001897bool
1898ScriptInterpreterPython::WatchpointCallbackFunction
1899(
1900 void *baton,
1901 StoppointCallbackContext *context,
1902 user_id_t watch_id
1903)
1904{
1905 WatchpointOptions::CommandData *wp_option_data = (WatchpointOptions::CommandData *) baton;
1906 const char *python_function_name = wp_option_data->script_source.c_str();
1907
1908 if (!context)
1909 return true;
1910
1911 ExecutionContext exe_ctx (context->exe_ctx_ref);
1912 Target *target = exe_ctx.GetTargetPtr();
1913
1914 if (!target)
1915 return true;
1916
1917 Debugger &debugger = target->GetDebugger();
1918 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1919 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1920
1921 if (!script_interpreter)
1922 return true;
1923
1924 if (python_function_name != NULL
1925 && python_function_name[0] != '\0')
1926 {
1927 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
1928 WatchpointSP wp_sp = target->GetWatchpointList().FindByID (watch_id);
1929 if (wp_sp)
1930 {
1931 if (stop_frame_sp && wp_sp)
1932 {
1933 bool ret_val = true;
1934 {
1935 Locker py_lock(python_interpreter);
1936 ret_val = g_swig_watchpoint_callback (python_function_name,
1937 python_interpreter->m_dictionary_name.c_str(),
1938 stop_frame_sp,
1939 wp_sp);
1940 }
1941 return ret_val;
1942 }
1943 }
1944 }
1945 // We currently always true so we stop in case anything goes wrong when
1946 // trying to call the script function
1947 return true;
1948}
1949
Caroline Tice2ade6112010-11-10 19:18:14 +00001950lldb::thread_result_t
1951ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1952{
1953 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1954
1955 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1956
1957 if (log)
1958 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1959
1960 char error_str[1024];
1961 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001962
Enrico Granatafa1f6172011-10-24 17:22:21 +00001963 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001964 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001965 StreamString run_string;
Johnny Chen8165d432012-08-18 04:14:54 +00001966
1967 // Ensure we have the GIL before running any Python code.
1968 // Since we're only running a few one-liners and then dropping to the interpreter (which will release the GIL when needed),
1969 // we can just release the GIL after finishing our work.
1970 // If finer-grained locking is desirable, we can lock and unlock the GIL only when calling a python function.
1971 Locker locker(script_interpreter,
1972 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1973 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1974
Caroline Tice0aa2e552011-01-14 00:29:16 +00001975 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1976 PyRun_SimpleString (run_string.GetData());
1977 run_string.Clear ();
1978
1979 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1980 PyRun_SimpleString (run_string.GetData());
1981 run_string.Clear ();
1982
1983 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1984 PyRun_SimpleString (run_string.GetData());
1985 run_string.Clear ();
1986
1987 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1988 pty_slave_name);
1989 PyRun_SimpleString (run_string.GetData());
1990 run_string.Clear ();
1991
Johnny Chen8054ba32011-03-11 00:28:50 +00001992 // The following call drops into the embedded interpreter loop and stays there until the
1993 // user chooses to exit from the Python interpreter.
Johnny Chen8165d432012-08-18 04:14:54 +00001994 // This embedded interpreter will, as any Python code that performs I/O, unlock the GIL before
1995 // a system call that can hang, and lock it when the syscall has returned.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001996
Johnny Chen8165d432012-08-18 04:14:54 +00001997 // We need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1998 // PyGILState_Release (using the Locker above). This is because Python has a global lock which must be held whenever we want
1999 // to touch any Python objects. Otherwise, if the user calls Python code, the interpreter state will be off,
2000 // and things could hang (it's happened before).
Caroline Ticece207c12011-03-11 00:21:55 +00002001
Caroline Tice0aa2e552011-01-14 00:29:16 +00002002 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
2003 PyRun_SimpleString (run_string.GetData());
2004 run_string.Clear ();
Johnny Chen8165d432012-08-18 04:14:54 +00002005
Caroline Tice0aa2e552011-01-14 00:29:16 +00002006 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
2007 PyRun_SimpleString (run_string.GetData());
2008 run_string.Clear();
Johnny Chen8165d432012-08-18 04:14:54 +00002009
Caroline Tice0aa2e552011-01-14 00:29:16 +00002010 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
2011 PyRun_SimpleString (run_string.GetData());
2012 run_string.Clear();
Caroline Tice2ade6112010-11-10 19:18:14 +00002013 }
2014
Johnny Chen8121d7a2012-08-17 23:44:35 +00002015 if (script_interpreter->m_embedded_python_input_reader_sp)
2016 script_interpreter->m_embedded_python_input_reader_sp->SetIsDone (true);
Caroline Tice2ade6112010-11-10 19:18:14 +00002017
2018 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002019
Caroline Tice2ade6112010-11-10 19:18:14 +00002020 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
2021 if (log)
2022 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
2023
2024
Johnny Chen8054ba32011-03-11 00:28:50 +00002025 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00002026 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Johnny Chen8121d7a2012-08-17 23:44:35 +00002027 const InputReaderSP reader_sp = script_interpreter->m_embedded_python_input_reader_sp;
2028 if (reader_sp)
2029 {
2030 debugger.PopInputReader (reader_sp);
2031 script_interpreter->m_embedded_python_input_reader_sp.reset();
2032 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00002033
Caroline Tice2ade6112010-11-10 19:18:14 +00002034 return NULL;
2035}
2036
Enrico Granataa1ba3142012-06-07 00:17:18 +00002037lldb::thread_result_t
2038ScriptInterpreterPython::PythonInputReaderManager::RunPythonInputReader (lldb::thread_arg_t baton)
2039{
2040 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
2041
2042 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
2043
2044 if (reader_sp)
2045 reader_sp->WaitOnReaderIsDone();
2046
2047 return NULL;
2048}
2049
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002050uint32_t
Enrico Granata400105d2012-03-06 23:42:15 +00002051ScriptInterpreterPython::CalculateNumChildren (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002052{
Enrico Granata400105d2012-03-06 23:42:15 +00002053 if (!implementor_sp)
2054 return 0;
2055
2056 void* implementor = implementor_sp->GetObject();
2057
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002058 if (!implementor)
2059 return 0;
2060
2061 if (!g_swig_calc_children)
2062 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00002063
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002064 uint32_t ret_val = 0;
2065
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002066 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002067 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00002068 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002069 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002070 }
2071
2072 return ret_val;
2073}
2074
Enrico Granata91544802011-09-06 19:20:51 +00002075lldb::ValueObjectSP
Enrico Granata400105d2012-03-06 23:42:15 +00002076ScriptInterpreterPython::GetChildAtIndex (const lldb::ScriptInterpreterObjectSP& implementor_sp, uint32_t idx)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002077{
Enrico Granata400105d2012-03-06 23:42:15 +00002078 if (!implementor_sp)
2079 return lldb::ValueObjectSP();
2080
2081 void* implementor = implementor_sp->GetObject();
2082
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002083 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00002084 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002085
Enrico Granata91544802011-09-06 19:20:51 +00002086 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
2087 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002088
Enrico Granata91544802011-09-06 19:20:51 +00002089 void* child_ptr = NULL;
2090 lldb::SBValue* value_sb = NULL;
2091 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002092
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002093 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002094 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00002095 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata91544802011-09-06 19:20:51 +00002096 child_ptr = g_swig_get_child_index (implementor,idx);
2097 if (child_ptr != NULL && child_ptr != Py_None)
2098 {
2099 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
2100 if (value_sb == NULL)
2101 Py_XDECREF(child_ptr);
2102 else
2103 ret_val = value_sb->get_sp();
2104 }
2105 else
2106 {
2107 Py_XDECREF(child_ptr);
2108 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002109 }
2110
2111 return ret_val;
2112}
2113
2114int
Enrico Granata400105d2012-03-06 23:42:15 +00002115ScriptInterpreterPython::GetIndexOfChildWithName (const lldb::ScriptInterpreterObjectSP& implementor_sp, const char* child_name)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002116{
Enrico Granata400105d2012-03-06 23:42:15 +00002117 if (!implementor_sp)
2118 return UINT32_MAX;
2119
2120 void* implementor = implementor_sp->GetObject();
2121
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002122 if (!implementor)
2123 return UINT32_MAX;
2124
2125 if (!g_swig_get_index_child)
2126 return UINT32_MAX;
2127
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002128 int ret_val = UINT32_MAX;
2129
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002130 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002131 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00002132 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002133 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002134 }
2135
2136 return ret_val;
2137}
2138
Enrico Granatacf09f882012-03-19 22:58:49 +00002139bool
Enrico Granata400105d2012-03-06 23:42:15 +00002140ScriptInterpreterPython::UpdateSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata979e20d2011-07-29 19:53:35 +00002141{
Enrico Granatacf09f882012-03-19 22:58:49 +00002142 bool ret_val = false;
2143
Enrico Granata400105d2012-03-06 23:42:15 +00002144 if (!implementor_sp)
Enrico Granatacf09f882012-03-19 22:58:49 +00002145 return ret_val;
Enrico Granata400105d2012-03-06 23:42:15 +00002146
2147 void* implementor = implementor_sp->GetObject();
2148
Enrico Granata979e20d2011-07-29 19:53:35 +00002149 if (!implementor)
Enrico Granatacf09f882012-03-19 22:58:49 +00002150 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00002151
2152 if (!g_swig_update_provider)
Enrico Granatacf09f882012-03-19 22:58:49 +00002153 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00002154
Enrico Granata979e20d2011-07-29 19:53:35 +00002155 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002156 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00002157 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granatacf09f882012-03-19 22:58:49 +00002158 ret_val = g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00002159 }
2160
Enrico Granatacf09f882012-03-19 22:58:49 +00002161 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00002162}
2163
Enrico Granatac2a28252011-08-16 16:49:25 +00002164bool
Enrico Granata59df36f2011-10-17 21:45:27 +00002165ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00002166 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00002167 lldb_private::Error& error)
2168{
2169 if (!pathname || !pathname[0])
2170 {
2171 error.SetErrorString("invalid pathname");
2172 return false;
2173 }
2174
2175 if (!g_swig_call_module_init)
2176 {
2177 error.SetErrorString("internal helper function missing");
2178 return false;
2179 }
2180
Greg Clayton13d24fb2012-01-29 20:56:30 +00002181 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granatafa1f6172011-10-24 17:22:21 +00002182
Enrico Granata59df36f2011-10-17 21:45:27 +00002183 {
Enrico Granata59df36f2011-10-17 21:45:27 +00002184 FileSpec target_file(pathname, true);
2185
2186 // TODO: would we want to reject any other value?
2187 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
2188 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
2189 {
2190 error.SetErrorString("invalid pathname");
2191 return false;
2192 }
2193
2194 const char* directory = target_file.GetDirectory().GetCString();
2195 std::string basename(target_file.GetFilename().GetCString());
Johnny Chen8165d432012-08-18 04:14:54 +00002196
2197 // Before executing Pyton code, lock the GIL.
2198 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00002199
2200 // now make sure that Python has "directory" in the search path
2201 StreamString command_stream;
2202 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
2203 directory,
2204 directory);
Enrico Granataa1ba3142012-06-07 00:17:18 +00002205 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData(), false);
Enrico Granata59df36f2011-10-17 21:45:27 +00002206 if (!syspath_retval)
2207 {
2208 error.SetErrorString("Python sys.path handling failed");
2209 return false;
2210 }
2211
2212 // strip .py or .pyc extension
2213 ConstString extension = target_file.GetFileNameExtension();
2214 if (::strcmp(extension.GetCString(), "py") == 0)
2215 basename.resize(basename.length()-3);
2216 else if(::strcmp(extension.GetCString(), "pyc") == 0)
2217 basename.resize(basename.length()-4);
2218
2219 // check if the module is already import-ed
2220 command_stream.Clear();
2221 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
2222 int refcount = 0;
2223 // this call will fail if the module does not exist (because the parameter to it is not a string
2224 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00002225 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
Enrico Granataa1ba3142012-06-07 00:17:18 +00002226 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount, false) && refcount > 0);
Enrico Granata6010ace2011-11-07 22:57:04 +00002227 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00002228 {
2229 error.SetErrorString("module already imported");
2230 return false;
2231 }
2232
2233 // now actually do the import
2234 command_stream.Clear();
2235 command_stream.Printf("import %s",basename.c_str());
Enrico Granataa1ba3142012-06-07 00:17:18 +00002236 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL, false);
Enrico Granata59df36f2011-10-17 21:45:27 +00002237 if (!import_retval)
2238 {
2239 error.SetErrorString("Python import statement failed");
2240 return false;
2241 }
2242
Enrico Granata16376ed2012-02-15 02:34:21 +00002243 // call __lldb_init_module(debugger,dict)
Enrico Granata59df36f2011-10-17 21:45:27 +00002244 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00002245 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00002246 debugger_sp))
2247 {
Enrico Granata16376ed2012-02-15 02:34:21 +00002248 error.SetErrorString("calling __lldb_init_module failed");
Enrico Granata59df36f2011-10-17 21:45:27 +00002249 return false;
2250 }
2251 return true;
2252 }
2253}
2254
Enrico Granata1328b142012-02-29 03:28:49 +00002255lldb::ScriptInterpreterObjectSP
2256ScriptInterpreterPython::MakeScriptObject (void* object)
2257{
2258 return lldb::ScriptInterpreterObjectSP(new ScriptInterpreterPythonObject(object));
2259}
2260
Enrico Granata6010ace2011-11-07 22:57:04 +00002261ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
2262 ScriptedCommandSynchronicity synchro) :
2263 m_debugger_sp(debugger_sp),
2264 m_synch_wanted(synchro),
2265 m_old_asynch(debugger_sp->GetAsyncExecution())
2266{
2267 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2268 m_debugger_sp->SetAsyncExecution(false);
2269 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2270 m_debugger_sp->SetAsyncExecution(true);
2271}
2272
2273ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
2274{
2275 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2276 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2277}
2278
Enrico Granata59df36f2011-10-17 21:45:27 +00002279bool
Enrico Granatac2a28252011-08-16 16:49:25 +00002280ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
2281 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00002282 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00002283 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00002284 Error& error)
2285{
2286 if (!impl_function)
2287 {
2288 error.SetErrorString("no function to execute");
2289 return false;
2290 }
2291
2292 if (!g_swig_call_command)
2293 {
2294 error.SetErrorString("no helper function to run scripted commands");
2295 return false;
2296 }
2297
Greg Clayton13d24fb2012-01-29 20:56:30 +00002298 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata6010ace2011-11-07 22:57:04 +00002299
2300 if (!debugger_sp.get())
2301 {
2302 error.SetErrorString("invalid Debugger pointer");
2303 return false;
2304 }
Enrico Granatac2a28252011-08-16 16:49:25 +00002305
2306 bool ret_val;
2307
2308 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00002309
Enrico Granatac2a28252011-08-16 16:49:25 +00002310 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002311 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00002312 SynchronicityHandler synch_handler(debugger_sp,
2313 synchronicity);
2314
Enrico Granataa1ba3142012-06-07 00:17:18 +00002315 PythonInputReaderManager py_input(this);
2316
Enrico Granatac2a28252011-08-16 16:49:25 +00002317 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00002318 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00002319 debugger_sp,
2320 args,
2321 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00002322 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00002323 }
Enrico Granata6010ace2011-11-07 22:57:04 +00002324
Enrico Granatac2a28252011-08-16 16:49:25 +00002325 if (!ret_val)
2326 error.SetErrorString(err_msg.c_str());
2327 else
2328 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00002329
Enrico Granatac2a28252011-08-16 16:49:25 +00002330 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00002331}
2332
Enrico Granatae5e34cb2011-08-17 01:30:04 +00002333// in Python, a special attribute __doc__ contains the docstring
2334// for an object (function, method, class, ...) if any is defined
2335// Otherwise, the attribute's value is None
2336std::string
2337ScriptInterpreterPython::GetDocumentationForItem(const char* item)
2338{
2339 std::string command(item);
2340 command += ".__doc__";
2341
2342 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
2343
2344 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00002345 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granataa1ba3142012-06-07 00:17:18 +00002346 &result_ptr, false) && result_ptr)
Enrico Granatae5e34cb2011-08-17 01:30:04 +00002347 {
2348 return std::string(result_ptr);
2349 }
2350 else
2351 return std::string("");
2352}
Caroline Tice2ade6112010-11-10 19:18:14 +00002353
Caroline Tice0aa2e552011-01-14 00:29:16 +00002354void
Enrico Granata1328b142012-02-29 03:28:49 +00002355ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback)
Greg Claytone86cbb92011-03-22 01:14:58 +00002356{
2357 g_swig_init_callback = python_swig_init_callback;
Enrico Granata1328b142012-02-29 03:28:49 +00002358 g_swig_breakpoint_callback = LLDBSwigPythonBreakpointCallbackFunction;
Johnny Chenf3ec4612012-08-09 23:09:42 +00002359 g_swig_watchpoint_callback = LLDBSwigPythonWatchpointCallbackFunction;
Enrico Granata1328b142012-02-29 03:28:49 +00002360 g_swig_typescript_callback = LLDBSwigPythonCallTypeScript;
2361 g_swig_synthetic_script = LLDBSwigPythonCreateSyntheticProvider;
2362 g_swig_calc_children = LLDBSwigPython_CalculateNumChildren;
2363 g_swig_get_child_index = LLDBSwigPython_GetChildAtIndex;
2364 g_swig_get_index_child = LLDBSwigPython_GetIndexOfChildWithName;
2365 g_swig_cast_to_sbvalue = LLDBSWIGPython_CastPyObjectToSBValue;
2366 g_swig_update_provider = LLDBSwigPython_UpdateSynthProviderInstance;
2367 g_swig_call_command = LLDBSwigPythonCallCommand;
2368 g_swig_call_module_init = LLDBSwigPythonCallModuleInit;
Greg Claytone86cbb92011-03-22 01:14:58 +00002369}
2370
2371void
2372ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00002373{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002374 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
2375
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002376 // Python will muck with STDIN terminal state, so save off any current TTY
2377 // settings so we can restore them.
2378 TerminalState stdin_tty_state;
2379 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002380
Johnny Chen8165d432012-08-18 04:14:54 +00002381 PyGILState_STATE gstate;
2382 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE));
2383 bool threads_already_initialized = false;
2384 if (PyEval_ThreadsInitialized ()) {
2385 gstate = PyGILState_Ensure ();
2386 if (log)
2387 log->Printf("Ensured PyGILState. Previous state = %slocked\n", gstate == PyGILState_UNLOCKED ? "un" : "");
2388 threads_already_initialized = true;
2389 } else {
2390 // InitThreads acquires the GIL if it hasn't been called before.
2391 PyEval_InitThreads ();
2392 }
Caroline Ticea54461d2011-06-02 22:09:43 +00002393 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002394
Greg Claytone86cbb92011-03-22 01:14:58 +00002395 // Initialize SWIG after setting up python
2396 assert (g_swig_init_callback != NULL);
2397 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002398
2399 // Update the path python uses to search for modules to include the current directory.
2400
Caroline Ticed4d92832011-06-13 21:33:00 +00002401 PyRun_SimpleString ("import sys");
2402 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00002403
2404 // Find the module that owns this code and use that path we get to
2405 // set the sys.path appropriately.
2406
2407 FileSpec file_spec;
2408 char python_dir_path[PATH_MAX];
2409 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
2410 {
2411 std::string python_path("sys.path.insert(0,\"");
2412 size_t orig_len = python_path.length();
2413 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2414 {
2415 python_path.append (python_dir_path);
2416 python_path.append ("\")");
2417 PyRun_SimpleString (python_path.c_str());
2418 python_path.resize (orig_len);
2419 }
2420
2421 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
2422 {
2423 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2424 {
2425 python_path.append (python_dir_path);
2426 python_path.append ("\")");
2427 PyRun_SimpleString (python_path.c_str());
2428 python_path.resize (orig_len);
2429 }
2430 }
2431 }
2432
Greg Clayton4e651b12012-04-25 00:58:03 +00002433 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 +00002434
Johnny Chen8165d432012-08-18 04:14:54 +00002435 if (threads_already_initialized) {
2436 if (log)
2437 log->Printf("Releasing PyGILState. Returning to state = %slocked\n", gstate == PyGILState_UNLOCKED ? "un" : "");
2438 PyGILState_Release (gstate);
2439 } else {
2440 // We initialized the threads in this function, just unlock the GIL.
2441 PyEval_SaveThread();
2442 }
2443
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002444 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002445}
2446
Greg Claytone86cbb92011-03-22 01:14:58 +00002447//void
2448//ScriptInterpreterPython::Terminate ()
2449//{
2450// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
2451// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
2452// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
2453// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
2454// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
2455// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
2456// // within Py_Finalize, which results in a seg fault.
2457// //
2458// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
2459// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
2460// // process exits).
2461// //
2462//// Py_Finalize ();
2463//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00002464
2465#endif // #ifdef LLDB_DISABLE_PYTHON