blob: 1e555c4cae6750f958affcccebcb0a8bcacaf587 [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
Caroline Tice202f6b82011-01-17 21:55:19 +0000131static Predicate<lldb::tid_t> &
132PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +0000133{
Caroline Tice202f6b82011-01-17 21:55:19 +0000134 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
135 return g_interpreter_is_running;
136}
137
Enrico Granatafa1f6172011-10-24 17:22:21 +0000138bool
139ScriptInterpreterPython::Locker::CurrentThreadHasPythonLock ()
Caroline Tice202f6b82011-01-17 21:55:19 +0000140{
141 TimeValue timeout;
142
143 timeout = TimeValue::Now(); // Don't wait any time.
144
145 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
146}
147
Enrico Granatafa1f6172011-10-24 17:22:21 +0000148bool
149ScriptInterpreterPython::Locker::TryGetPythonLock (uint32_t seconds_to_wait)
Caroline Tice202f6b82011-01-17 21:55:19 +0000150{
151
152 TimeValue timeout;
153
154 if (seconds_to_wait != UINT32_MAX)
155 {
156 timeout = TimeValue::Now();
157 timeout.OffsetWithSeconds (seconds_to_wait);
158 }
159
160 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
161 Host::GetCurrentThreadID(), &timeout, NULL);
162}
163
Enrico Granatafa1f6172011-10-24 17:22:21 +0000164void
165ScriptInterpreterPython::Locker::ReleasePythonLock ()
Caroline Tice202f6b82011-01-17 21:55:19 +0000166{
167 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000168}
169
Enrico Granatafa1f6172011-10-24 17:22:21 +0000170ScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *py_interpreter,
171 uint16_t on_entry,
172 uint16_t on_leave,
173 FILE* wait_msg_handle) :
174 m_need_session( (on_leave & TearDownSession) == TearDownSession ),
175 m_release_lock ( false ), // decide in constructor body
176 m_python_interpreter(py_interpreter),
177 m_tmp_fh(wait_msg_handle)
Enrico Granata91544802011-09-06 19:20:51 +0000178{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000179 if (m_python_interpreter && !m_tmp_fh)
180 m_tmp_fh = (m_python_interpreter->m_dbg_stdout ? m_python_interpreter->m_dbg_stdout : stdout);
181
182 if ( (on_entry & AcquireLock) == AcquireLock )
183 {
184 if (CurrentThreadHasPythonLock())
185 {
186 if ( (on_leave & FreeLock) == FreeLock )
187 m_release_lock = true;
188 }
189 else
190 {
191 DoAcquireLock();
192 if ( (on_leave & FreeLock) == FreeLock )
193 m_release_lock = true;
194 if ( (on_leave & FreeAcquiredLock) == FreeAcquiredLock )
195 m_release_lock = true;
196 }
197 }
198 if ( (on_entry & InitSession) == InitSession )
199 DoInitSession();
200}
201
202bool
203ScriptInterpreterPython::Locker::DoAcquireLock()
204{
Enrico Granata91544802011-09-06 19:20:51 +0000205 if (!CurrentThreadHasPythonLock())
206 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000207 while (!TryGetPythonLock (1))
208 if (m_tmp_fh)
209 fprintf (m_tmp_fh,
Enrico Granata91544802011-09-06 19:20:51 +0000210 "Python interpreter locked on another thread; waiting to acquire lock...\n");
Enrico Granata91544802011-09-06 19:20:51 +0000211 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000212 return true;
213}
214
215bool
216ScriptInterpreterPython::Locker::DoInitSession()
217{
218 if (!m_python_interpreter)
219 return false;
220 m_python_interpreter->EnterSession ();
221 return true;
222}
223
224bool
225ScriptInterpreterPython::Locker::DoFreeLock()
226{
227 ReleasePythonLock ();
228 return true;
229}
230
231bool
232ScriptInterpreterPython::Locker::DoTearDownSession()
233{
234 if (!m_python_interpreter)
235 return false;
236 m_python_interpreter->LeaveSession ();
237 return true;
Enrico Granata91544802011-09-06 19:20:51 +0000238}
239
240ScriptInterpreterPython::Locker::~Locker()
241{
242 if (m_need_session)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000243 DoTearDownSession();
Enrico Granata91544802011-09-06 19:20:51 +0000244 if (m_release_lock)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000245 DoFreeLock();
Enrico Granata91544802011-09-06 19:20:51 +0000246}
247
Enrico Granatadba1de82012-03-27 02:35:13 +0000248class ForceDisableSyntheticChildren
249{
250public:
251 ForceDisableSyntheticChildren (Target* target) :
252 m_target(target)
253 {
254 m_old_value = target->GetSuppressSyntheticValue();
255 target->SetSuppressSyntheticValue(true);
256 }
257 ~ForceDisableSyntheticChildren ()
258 {
259 m_target->SetSuppressSyntheticValue(m_old_value);
260 }
261private:
262 Target* m_target;
263 bool m_old_value;
264};
265
Enrico Granataa1ba3142012-06-07 00:17:18 +0000266ScriptInterpreterPython::PythonInputReaderManager::PythonInputReaderManager (ScriptInterpreterPython *interpreter) :
267m_interpreter(interpreter),
268m_debugger_sp(),
269m_reader_sp(),
270m_error(false)
271{
272 if (m_interpreter == NULL)
273 {
274 m_error = true;
275 return;
276 }
277
278 m_debugger_sp = m_interpreter->GetCommandInterpreter().GetDebugger().shared_from_this();
279
280 if (!m_debugger_sp)
281 {
282 m_error = true;
283 return;
284 }
285
286 m_reader_sp = InputReaderSP(new InputReader(*m_debugger_sp.get()));
287
288 if (!m_reader_sp)
289 {
290 m_error = true;
291 return;
292 }
293
294 Error error (m_reader_sp->Initialize (ScriptInterpreterPython::PythonInputReaderManager::InputReaderCallback,
295 m_interpreter, // baton
296 eInputReaderGranularityLine, // token size, to pass to callback function
297 NULL, // end token
298 NULL, // prompt
299 true)); // echo input
300 if (error.Fail())
301 m_error = true;
302 else
303 {
304 m_debugger_sp->PushInputReader (m_reader_sp);
305 m_interpreter->m_embedded_thread_input_reader_sp = m_reader_sp;
306 }
307}
308
309ScriptInterpreterPython::PythonInputReaderManager::~PythonInputReaderManager()
310{
311 if (m_interpreter)
312 {
313 if (m_interpreter->m_embedded_thread_input_reader_sp)
314 m_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
315 m_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
316 }
317
318
319 if (m_reader_sp)
320 {
321 m_reader_sp->SetIsDone (true);
322 if (m_debugger_sp)
323 m_debugger_sp->PopInputReader(m_reader_sp);
324 }
325
326 if (m_interpreter)
327 m_interpreter->m_embedded_thread_input_reader_sp.reset();
328}
329
330size_t
331ScriptInterpreterPython::PythonInputReaderManager::InputReaderCallback
332(
333 void *baton,
334 InputReader &reader,
335 InputReaderAction notification,
336 const char *bytes,
337 size_t bytes_len
338 )
339{
340 lldb::thread_t embedded_interpreter_thread;
341 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
342
343 if (baton == NULL)
344 return 0;
345
346 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
347
348 if (script_interpreter->m_script_lang != eScriptLanguagePython)
349 return 0;
350
351 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
352
353 switch (notification)
354 {
355 case eInputReaderActivate:
356 {
357 // Save terminal settings if we can
358 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
359 if (input_fd == File::kInvalidDescriptor)
360 input_fd = STDIN_FILENO;
361
362 script_interpreter->SaveTerminalState(input_fd);
363
364 {
365 ScriptInterpreterPython::Locker locker(script_interpreter,
366 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
367 ScriptInterpreterPython::Locker::FreeAcquiredLock);
368 }
369
370 char error_str[1024];
371 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
372 sizeof(error_str)))
373 {
374 if (log)
375 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
376 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
377 {
378 StreamString run_string;
379 char error_str[1024];
380 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Enrico Granataca2c7072012-07-31 16:58:12 +0000381 if (pty_slave_name != NULL && PyThreadState_GetDict() != NULL)
Enrico Granataa1ba3142012-06-07 00:17:18 +0000382 {
383 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
384 PyRun_SimpleString (run_string.GetData());
385 run_string.Clear ();
386
387 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
388 PyRun_SimpleString (run_string.GetData());
389 run_string.Clear ();
390
391 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
392 PyRun_SimpleString (run_string.GetData());
393 run_string.Clear ();
394
395 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
396 pty_slave_name);
397 PyRun_SimpleString (run_string.GetData());
398 run_string.Clear ();
399 }
400 }
401 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.noninteractive-python>",
402 ScriptInterpreterPython::PythonInputReaderManager::RunPythonInputReader,
403 script_interpreter, NULL);
404 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
405 {
406 if (log)
407 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
408 Error detach_error;
409 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
410 }
411 else
412 {
413 if (log)
414 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, failed in creating thread");
415 reader.SetIsDone (true);
416 }
417 }
418 else
419 {
420 if (log)
421 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, failed to open master pty ");
422 reader.SetIsDone (true);
423 }
424 }
425 break;
426
427 case eInputReaderDeactivate:
428 // When another input reader is pushed, don't leave the session...
429 //script_interpreter->LeaveSession ();
430 break;
431
432 case eInputReaderReactivate:
433 {
434 // Don't try and acquire the interpreter lock here because code like
435 // this:
436 //
437 // (lldb) script
438 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
439 //
440 // This will cause the process to run. The interpreter lock is taken
441 // by the input reader for the "script" command. If we try and acquire
442 // the lock here, when the process runs it might deactivate this input
443 // reader (if STDIN is hooked up to the inferior process) and
444 // reactivate it when the process stops which will deadlock.
445 //ScriptInterpreterPython::Locker locker(script_interpreter,
446 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
447 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
448 }
449 break;
450
451 case eInputReaderAsynchronousOutputWritten:
452 break;
453
454 case eInputReaderInterrupt:
455 reader.SetIsDone(true);
456 break;
457
458 case eInputReaderEndOfFile:
459 reader.SetIsDone(true);
460 break;
461
462 case eInputReaderGotToken:
463 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
464 {
465 if (log)
466 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
467 bytes_len);
468 if (bytes && bytes_len)
469 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
470 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
471 }
472 else
473 {
474 if (log)
475 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
476 bytes,
477 bytes_len);
478 reader.SetIsDone (true);
479 }
480
481 break;
482
483 case eInputReaderDone:
484 {
485 StreamString run_string;
486 char error_str[1024];
487 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Enrico Granataca2c7072012-07-31 16:58:12 +0000488 if (pty_slave_name != NULL && PyThreadState_GetDict() != NULL)
Enrico Granataa1ba3142012-06-07 00:17:18 +0000489 {
490 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
491 PyRun_SimpleString (run_string.GetData());
492 run_string.Clear();
493
494 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
495 PyRun_SimpleString (run_string.GetData());
496 run_string.Clear();
497 }
498 }
499
500 // Restore terminal settings if they were validly saved
501 if (log)
502 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Done, closing down input reader.");
503
504 script_interpreter->RestoreTerminalState ();
505
506 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
507 break;
508 }
509
510 return bytes_len;
511}
512
Greg Clayton63094e02010-06-23 01:19:29 +0000513ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000514 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000515 m_embedded_python_pty (),
516 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +0000517 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000518 m_new_sysout (NULL),
Johnny Chenc65046d2012-03-08 20:53:04 +0000519 m_old_sysout (NULL),
520 m_old_syserr (NULL),
Enrico Granata400105d2012-03-06 23:42:15 +0000521 m_run_one_line (NULL),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000522 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000523 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000524 m_session_is_active (false),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000525 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000526{
527
Greg Clayton7c330d62011-01-27 01:01:10 +0000528 static int g_initialized = false;
529
530 if (!g_initialized)
531 {
532 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000533 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000534 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000535
536 Locker locker(this,
537 ScriptInterpreterPython::Locker::AcquireLock,
538 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Greg Clayton7c330d62011-01-27 01:01:10 +0000539
Caroline Tice0aa2e552011-01-14 00:29:16 +0000540 m_dictionary_name.append("_dict");
541 StreamString run_string;
542 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
543 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000544
Caroline Tice0aa2e552011-01-14 00:29:16 +0000545 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000546
547 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
548 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
549 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
550 // call to Debugger::Terminate is made, the ref-count has the correct value.
551 //
552 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
553 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000554
Caroline Tice0aa2e552011-01-14 00:29:16 +0000555 int old_count = Debugger::TestDebuggerRefCount();
Greg Claytonb302dff2012-02-01 08:09:32 +0000556
Greg Clayton4e651b12012-04-25 00:58:03 +0000557 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 +0000558 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000559
Enrico Granata8f84cfb2012-02-23 23:10:03 +0000560 // WARNING: temporary code that loads Cocoa formatters - this should be done on a per-platform basis rather than loading the whole set
561 // and letting the individual formatter classes exploit APIs to check whether they can/cannot do their task
562 run_string.Clear();
Greg Clayton4e651b12012-04-25 00:58:03 +0000563 //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 +0000564 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 +0000565 PyRun_SimpleString (run_string.GetData());
Greg Claytonb302dff2012-02-01 08:09:32 +0000566
Caroline Tice0aa2e552011-01-14 00:29:16 +0000567 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000568
Caroline Tice0aa2e552011-01-14 00:29:16 +0000569 if (new_count > old_count)
570 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000571
Caroline Tice0aa2e552011-01-14 00:29:16 +0000572 run_string.Clear();
Greg Clayton444e35b2011-10-19 18:09:39 +0000573 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000574 interpreter.GetDebugger().GetID());
575 PyRun_SimpleString (run_string.GetData());
576
577 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000578 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000579 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000580 }
Chris Lattner24943d22010-06-08 16:52:24 +0000581}
582
583ScriptInterpreterPython::~ScriptInterpreterPython ()
584{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000585 Debugger &debugger = GetCommandInterpreter().GetDebugger();
586
587 if (m_embedded_thread_input_reader_sp.get() != NULL)
588 {
589 m_embedded_thread_input_reader_sp->SetIsDone (true);
590 m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000591 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
592 m_embedded_thread_input_reader_sp.reset();
593 debugger.PopInputReader (reader_sp);
594 }
595
596 if (m_new_sysout)
597 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000598 Locker locker(this,
599 ScriptInterpreterPython::Locker::AcquireLock,
600 ScriptInterpreterPython::Locker::FreeLock);
601 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000602 }
Chris Lattner24943d22010-06-08 16:52:24 +0000603}
604
Caroline Tice0aa2e552011-01-14 00:29:16 +0000605void
606ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
607{
608 if (fh == NULL)
609 return;
610
611 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000612
Johnny Chenc65046d2012-03-08 20:53:04 +0000613 Locker locker(this,
614 ScriptInterpreterPython::Locker::AcquireLock,
615 ScriptInterpreterPython::Locker::FreeAcquiredLock);
616
Enrico Granata91544802011-09-06 19:20:51 +0000617 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000618}
619
620void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000621ScriptInterpreterPython::SaveTerminalState (int fd)
622{
623 // Python mucks with the terminal state of STDIN. If we can possibly avoid
624 // this by setting the file handles up correctly prior to entering the
625 // interpreter we should. For now we save and restore the terminal state
626 // on the input file handle.
627 m_terminal_state.Save (fd, false);
628}
629
630void
631ScriptInterpreterPython::RestoreTerminalState ()
632{
633 // Python mucks with the terminal state of STDIN. If we can possibly avoid
634 // this by setting the file handles up correctly prior to entering the
635 // interpreter we should. For now we save and restore the terminal state
636 // on the input file handle.
637 m_terminal_state.Restore();
638}
639
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000640void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000641ScriptInterpreterPython::LeaveSession ()
642{
Enrico Granata7aa754c2012-04-04 17:31:29 +0000643 // checking that we have a valid thread state - since we use our own threading and locking
644 // in some (rare) cases during cleanup Python may end up believing we have no thread state
645 // and PyImport_AddModule will crash if that is the case - since that seems to only happen
646 // when destroying the SBDebugger, we can make do without clearing up stdout and stderr
Johnny Chen2b536952012-05-04 20:37:11 +0000647
648 // rdar://problem/11292882
649 // When the current thread state is NULL, PyThreadState_Get() issues a fatal error.
650 if (PyThreadState_GetDict())
Johnny Chen41641f92012-02-29 01:52:13 +0000651 {
Enrico Granata7aa754c2012-04-04 17:31:29 +0000652 PyObject *sysmod = PyImport_AddModule ("sys");
653 PyObject *sysdict = PyModule_GetDict (sysmod);
654
655 if (m_new_sysout && sysmod && sysdict)
656 {
657 if (m_old_sysout)
658 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_old_sysout);
659 if (m_old_syserr)
660 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_old_syserr);
661 }
Johnny Chen41641f92012-02-29 01:52:13 +0000662 }
663
Caroline Tice0aa2e552011-01-14 00:29:16 +0000664 m_session_is_active = false;
665}
666
667void
668ScriptInterpreterPython::EnterSession ()
669{
670 // If we have already entered the session, without having officially 'left' it, then there is no need to
671 // 'enter' it again.
672
673 if (m_session_is_active)
674 return;
675
676 m_session_is_active = true;
677
Caroline Tice202f6b82011-01-17 21:55:19 +0000678 StreamString run_string;
679
Greg Clayton2fecc452012-01-28 02:11:02 +0000680 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %llu", m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
681 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)", GetCommandInterpreter().GetDebugger().GetID());
682 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
683 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
684 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
685 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
686 // Make sure STDIN is closed since when we run this as an embedded
687 // interpreter we don't want someone to call "line = sys.stdin.readline()"
688 // and lock up. We don't have multiple windows and when the interpreter is
689 // embedded we don't know we should be feeding input to the embedded
690 // interpreter or to the python sys.stdin. We also don't want to let python
691 // play with the real stdin from this process, so we need to close it...
Greg Clayton3eeaf6e2012-02-03 01:30:30 +0000692 //run_string.PutCString ("; sys.stdin.close()");
Greg Clayton2fecc452012-01-28 02:11:02 +0000693 run_string.PutCString ("')");
Caroline Tice0aa2e552011-01-14 00:29:16 +0000694
Caroline Tice6af65cb2011-05-03 21:21:50 +0000695 PyRun_SimpleString (run_string.GetData());
696 run_string.Clear();
Johnny Chen41641f92012-02-29 01:52:13 +0000697
Caroline Tice0aa2e552011-01-14 00:29:16 +0000698 PyObject *sysmod = PyImport_AddModule ("sys");
699 PyObject *sysdict = PyModule_GetDict (sysmod);
Johnny Chen41641f92012-02-29 01:52:13 +0000700
Greg Clayton2fecc452012-01-28 02:11:02 +0000701 if (m_new_sysout && sysmod && sysdict)
702 {
Johnny Chen41641f92012-02-29 01:52:13 +0000703 m_old_sysout = PyDict_GetItemString(sysdict, "stdout");
704 m_old_syserr = PyDict_GetItemString(sysdict, "stderr");
Johnny Chenc65046d2012-03-08 20:53:04 +0000705 if (m_new_sysout)
706 {
707 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
708 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
709 }
Greg Clayton2fecc452012-01-28 02:11:02 +0000710 }
Johnny Chen41641f92012-02-29 01:52:13 +0000711
Caroline Tice0aa2e552011-01-14 00:29:16 +0000712 if (PyErr_Occurred())
713 PyErr_Clear ();
Greg Clayton2fecc452012-01-28 02:11:02 +0000714}
Caroline Tice0aa2e552011-01-14 00:29:16 +0000715
Enrico Granata400105d2012-03-06 23:42:15 +0000716static PyObject*
717FindSessionDictionary (const char* dict_name)
718{
719 static std::map<ConstString,PyObject*> g_dict_map;
720
721 ConstString dict(dict_name);
722
723 std::map<ConstString,PyObject*>::iterator iter = g_dict_map.find(dict);
724
725 if (iter != g_dict_map.end())
726 return iter->second;
727
728 PyObject *main_mod = PyImport_AddModule ("__main__");
729 if (main_mod != NULL)
730 {
731 PyObject *main_dict = PyModule_GetDict (main_mod);
732 if ((main_dict != NULL)
733 && PyDict_Check (main_dict))
734 {
735 // Go through the main dictionary looking for the correct python script interpreter dictionary
736 PyObject *key, *value;
737 Py_ssize_t pos = 0;
738
739 while (PyDict_Next (main_dict, &pos, &key, &value))
740 {
741 // We have stolen references to the key and value objects in the dictionary; we need to increment
742 // them now so that Python's garbage collector doesn't collect them out from under us.
743 Py_INCREF (key);
744 Py_INCREF (value);
745 if (strcmp (PyString_AsString (key), dict_name) == 0)
746 {
747 g_dict_map[dict] = value;
748 return value;
749 }
750 }
751 }
752 }
753 return NULL;
754}
755
756static std::string
757GenerateUniqueName (const char* base_name_wanted,
758 uint32_t& functions_counter,
759 void* name_token = NULL)
760{
761 StreamString sstr;
762
763 if (!base_name_wanted)
764 return std::string();
765
766 if (!name_token)
767 sstr.Printf ("%s_%d", base_name_wanted, functions_counter++);
768 else
769 sstr.Printf ("%s_%p", base_name_wanted, name_token);
770
771 return sstr.GetString();
772}
773
Johnny Chen60dde642010-07-30 22:33:14 +0000774bool
Enrico Granataa1ba3142012-06-07 00:17:18 +0000775ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result, bool enable_io)
Chris Lattner24943d22010-06-08 16:52:24 +0000776{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000777 if (!m_valid_session)
778 return false;
779
Caroline Tice4a461da2011-01-14 21:09:29 +0000780 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
781 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
782 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
783 // method to pass the command string directly down to Python.
784
Enrico Granatafa1f6172011-10-24 17:22:21 +0000785 Locker locker(this,
786 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
787 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000788
789 bool success = false;
790
Greg Clayton63094e02010-06-23 01:19:29 +0000791 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000792 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000793 // Find the correct script interpreter dictionary in the main module.
Enrico Granata400105d2012-03-06 23:42:15 +0000794 PyObject *script_interpreter_dict = FindSessionDictionary(m_dictionary_name.c_str());
795 if (script_interpreter_dict != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000796 {
Enrico Granata400105d2012-03-06 23:42:15 +0000797 PyObject *pfunc = (PyObject*)m_run_one_line;
Greg Clayton6f2f0ab2012-04-25 01:49:50 +0000798 PyObject *pmod = PyImport_AddModule ("lldb.embedded_interpreter");
Enrico Granata400105d2012-03-06 23:42:15 +0000799 if (pmod != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000800 {
Enrico Granata400105d2012-03-06 23:42:15 +0000801 PyObject *pmod_dict = PyModule_GetDict (pmod);
802 if ((pmod_dict != NULL)
803 && PyDict_Check (pmod_dict))
Caroline Tice4a461da2011-01-14 21:09:29 +0000804 {
Enrico Granata400105d2012-03-06 23:42:15 +0000805 if (!pfunc)
Caroline Tice4a461da2011-01-14 21:09:29 +0000806 {
807 PyObject *key, *value;
808 Py_ssize_t pos = 0;
809
810 while (PyDict_Next (pmod_dict, &pos, &key, &value))
811 {
812 Py_INCREF (key);
813 Py_INCREF (value);
814 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
815 {
816 pfunc = value;
817 break;
818 }
819 }
Enrico Granata400105d2012-03-06 23:42:15 +0000820 m_run_one_line = pfunc;
821 }
822
823 if (pfunc && PyCallable_Check (pfunc))
824 {
825 PyObject *pargs = Py_BuildValue("(Os)",script_interpreter_dict,command);
826 if (pargs != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000827 {
Enrico Granataa1ba3142012-06-07 00:17:18 +0000828 PyObject *pvalue = NULL;
829 { // scope for PythonInputReaderManager
830 PythonInputReaderManager py_input(enable_io ? this : NULL);
831 pvalue = PyObject_CallObject (pfunc, pargs);
832 }
Enrico Granata400105d2012-03-06 23:42:15 +0000833 Py_DECREF (pargs);
834 if (pvalue != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000835 {
Enrico Granata400105d2012-03-06 23:42:15 +0000836 Py_DECREF (pvalue);
837 success = true;
838 }
839 else if (PyErr_Occurred ())
840 {
841 PyErr_Print();
842 PyErr_Clear();
Caroline Tice4a461da2011-01-14 21:09:29 +0000843 }
844 }
845 }
846 }
Caroline Tice4a461da2011-01-14 21:09:29 +0000847 }
Enrico Granata400105d2012-03-06 23:42:15 +0000848 Py_INCREF (script_interpreter_dict);
Caroline Tice4a461da2011-01-14 21:09:29 +0000849 }
Greg Clayton63094e02010-06-23 01:19:29 +0000850
Caroline Tice4a461da2011-01-14 21:09:29 +0000851 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000852 return true;
853
854 // The one-liner failed. Append the error message.
855 if (result)
856 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
857 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000858 }
Johnny Chen60dde642010-07-30 22:33:14 +0000859
860 if (result)
861 result->AppendError ("empty command passed to python\n");
862 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000863}
864
Chris Lattner24943d22010-06-08 16:52:24 +0000865size_t
866ScriptInterpreterPython::InputReaderCallback
867(
868 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000869 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000870 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000871 const char *bytes,
872 size_t bytes_len
873)
874{
Caroline Tice2ade6112010-11-10 19:18:14 +0000875 lldb::thread_t embedded_interpreter_thread;
876 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
877
Chris Lattner24943d22010-06-08 16:52:24 +0000878 if (baton == NULL)
879 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000880
881 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000882
Caroline Tice0aa2e552011-01-14 00:29:16 +0000883 if (script_interpreter->m_script_lang != eScriptLanguagePython)
884 return 0;
885
Caroline Tice892fadd2011-06-16 16:27:19 +0000886 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
887 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
888
Chris Lattner24943d22010-06-08 16:52:24 +0000889 switch (notification)
890 {
891 case eInputReaderActivate:
892 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000893 if (!batch_mode)
894 {
895 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
896 out_stream->Flush();
897 }
Greg Clayton58928562011-02-09 01:08:52 +0000898
Chris Lattner24943d22010-06-08 16:52:24 +0000899 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000900 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
901 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000902 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000903
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000904 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000905
Caroline Tice202f6b82011-01-17 21:55:19 +0000906 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000907 ScriptInterpreterPython::Locker locker(script_interpreter,
908 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
909 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000910 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000911
Caroline Tice2ade6112010-11-10 19:18:14 +0000912 char error_str[1024];
913 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
914 sizeof(error_str)))
915 {
916 if (log)
917 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
918 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
919 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
920 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
921 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000922 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000923 {
924 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000925 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000926 Error detach_error;
927 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
928 }
929 else
930 {
931 if (log)
932 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
933 reader.SetIsDone (true);
934 }
935 }
936 else
937 {
938 if (log)
939 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
940 reader.SetIsDone (true);
941 }
Chris Lattner24943d22010-06-08 16:52:24 +0000942 }
943 break;
944
945 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000946 // When another input reader is pushed, don't leave the session...
947 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000948 break;
949
950 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000951 {
Greg Claytona1cec242012-01-06 00:47:38 +0000952 // Don't try and acquire the interpreter lock here because code like
953 // this:
954 //
955 // (lldb) script
956 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
957 //
958 // This will cause the process to run. The interpreter lock is taken
959 // by the input reader for the "script" command. If we try and acquire
960 // the lock here, when the process runs it might deactivate this input
961 // reader (if STDIN is hooked up to the inferior process) and
962 // reactivate it when the process stops which will deadlock.
963 //ScriptInterpreterPython::Locker locker(script_interpreter,
964 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
965 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000966 }
Chris Lattner24943d22010-06-08 16:52:24 +0000967 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000968
Caroline Tice4a348082011-05-02 20:41:46 +0000969 case eInputReaderAsynchronousOutputWritten:
970 break;
971
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000972 case eInputReaderInterrupt:
973 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
974 break;
975
976 case eInputReaderEndOfFile:
977 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
978 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000979
980 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000981 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000982 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000983 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000984 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000985 bytes_len);
986 if (bytes && bytes_len)
987 {
988 if ((int) bytes[0] == 4)
989 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
990 else
991 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
992 }
993 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000994 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000995 else
996 {
997 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000998 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000999 bytes,
1000 bytes_len);
1001 reader.SetIsDone (true);
1002 }
1003
Chris Lattner24943d22010-06-08 16:52:24 +00001004 break;
1005
1006 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +00001007 script_interpreter->LeaveSession ();
1008
Chris Lattner24943d22010-06-08 16:52:24 +00001009 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +00001010 if (log)
1011 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +00001012
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001013 script_interpreter->RestoreTerminalState ();
1014
Caroline Tice2ade6112010-11-10 19:18:14 +00001015 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +00001016 break;
1017 }
1018
1019 return bytes_len;
1020}
1021
1022
1023void
Greg Clayton238c0a12010-09-18 01:14:36 +00001024ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +00001025{
1026 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1027
Caroline Tice0aa2e552011-01-14 00:29:16 +00001028 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +00001029
1030 // At the moment, the only time the debugger does not have an input file handle is when this is called
1031 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
1032 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
1033 // do it.
1034
Greg Clayton58928562011-02-09 01:08:52 +00001035 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +00001036 return;
1037
Greg Clayton63094e02010-06-23 01:19:29 +00001038 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001039 if (reader_sp)
1040 {
1041 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
1042 this, // baton
1043 eInputReaderGranularityLine, // token size, to pass to callback function
1044 NULL, // end token
1045 NULL, // prompt
1046 true)); // echo input
1047
1048 if (error.Success())
1049 {
Greg Clayton63094e02010-06-23 01:19:29 +00001050 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +00001051 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001052 }
1053 }
1054}
1055
1056bool
1057ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +00001058 ScriptInterpreter::ScriptReturnType return_type,
Enrico Granataa1ba3142012-06-07 00:17:18 +00001059 void *ret_value,
1060 bool enable_io)
Chris Lattner24943d22010-06-08 16:52:24 +00001061{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001062
Enrico Granatafa1f6172011-10-24 17:22:21 +00001063 Locker locker(this,
1064 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1065 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001066
Chris Lattner24943d22010-06-08 16:52:24 +00001067 PyObject *py_return = NULL;
1068 PyObject *mainmod = PyImport_AddModule ("__main__");
1069 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001070 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001071 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +00001072 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001073 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001074 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001075
Enrico Granata400105d2012-03-06 23:42:15 +00001076 locals = FindSessionDictionary(m_dictionary_name.c_str());
1077
Caroline Tice0aa2e552011-01-14 00:29:16 +00001078 if (locals == NULL)
1079 {
1080 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
1081 should_decrement_locals = true;
1082 }
1083
1084 if (locals == NULL)
1085 {
1086 locals = globals;
1087 should_decrement_locals = false;
1088 }
1089
1090 py_error = PyErr_Occurred();
1091 if (py_error != NULL)
1092 PyErr_Clear();
1093
Chris Lattner24943d22010-06-08 16:52:24 +00001094 if (in_string != NULL)
1095 {
Enrico Granataa1ba3142012-06-07 00:17:18 +00001096 { // scope for PythonInputReaderManager
1097 PythonInputReaderManager py_input(enable_io ? this : NULL);
1098 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
1099 if (py_return == NULL)
1100 {
1101 py_error = PyErr_Occurred ();
1102 if (py_error != NULL)
1103 PyErr_Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +00001104
Enrico Granataa1ba3142012-06-07 00:17:18 +00001105 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
1106 }
Chris Lattner24943d22010-06-08 16:52:24 +00001107 }
1108
Caroline Tice0aa2e552011-01-14 00:29:16 +00001109 if (locals != NULL
1110 && should_decrement_locals)
1111 Py_DECREF (locals);
1112
Chris Lattner24943d22010-06-08 16:52:24 +00001113 if (py_return != NULL)
1114 {
1115 switch (return_type)
1116 {
Enrico Granata59df36f2011-10-17 21:45:27 +00001117 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +00001118 {
1119 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001120 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +00001121 break;
1122 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001123 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +00001124 {
1125 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001126 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +00001127 break;
1128 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001129 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +00001130 {
1131 const char format[2] = "b";
1132 success = PyArg_Parse (py_return, format, (bool *) ret_value);
1133 break;
1134 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001135 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +00001136 {
1137 const char format[2] = "h";
1138 success = PyArg_Parse (py_return, format, (short *) ret_value);
1139 break;
1140 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001141 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001142 {
1143 const char format[2] = "H";
1144 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
1145 break;
1146 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001147 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +00001148 {
1149 const char format[2] = "i";
1150 success = PyArg_Parse (py_return, format, (int *) ret_value);
1151 break;
1152 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001153 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001154 {
1155 const char format[2] = "I";
1156 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
1157 break;
1158 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001159 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +00001160 {
1161 const char format[2] = "l";
1162 success = PyArg_Parse (py_return, format, (long *) ret_value);
1163 break;
1164 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001165 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001166 {
1167 const char format[2] = "k";
1168 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
1169 break;
1170 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001171 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +00001172 {
1173 const char format[2] = "L";
1174 success = PyArg_Parse (py_return, format, (long long *) ret_value);
1175 break;
1176 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001177 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001178 {
1179 const char format[2] = "K";
1180 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
1181 break;
1182 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001183 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +00001184 {
1185 const char format[2] = "f";
1186 success = PyArg_Parse (py_return, format, (float *) ret_value);
1187 break;
1188 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001189 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +00001190 {
1191 const char format[2] = "d";
1192 success = PyArg_Parse (py_return, format, (double *) ret_value);
1193 break;
1194 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001195 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +00001196 {
1197 const char format[2] = "c";
1198 success = PyArg_Parse (py_return, format, (char *) ret_value);
1199 break;
1200 }
1201 default:
1202 {}
1203 }
1204 Py_DECREF (py_return);
1205 if (success)
1206 ret_success = true;
1207 else
1208 ret_success = false;
1209 }
1210 }
1211
1212 py_error = PyErr_Occurred();
1213 if (py_error != NULL)
1214 {
1215 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1216 PyErr_Print ();
1217 PyErr_Clear();
1218 ret_success = false;
1219 }
Caroline Tice202f6b82011-01-17 21:55:19 +00001220
Chris Lattner24943d22010-06-08 16:52:24 +00001221 return ret_success;
1222}
1223
1224bool
Enrico Granataa1ba3142012-06-07 00:17:18 +00001225ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string, bool enable_io)
Chris Lattner24943d22010-06-08 16:52:24 +00001226{
Enrico Granatafa1f6172011-10-24 17:22:21 +00001227
1228
1229 Locker locker(this,
1230 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1231 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001232
Chris Lattner24943d22010-06-08 16:52:24 +00001233 bool success = false;
1234 PyObject *py_return = NULL;
1235 PyObject *mainmod = PyImport_AddModule ("__main__");
1236 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001237 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001238 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001239 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001240
Enrico Granata400105d2012-03-06 23:42:15 +00001241 locals = FindSessionDictionary(m_dictionary_name.c_str());
1242
Caroline Tice0aa2e552011-01-14 00:29:16 +00001243 if (locals == NULL)
1244 {
1245 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
1246 should_decrement_locals = true;
1247 }
1248
1249 if (locals == NULL)
1250 {
1251 locals = globals;
1252 should_decrement_locals = false;
1253 }
1254
1255 py_error = PyErr_Occurred();
1256 if (py_error != NULL)
1257 PyErr_Clear();
1258
Chris Lattner24943d22010-06-08 16:52:24 +00001259 if (in_string != NULL)
1260 {
1261 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
1262 if (compiled_node)
1263 {
1264 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
1265 if (compiled_code)
1266 {
Enrico Granataa1ba3142012-06-07 00:17:18 +00001267 { // scope for PythonInputReaderManager
1268 PythonInputReaderManager py_input(enable_io ? this : NULL);
1269 py_return = PyEval_EvalCode (compiled_code, globals, locals);
1270 }
Chris Lattner24943d22010-06-08 16:52:24 +00001271 if (py_return != NULL)
1272 {
1273 success = true;
1274 Py_DECREF (py_return);
1275 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001276 if (locals && should_decrement_locals)
1277 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +00001278 }
1279 }
1280 }
1281
1282 py_error = PyErr_Occurred ();
1283 if (py_error != NULL)
1284 {
1285 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1286 PyErr_Print ();
1287 PyErr_Clear();
1288 success = false;
1289 }
1290
1291 return success;
1292}
1293
1294static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1295
1296size_t
1297ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1298(
1299 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001300 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001301 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001302 const char *bytes,
1303 size_t bytes_len
1304)
1305{
Caroline Tice892fadd2011-06-16 16:27:19 +00001306 static StringList commands_in_progress;
1307
1308 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1309 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1310
Chris Lattner24943d22010-06-08 16:52:24 +00001311 switch (notification)
1312 {
1313 case eInputReaderActivate:
1314 {
1315 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +00001316 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +00001317 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001318 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001319 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +00001320 out_stream->Printf ("%s", reader.GetPrompt());
1321 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001322 }
1323 }
1324 break;
1325
1326 case eInputReaderDeactivate:
1327 break;
1328
1329 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001330 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001331 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001332 out_stream->Printf ("%s", reader.GetPrompt());
1333 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001334 }
Chris Lattner24943d22010-06-08 16:52:24 +00001335 break;
1336
Caroline Tice4a348082011-05-02 20:41:46 +00001337 case eInputReaderAsynchronousOutputWritten:
1338 break;
1339
Chris Lattner24943d22010-06-08 16:52:24 +00001340 case eInputReaderGotToken:
1341 {
1342 std::string temp_string (bytes, bytes_len);
1343 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001344 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001345 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001346 out_stream->Printf ("%s", reader.GetPrompt());
1347 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001348 }
Chris Lattner24943d22010-06-08 16:52:24 +00001349 }
1350 break;
1351
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001352 case eInputReaderEndOfFile:
1353 case eInputReaderInterrupt:
1354 // Control-c (SIGINT) & control-d both mean finish & exit.
1355 reader.SetIsDone(true);
1356
1357 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1358 if (notification == eInputReaderInterrupt)
1359 commands_in_progress.Clear();
1360
1361 // Fall through here...
1362
Chris Lattner24943d22010-06-08 16:52:24 +00001363 case eInputReaderDone:
1364 {
1365 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1366 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1367 data_ap->user_source.AppendList (commands_in_progress);
1368 if (data_ap.get())
1369 {
Greg Clayton63094e02010-06-23 01:19:29 +00001370 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001371 if (interpreter)
1372 {
1373 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1374 data_ap->script_source))
1375 {
Enrico Granata400105d2012-03-06 23:42:15 +00001376 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1377 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001378 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001379 else if (!batch_mode)
1380 {
1381 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1382 out_stream->Flush();
1383 }
Chris Lattner24943d22010-06-08 16:52:24 +00001384 }
1385 else
1386 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001387 if (!batch_mode)
1388 {
1389 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1390 out_stream->Flush();
1391 }
Chris Lattner24943d22010-06-08 16:52:24 +00001392 }
1393 }
1394 }
1395 break;
1396
1397 }
1398
1399 return bytes_len;
1400}
1401
Johnny Chenf3ec4612012-08-09 23:09:42 +00001402size_t
1403ScriptInterpreterPython::GenerateWatchpointOptionsCommandCallback
1404(
1405 void *baton,
1406 InputReader &reader,
1407 InputReaderAction notification,
1408 const char *bytes,
1409 size_t bytes_len
1410)
1411{
1412 static StringList commands_in_progress;
1413
1414 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1415 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1416
1417 switch (notification)
1418 {
1419 case eInputReaderActivate:
1420 {
1421 commands_in_progress.Clear();
1422 if (!batch_mode)
1423 {
1424 out_stream->Printf ("%s\n", g_reader_instructions);
1425 if (reader.GetPrompt())
1426 out_stream->Printf ("%s", reader.GetPrompt());
1427 out_stream->Flush ();
1428 }
1429 }
1430 break;
1431
1432 case eInputReaderDeactivate:
1433 break;
1434
1435 case eInputReaderReactivate:
1436 if (reader.GetPrompt() && !batch_mode)
1437 {
1438 out_stream->Printf ("%s", reader.GetPrompt());
1439 out_stream->Flush ();
1440 }
1441 break;
1442
1443 case eInputReaderAsynchronousOutputWritten:
1444 break;
1445
1446 case eInputReaderGotToken:
1447 {
1448 std::string temp_string (bytes, bytes_len);
1449 commands_in_progress.AppendString (temp_string.c_str());
1450 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
1451 {
1452 out_stream->Printf ("%s", reader.GetPrompt());
1453 out_stream->Flush ();
1454 }
1455 }
1456 break;
1457
1458 case eInputReaderEndOfFile:
1459 case eInputReaderInterrupt:
1460 // Control-c (SIGINT) & control-d both mean finish & exit.
1461 reader.SetIsDone(true);
1462
1463 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1464 if (notification == eInputReaderInterrupt)
1465 commands_in_progress.Clear();
1466
1467 // Fall through here...
1468
1469 case eInputReaderDone:
1470 {
1471 WatchpointOptions *wp_options = (WatchpointOptions *)baton;
1472 std::auto_ptr<WatchpointOptions::CommandData> data_ap(new WatchpointOptions::CommandData());
1473 data_ap->user_source.AppendList (commands_in_progress);
1474 if (data_ap.get())
1475 {
1476 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
1477 if (interpreter)
1478 {
1479 if (interpreter->GenerateWatchpointCommandCallbackData (data_ap->user_source,
1480 data_ap->script_source))
1481 {
1482 BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release()));
1483 wp_options->SetCallback (ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp);
1484 }
1485 else if (!batch_mode)
1486 {
1487 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1488 out_stream->Flush();
1489 }
1490 }
1491 else
1492 {
1493 if (!batch_mode)
1494 {
1495 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1496 out_stream->Flush();
1497 }
1498 }
1499 }
1500 }
1501 break;
1502
1503 }
1504
1505 return bytes_len;
1506}
1507
Chris Lattner24943d22010-06-08 16:52:24 +00001508void
Greg Clayton238c0a12010-09-18 01:14:36 +00001509ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001510 CommandReturnObject &result)
1511{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001512 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1513
Greg Clayton63094e02010-06-23 01:19:29 +00001514 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001515
1516 if (reader_sp)
1517 {
1518 Error err = reader_sp->Initialize (
1519 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1520 bp_options, // baton
1521 eInputReaderGranularityLine, // token size, for feeding data to callback function
1522 "DONE", // end token
1523 "> ", // prompt
1524 true); // echo input
1525
1526 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001527 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001528 else
1529 {
1530 result.AppendError (err.AsCString());
1531 result.SetStatus (eReturnStatusFailed);
1532 }
1533 }
1534 else
1535 {
1536 result.AppendError("out of memory");
1537 result.SetStatus (eReturnStatusFailed);
1538 }
1539}
1540
Johnny Chenf3ec4612012-08-09 23:09:42 +00001541void
1542ScriptInterpreterPython::CollectDataForWatchpointCommandCallback (WatchpointOptions *wp_options,
1543 CommandReturnObject &result)
1544{
1545 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1546
1547 InputReaderSP reader_sp (new InputReader (debugger));
1548
1549 if (reader_sp)
1550 {
1551 Error err = reader_sp->Initialize (
1552 ScriptInterpreterPython::GenerateWatchpointOptionsCommandCallback,
1553 wp_options, // baton
1554 eInputReaderGranularityLine, // token size, for feeding data to callback function
1555 "DONE", // end token
1556 "> ", // prompt
1557 true); // echo input
1558
1559 if (err.Success())
1560 debugger.PushInputReader (reader_sp);
1561 else
1562 {
1563 result.AppendError (err.AsCString());
1564 result.SetStatus (eReturnStatusFailed);
1565 }
1566 }
1567 else
1568 {
1569 result.AppendError("out of memory");
1570 result.SetStatus (eReturnStatusFailed);
1571 }
1572}
1573
Johnny Chen3e0571b2010-09-11 00:23:59 +00001574// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001575void
Greg Clayton238c0a12010-09-18 01:14:36 +00001576ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001577 const char *oneliner)
1578{
1579 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1580
1581 // It's necessary to set both user_source and script_source to the oneliner.
1582 // The former is used to generate callback description (as in breakpoint command list)
1583 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001584
Johnny Chend1c2dca2010-09-10 18:21:10 +00001585 data_ap->user_source.AppendString (oneliner);
Johnny Chenf3ec4612012-08-09 23:09:42 +00001586 data_ap->script_source.assign (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001587
Caroline Tice5136f942010-09-27 21:35:15 +00001588 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1589 {
Enrico Granata400105d2012-03-06 23:42:15 +00001590 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1591 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Caroline Tice5136f942010-09-27 21:35:15 +00001592 }
1593
Johnny Chend1c2dca2010-09-10 18:21:10 +00001594 return;
1595}
1596
Johnny Chenf3ec4612012-08-09 23:09:42 +00001597// Set a Python one-liner as the callback for the watchpoint.
1598void
1599ScriptInterpreterPython::SetWatchpointCommandCallback (WatchpointOptions *wp_options,
1600 const char *oneliner)
1601{
1602 std::auto_ptr<WatchpointOptions::CommandData> data_ap(new WatchpointOptions::CommandData());
1603
1604 // It's necessary to set both user_source and script_source to the oneliner.
1605 // The former is used to generate callback description (as in watchpoint command list)
1606 // while the latter is used for Python to interpret during the actual callback.
1607
1608 data_ap->user_source.AppendString (oneliner);
1609 data_ap->script_source.assign (oneliner);
1610
1611 if (GenerateWatchpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1612 {
1613 BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release()));
1614 wp_options->SetCallback (ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp);
1615 }
1616
1617 return;
1618}
1619
Chris Lattner24943d22010-06-08 16:52:24 +00001620bool
1621ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1622{
1623 // Convert StringList to one long, newline delimited, const char *.
Enrico Granata400105d2012-03-06 23:42:15 +00001624 std::string function_def_string(function_def.CopyList());
Chris Lattner24943d22010-06-08 16:52:24 +00001625
Enrico Granataa1ba3142012-06-07 00:17:18 +00001626 return ExecuteMultipleLines (function_def_string.c_str(), false);
Chris Lattner24943d22010-06-08 16:52:24 +00001627}
1628
Enrico Granataf7a9b142011-07-15 02:26:42 +00001629bool
Enrico Granata400105d2012-03-06 23:42:15 +00001630ScriptInterpreterPython::GenerateFunction(const char *signature, const StringList &input)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001631{
1632 int num_lines = input.GetSize ();
1633 if (num_lines == 0)
1634 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001635
1636 if (!signature || *signature == 0)
1637 return false;
1638
Enrico Granataf7a9b142011-07-15 02:26:42 +00001639 StreamString sstr;
1640 StringList auto_generated_function;
Enrico Granata400105d2012-03-06 23:42:15 +00001641 auto_generated_function.AppendString (signature);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001642 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001643 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 +00001644 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001645 auto_generated_function.AppendString (" global_dict.update (internal_dict)"); // Add the session dictionary to the
Enrico Granataf7a9b142011-07-15 02:26:42 +00001646 // global dictionary.
1647
1648 // Wrap everything up inside the function, increasing the indentation.
1649
1650 for (int i = 0; i < num_lines; ++i)
1651 {
1652 sstr.Clear ();
1653 sstr.Printf (" %s", input.GetStringAtIndex (i));
1654 auto_generated_function.AppendString (sstr.GetData());
1655 }
1656 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001657 auto_generated_function.AppendString (" internal_dict[key] = global_dict[key]"); // Update session dict values
Enrico Granataf7a9b142011-07-15 02:26:42 +00001658 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1659 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1660
1661 // Verify that the results are valid Python.
1662
1663 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1664 return false;
1665
1666 return true;
1667
1668}
1669
Enrico Granataf7a9b142011-07-15 02:26:42 +00001670bool
Enrico Granata400105d2012-03-06 23:42:15 +00001671ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001672{
Enrico Granata400105d2012-03-06 23:42:15 +00001673 static uint32_t num_created_functions = 0;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001674 user_input.RemoveBlankLines ();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001675 StreamString sstr;
1676
1677 // Check to see if we have any data; if not, just return.
1678 if (user_input.GetSize() == 0)
1679 return false;
1680
1681 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1682 // ValueObject as parameter to the function.
1683
Enrico Granata400105d2012-03-06 23:42:15 +00001684 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 +00001685 sstr.Printf ("def %s (valobj, internal_dict):", auto_generated_function_name.c_str());
Enrico Granataf7a9b142011-07-15 02:26:42 +00001686
Enrico Granata400105d2012-03-06 23:42:15 +00001687 if (!GenerateFunction(sstr.GetData(), user_input))
Enrico Granataf7a9b142011-07-15 02:26:42 +00001688 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001689
Enrico Granataf7a9b142011-07-15 02:26:42 +00001690 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001691 output.assign(auto_generated_function_name);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001692 return true;
1693}
1694
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001695bool
Enrico Granata400105d2012-03-06 23:42:15 +00001696ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, std::string &output)
Enrico Granatac2a28252011-08-16 16:49:25 +00001697{
Enrico Granata400105d2012-03-06 23:42:15 +00001698 static uint32_t num_created_functions = 0;
Enrico Granatac2a28252011-08-16 16:49:25 +00001699 user_input.RemoveBlankLines ();
Enrico Granatac2a28252011-08-16 16:49:25 +00001700 StreamString sstr;
1701
1702 // Check to see if we have any data; if not, just return.
1703 if (user_input.GetSize() == 0)
1704 return false;
1705
Enrico Granata400105d2012-03-06 23:42:15 +00001706 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_cmd_alias_func", num_created_functions));
1707
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001708 sstr.Printf ("def %s (debugger, args, result, internal_dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001709
Enrico Granata400105d2012-03-06 23:42:15 +00001710 if (!GenerateFunction(sstr.GetData(),user_input))
Enrico Granatac2a28252011-08-16 16:49:25 +00001711 return false;
1712
1713 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001714 output.assign(auto_generated_function_name);
Enrico Granatac2a28252011-08-16 16:49:25 +00001715 return true;
1716}
1717
1718
1719bool
Enrico Granata400105d2012-03-06 23:42:15 +00001720ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, std::string &output, void* name_token)
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001721{
Enrico Granata400105d2012-03-06 23:42:15 +00001722 static uint32_t num_created_classes = 0;
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001723 user_input.RemoveBlankLines ();
1724 int num_lines = user_input.GetSize ();
1725 StreamString sstr;
1726
1727 // Check to see if we have any data; if not, just return.
1728 if (user_input.GetSize() == 0)
1729 return false;
1730
1731 // Wrap all user input into a Python class
1732
Enrico Granata400105d2012-03-06 23:42:15 +00001733 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 +00001734
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001735 StringList auto_generated_class;
1736
1737 // Create the function name & definition string.
1738
1739 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1740 auto_generated_class.AppendString (sstr.GetData());
1741
1742 // Wrap everything up inside the class, increasing the indentation.
1743
1744 for (int i = 0; i < num_lines; ++i)
1745 {
1746 sstr.Clear ();
1747 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1748 auto_generated_class.AppendString (sstr.GetData());
1749 }
1750
1751
1752 // Verify that the results are valid Python.
1753 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1754 // (TODO: rename that method to ExportDefinitionToInterpreter)
1755 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1756 return false;
1757
1758 // Store the name of the auto-generated class
1759
Enrico Granata400105d2012-03-06 23:42:15 +00001760 output.assign(auto_generated_class_name);
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001761 return true;
1762}
1763
Enrico Granata400105d2012-03-06 23:42:15 +00001764lldb::ScriptInterpreterObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001765ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1766 lldb::ValueObjectSP valobj)
1767{
1768 if (class_name.empty())
Enrico Granata400105d2012-03-06 23:42:15 +00001769 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001770
1771 if (!valobj.get())
Enrico Granata400105d2012-03-06 23:42:15 +00001772 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001773
Greg Claytonb4d7fc02012-02-17 07:49:44 +00001774 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1775 Target *target = exe_ctx.GetTargetPtr();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001776
1777 if (!target)
Enrico Granata400105d2012-03-06 23:42:15 +00001778 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001779
1780 Debugger &debugger = target->GetDebugger();
1781 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1782 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1783
1784 if (!script_interpreter)
Enrico Granata400105d2012-03-06 23:42:15 +00001785 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001786
1787 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001788
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001789 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001790 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001791 ForceDisableSyntheticChildren no_synthetics(target);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001792 ret_val = g_swig_synthetic_script (class_name,
1793 python_interpreter->m_dictionary_name.c_str(),
1794 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001795 }
1796
Enrico Granata400105d2012-03-06 23:42:15 +00001797 return MakeScriptObject(ret_val);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001798}
1799
Enrico Granataf7a9b142011-07-15 02:26:42 +00001800bool
Enrico Granata400105d2012-03-06 23:42:15 +00001801ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001802{
Enrico Granata16376ed2012-02-15 02:34:21 +00001803 StringList input;
1804 input.SplitIntoLines(oneliner, strlen(oneliner));
1805 return GenerateTypeScriptFunction(input, output, name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001806}
1807
Chris Lattner24943d22010-06-08 16:52:24 +00001808bool
Enrico Granata400105d2012-03-06 23:42:15 +00001809ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, std::string& output, void* name_token)
Enrico Granata16376ed2012-02-15 02:34:21 +00001810{
1811 StringList input;
1812 input.SplitIntoLines(oneliner, strlen(oneliner));
1813 return GenerateTypeSynthClass(input, output, name_token);
1814}
1815
1816
1817bool
Enrico Granata400105d2012-03-06 23:42:15 +00001818ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, std::string& output)
Chris Lattner24943d22010-06-08 16:52:24 +00001819{
Enrico Granata400105d2012-03-06 23:42:15 +00001820 static uint32_t num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001821 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001822 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001823
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001824 if (user_input.GetSize() == 0)
1825 return false;
1826
Enrico Granata400105d2012-03-06 23:42:15 +00001827 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_bp_callback_func_",num_created_functions));
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001828 sstr.Printf ("def %s (frame, bp_loc, internal_dict):", auto_generated_function_name.c_str());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001829
Enrico Granata400105d2012-03-06 23:42:15 +00001830 if (!GenerateFunction(sstr.GetData(), user_input))
Caroline Ticeb447e842010-09-21 19:25:28 +00001831 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001832
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001833 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001834 output.assign(auto_generated_function_name);
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001835 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001836}
1837
Enrico Granata1328b142012-02-29 03:28:49 +00001838bool
Johnny Chenf3ec4612012-08-09 23:09:42 +00001839ScriptInterpreterPython::GenerateWatchpointCommandCallbackData (StringList &user_input, std::string& output)
1840{
1841 static uint32_t num_created_functions = 0;
1842 user_input.RemoveBlankLines ();
1843 StreamString sstr;
1844
1845 if (user_input.GetSize() == 0)
1846 return false;
1847
1848 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_wp_callback_func_",num_created_functions));
1849 sstr.Printf ("def %s (frame, wp, internal_dict):", auto_generated_function_name.c_str());
1850
1851 if (!GenerateFunction(sstr.GetData(), user_input))
1852 return false;
1853
1854 // Store the name of the auto-generated function to be called.
1855 output.assign(auto_generated_function_name);
1856 return true;
1857}
1858
1859bool
Enrico Granata1328b142012-02-29 03:28:49 +00001860ScriptInterpreterPython::GetScriptedSummary (const char *python_function_name,
1861 lldb::ValueObjectSP valobj,
1862 lldb::ScriptInterpreterObjectSP& callee_wrapper_sp,
1863 std::string& retval)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001864{
1865
Enrico Granata1328b142012-02-29 03:28:49 +00001866 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001867
1868 if (!valobj.get())
Enrico Granata1328b142012-02-29 03:28:49 +00001869 {
1870 retval.assign("<no object>");
1871 return false;
1872 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001873
Enrico Granata1328b142012-02-29 03:28:49 +00001874 void* old_callee = (callee_wrapper_sp ? callee_wrapper_sp->GetObject() : NULL);
1875 void* new_callee = old_callee;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001876
Enrico Granata1328b142012-02-29 03:28:49 +00001877 bool ret_val;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001878 if (python_function_name
1879 && *python_function_name)
1880 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001881 {
Enrico Granata1328b142012-02-29 03:28:49 +00001882 Locker py_lock(this);
1883 {
1884 Timer scoped_timer ("g_swig_typescript_callback","g_swig_typescript_callback");
1885 ret_val = g_swig_typescript_callback (python_function_name,
1886 FindSessionDictionary(m_dictionary_name.c_str()),
1887 valobj,
1888 &new_callee,
1889 retval);
1890 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001891 }
1892 }
1893 else
Enrico Granata1328b142012-02-29 03:28:49 +00001894 {
1895 retval.assign("<no function name>");
1896 return false;
1897 }
1898
1899 if (new_callee && old_callee != new_callee)
1900 callee_wrapper_sp = MakeScriptObject(new_callee);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001901
1902 return ret_val;
1903
1904}
1905
Greg Clayton5144f382010-10-07 17:14:24 +00001906bool
1907ScriptInterpreterPython::BreakpointCallbackFunction
1908(
1909 void *baton,
1910 StoppointCallbackContext *context,
1911 user_id_t break_id,
1912 user_id_t break_loc_id
1913)
1914{
1915 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
Enrico Granata400105d2012-03-06 23:42:15 +00001916 const char *python_function_name = bp_option_data->script_source.c_str();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001917
1918 if (!context)
1919 return true;
1920
Greg Claytonf4124de2012-02-21 00:09:25 +00001921 ExecutionContext exe_ctx (context->exe_ctx_ref);
1922 Target *target = exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001923
1924 if (!target)
1925 return true;
1926
1927 Debugger &debugger = target->GetDebugger();
1928 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1929 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1930
1931 if (!script_interpreter)
1932 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001933
1934 if (python_function_name != NULL
1935 && python_function_name[0] != '\0')
1936 {
Greg Claytonf4124de2012-02-21 00:09:25 +00001937 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001938 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001939 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001940 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001941 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1942
1943 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001944 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001945 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001946 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001947 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001948 ret_val = g_swig_breakpoint_callback (python_function_name,
1949 python_interpreter->m_dictionary_name.c_str(),
1950 stop_frame_sp,
1951 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001952 }
1953 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001954 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001955 }
Greg Clayton5144f382010-10-07 17:14:24 +00001956 }
1957 // We currently always true so we stop in case anything goes wrong when
1958 // trying to call the script function
1959 return true;
1960}
Caroline Tice2ade6112010-11-10 19:18:14 +00001961
Johnny Chenf3ec4612012-08-09 23:09:42 +00001962bool
1963ScriptInterpreterPython::WatchpointCallbackFunction
1964(
1965 void *baton,
1966 StoppointCallbackContext *context,
1967 user_id_t watch_id
1968)
1969{
1970 WatchpointOptions::CommandData *wp_option_data = (WatchpointOptions::CommandData *) baton;
1971 const char *python_function_name = wp_option_data->script_source.c_str();
1972
1973 if (!context)
1974 return true;
1975
1976 ExecutionContext exe_ctx (context->exe_ctx_ref);
1977 Target *target = exe_ctx.GetTargetPtr();
1978
1979 if (!target)
1980 return true;
1981
1982 Debugger &debugger = target->GetDebugger();
1983 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1984 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1985
1986 if (!script_interpreter)
1987 return true;
1988
1989 if (python_function_name != NULL
1990 && python_function_name[0] != '\0')
1991 {
1992 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
1993 WatchpointSP wp_sp = target->GetWatchpointList().FindByID (watch_id);
1994 if (wp_sp)
1995 {
1996 if (stop_frame_sp && wp_sp)
1997 {
1998 bool ret_val = true;
1999 {
2000 Locker py_lock(python_interpreter);
2001 ret_val = g_swig_watchpoint_callback (python_function_name,
2002 python_interpreter->m_dictionary_name.c_str(),
2003 stop_frame_sp,
2004 wp_sp);
2005 }
2006 return ret_val;
2007 }
2008 }
2009 }
2010 // We currently always true so we stop in case anything goes wrong when
2011 // trying to call the script function
2012 return true;
2013}
2014
Caroline Tice2ade6112010-11-10 19:18:14 +00002015lldb::thread_result_t
2016ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
2017{
2018 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
2019
2020 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
2021
2022 if (log)
2023 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
2024
2025 char error_str[1024];
2026 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00002027
Enrico Granatafa1f6172011-10-24 17:22:21 +00002028 Locker locker(script_interpreter,
2029 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
2030 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
2031
2032 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00002033 {
Caroline Tice2ade6112010-11-10 19:18:14 +00002034 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00002035
Caroline Tice0aa2e552011-01-14 00:29:16 +00002036 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
2037 PyRun_SimpleString (run_string.GetData());
2038 run_string.Clear ();
2039
2040 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
2041 PyRun_SimpleString (run_string.GetData());
2042 run_string.Clear ();
2043
2044 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
2045 PyRun_SimpleString (run_string.GetData());
2046 run_string.Clear ();
2047
2048 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
2049 pty_slave_name);
2050 PyRun_SimpleString (run_string.GetData());
2051 run_string.Clear ();
2052
Johnny Chen8054ba32011-03-11 00:28:50 +00002053 // The following call drops into the embedded interpreter loop and stays there until the
2054 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00002055
Caroline Ticece207c12011-03-11 00:21:55 +00002056 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00002057 // the ability to run multi-threaded stuff, so we need to surround the call to the embedded interpreter with
Caroline Ticece207c12011-03-11 00:21:55 +00002058 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
2059
2060 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
2061 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
2062 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
2063 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
2064 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
2065 // hang (it's happened before).
2066
Caroline Tice9d352ce2011-03-07 23:24:28 +00002067 Py_BEGIN_ALLOW_THREADS
2068 PyGILState_STATE gstate = PyGILState_Ensure();
2069
Caroline Tice0aa2e552011-01-14 00:29:16 +00002070 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
2071 PyRun_SimpleString (run_string.GetData());
2072 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00002073
Caroline Tice9d352ce2011-03-07 23:24:28 +00002074 PyGILState_Release (gstate);
2075 Py_END_ALLOW_THREADS
2076
Caroline Tice0aa2e552011-01-14 00:29:16 +00002077 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
2078 PyRun_SimpleString (run_string.GetData());
2079 run_string.Clear();
2080
2081 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
2082 PyRun_SimpleString (run_string.GetData());
2083 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00002084
Caroline Tice2ade6112010-11-10 19:18:14 +00002085 }
2086
2087 if (script_interpreter->m_embedded_thread_input_reader_sp)
2088 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
2089
2090 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002091
Caroline Tice2ade6112010-11-10 19:18:14 +00002092 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
2093 if (log)
2094 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
2095
2096
Johnny Chen8054ba32011-03-11 00:28:50 +00002097 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00002098 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00002099 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
2100 script_interpreter->m_embedded_thread_input_reader_sp.reset();
2101 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002102
Caroline Tice2ade6112010-11-10 19:18:14 +00002103 return NULL;
2104}
2105
Enrico Granataa1ba3142012-06-07 00:17:18 +00002106lldb::thread_result_t
2107ScriptInterpreterPython::PythonInputReaderManager::RunPythonInputReader (lldb::thread_arg_t baton)
2108{
2109 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
2110
2111 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
2112
2113 if (reader_sp)
2114 reader_sp->WaitOnReaderIsDone();
2115
2116 return NULL;
2117}
2118
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002119uint32_t
Enrico Granata400105d2012-03-06 23:42:15 +00002120ScriptInterpreterPython::CalculateNumChildren (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002121{
Enrico Granata400105d2012-03-06 23:42:15 +00002122 if (!implementor_sp)
2123 return 0;
2124
2125 void* implementor = implementor_sp->GetObject();
2126
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002127 if (!implementor)
2128 return 0;
2129
2130 if (!g_swig_calc_children)
2131 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00002132
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002133 uint32_t ret_val = 0;
2134
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002135 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002136 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00002137 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002138 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002139 }
2140
2141 return ret_val;
2142}
2143
Enrico Granata91544802011-09-06 19:20:51 +00002144lldb::ValueObjectSP
Enrico Granata400105d2012-03-06 23:42:15 +00002145ScriptInterpreterPython::GetChildAtIndex (const lldb::ScriptInterpreterObjectSP& implementor_sp, uint32_t idx)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002146{
Enrico Granata400105d2012-03-06 23:42:15 +00002147 if (!implementor_sp)
2148 return lldb::ValueObjectSP();
2149
2150 void* implementor = implementor_sp->GetObject();
2151
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002152 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00002153 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002154
Enrico Granata91544802011-09-06 19:20:51 +00002155 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
2156 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002157
Enrico Granata91544802011-09-06 19:20:51 +00002158 void* child_ptr = NULL;
2159 lldb::SBValue* value_sb = NULL;
2160 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002161
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002162 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002163 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00002164 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata91544802011-09-06 19:20:51 +00002165 child_ptr = g_swig_get_child_index (implementor,idx);
2166 if (child_ptr != NULL && child_ptr != Py_None)
2167 {
2168 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
2169 if (value_sb == NULL)
2170 Py_XDECREF(child_ptr);
2171 else
2172 ret_val = value_sb->get_sp();
2173 }
2174 else
2175 {
2176 Py_XDECREF(child_ptr);
2177 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002178 }
2179
2180 return ret_val;
2181}
2182
2183int
Enrico Granata400105d2012-03-06 23:42:15 +00002184ScriptInterpreterPython::GetIndexOfChildWithName (const lldb::ScriptInterpreterObjectSP& implementor_sp, const char* child_name)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002185{
Enrico Granata400105d2012-03-06 23:42:15 +00002186 if (!implementor_sp)
2187 return UINT32_MAX;
2188
2189 void* implementor = implementor_sp->GetObject();
2190
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002191 if (!implementor)
2192 return UINT32_MAX;
2193
2194 if (!g_swig_get_index_child)
2195 return UINT32_MAX;
2196
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002197 int ret_val = UINT32_MAX;
2198
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002199 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002200 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00002201 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002202 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002203 }
2204
2205 return ret_val;
2206}
2207
Enrico Granatacf09f882012-03-19 22:58:49 +00002208bool
Enrico Granata400105d2012-03-06 23:42:15 +00002209ScriptInterpreterPython::UpdateSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata979e20d2011-07-29 19:53:35 +00002210{
Enrico Granatacf09f882012-03-19 22:58:49 +00002211 bool ret_val = false;
2212
Enrico Granata400105d2012-03-06 23:42:15 +00002213 if (!implementor_sp)
Enrico Granatacf09f882012-03-19 22:58:49 +00002214 return ret_val;
Enrico Granata400105d2012-03-06 23:42:15 +00002215
2216 void* implementor = implementor_sp->GetObject();
2217
Enrico Granata979e20d2011-07-29 19:53:35 +00002218 if (!implementor)
Enrico Granatacf09f882012-03-19 22:58:49 +00002219 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00002220
2221 if (!g_swig_update_provider)
Enrico Granatacf09f882012-03-19 22:58:49 +00002222 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00002223
Enrico Granata979e20d2011-07-29 19:53:35 +00002224 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002225 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00002226 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granatacf09f882012-03-19 22:58:49 +00002227 ret_val = g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00002228 }
2229
Enrico Granatacf09f882012-03-19 22:58:49 +00002230 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00002231}
2232
Enrico Granatac2a28252011-08-16 16:49:25 +00002233bool
Enrico Granata59df36f2011-10-17 21:45:27 +00002234ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00002235 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00002236 lldb_private::Error& error)
2237{
2238 if (!pathname || !pathname[0])
2239 {
2240 error.SetErrorString("invalid pathname");
2241 return false;
2242 }
2243
2244 if (!g_swig_call_module_init)
2245 {
2246 error.SetErrorString("internal helper function missing");
2247 return false;
2248 }
2249
Greg Clayton13d24fb2012-01-29 20:56:30 +00002250 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granatafa1f6172011-10-24 17:22:21 +00002251
Enrico Granata59df36f2011-10-17 21:45:27 +00002252 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002253 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00002254
2255 FileSpec target_file(pathname, true);
2256
2257 // TODO: would we want to reject any other value?
2258 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
2259 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
2260 {
2261 error.SetErrorString("invalid pathname");
2262 return false;
2263 }
2264
2265 const char* directory = target_file.GetDirectory().GetCString();
2266 std::string basename(target_file.GetFilename().GetCString());
2267
2268 // now make sure that Python has "directory" in the search path
2269 StreamString command_stream;
2270 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
2271 directory,
2272 directory);
Enrico Granataa1ba3142012-06-07 00:17:18 +00002273 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData(), false);
Enrico Granata59df36f2011-10-17 21:45:27 +00002274 if (!syspath_retval)
2275 {
2276 error.SetErrorString("Python sys.path handling failed");
2277 return false;
2278 }
2279
2280 // strip .py or .pyc extension
2281 ConstString extension = target_file.GetFileNameExtension();
2282 if (::strcmp(extension.GetCString(), "py") == 0)
2283 basename.resize(basename.length()-3);
2284 else if(::strcmp(extension.GetCString(), "pyc") == 0)
2285 basename.resize(basename.length()-4);
2286
2287 // check if the module is already import-ed
2288 command_stream.Clear();
2289 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
2290 int refcount = 0;
2291 // this call will fail if the module does not exist (because the parameter to it is not a string
2292 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00002293 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
Enrico Granataa1ba3142012-06-07 00:17:18 +00002294 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount, false) && refcount > 0);
Enrico Granata6010ace2011-11-07 22:57:04 +00002295 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00002296 {
2297 error.SetErrorString("module already imported");
2298 return false;
2299 }
2300
2301 // now actually do the import
2302 command_stream.Clear();
2303 command_stream.Printf("import %s",basename.c_str());
Enrico Granataa1ba3142012-06-07 00:17:18 +00002304 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL, false);
Enrico Granata59df36f2011-10-17 21:45:27 +00002305 if (!import_retval)
2306 {
2307 error.SetErrorString("Python import statement failed");
2308 return false;
2309 }
2310
Enrico Granata16376ed2012-02-15 02:34:21 +00002311 // call __lldb_init_module(debugger,dict)
Enrico Granata59df36f2011-10-17 21:45:27 +00002312 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00002313 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00002314 debugger_sp))
2315 {
Enrico Granata16376ed2012-02-15 02:34:21 +00002316 error.SetErrorString("calling __lldb_init_module failed");
Enrico Granata59df36f2011-10-17 21:45:27 +00002317 return false;
2318 }
2319 return true;
2320 }
2321}
2322
Enrico Granata1328b142012-02-29 03:28:49 +00002323lldb::ScriptInterpreterObjectSP
2324ScriptInterpreterPython::MakeScriptObject (void* object)
2325{
2326 return lldb::ScriptInterpreterObjectSP(new ScriptInterpreterPythonObject(object));
2327}
2328
Enrico Granata6010ace2011-11-07 22:57:04 +00002329ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
2330 ScriptedCommandSynchronicity synchro) :
2331 m_debugger_sp(debugger_sp),
2332 m_synch_wanted(synchro),
2333 m_old_asynch(debugger_sp->GetAsyncExecution())
2334{
2335 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2336 m_debugger_sp->SetAsyncExecution(false);
2337 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2338 m_debugger_sp->SetAsyncExecution(true);
2339}
2340
2341ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
2342{
2343 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2344 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2345}
2346
Enrico Granata59df36f2011-10-17 21:45:27 +00002347bool
Enrico Granatac2a28252011-08-16 16:49:25 +00002348ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
2349 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00002350 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00002351 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00002352 Error& error)
2353{
2354 if (!impl_function)
2355 {
2356 error.SetErrorString("no function to execute");
2357 return false;
2358 }
2359
2360 if (!g_swig_call_command)
2361 {
2362 error.SetErrorString("no helper function to run scripted commands");
2363 return false;
2364 }
2365
Greg Clayton13d24fb2012-01-29 20:56:30 +00002366 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata6010ace2011-11-07 22:57:04 +00002367
2368 if (!debugger_sp.get())
2369 {
2370 error.SetErrorString("invalid Debugger pointer");
2371 return false;
2372 }
Enrico Granatac2a28252011-08-16 16:49:25 +00002373
2374 bool ret_val;
2375
2376 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00002377
Enrico Granatac2a28252011-08-16 16:49:25 +00002378 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002379 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00002380 SynchronicityHandler synch_handler(debugger_sp,
2381 synchronicity);
2382
Enrico Granataa1ba3142012-06-07 00:17:18 +00002383 PythonInputReaderManager py_input(this);
2384
Enrico Granatac2a28252011-08-16 16:49:25 +00002385 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00002386 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00002387 debugger_sp,
2388 args,
2389 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00002390 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00002391 }
Enrico Granata6010ace2011-11-07 22:57:04 +00002392
Enrico Granatac2a28252011-08-16 16:49:25 +00002393 if (!ret_val)
2394 error.SetErrorString(err_msg.c_str());
2395 else
2396 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00002397
Enrico Granatac2a28252011-08-16 16:49:25 +00002398 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00002399}
2400
Enrico Granatae5e34cb2011-08-17 01:30:04 +00002401// in Python, a special attribute __doc__ contains the docstring
2402// for an object (function, method, class, ...) if any is defined
2403// Otherwise, the attribute's value is None
2404std::string
2405ScriptInterpreterPython::GetDocumentationForItem(const char* item)
2406{
2407 std::string command(item);
2408 command += ".__doc__";
2409
2410 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
2411
2412 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00002413 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granataa1ba3142012-06-07 00:17:18 +00002414 &result_ptr, false) && result_ptr)
Enrico Granatae5e34cb2011-08-17 01:30:04 +00002415 {
2416 return std::string(result_ptr);
2417 }
2418 else
2419 return std::string("");
2420}
Caroline Tice2ade6112010-11-10 19:18:14 +00002421
Caroline Tice0aa2e552011-01-14 00:29:16 +00002422void
Enrico Granata1328b142012-02-29 03:28:49 +00002423ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback)
Greg Claytone86cbb92011-03-22 01:14:58 +00002424{
2425 g_swig_init_callback = python_swig_init_callback;
Enrico Granata1328b142012-02-29 03:28:49 +00002426 g_swig_breakpoint_callback = LLDBSwigPythonBreakpointCallbackFunction;
Johnny Chenf3ec4612012-08-09 23:09:42 +00002427 g_swig_watchpoint_callback = LLDBSwigPythonWatchpointCallbackFunction;
Enrico Granata1328b142012-02-29 03:28:49 +00002428 g_swig_typescript_callback = LLDBSwigPythonCallTypeScript;
2429 g_swig_synthetic_script = LLDBSwigPythonCreateSyntheticProvider;
2430 g_swig_calc_children = LLDBSwigPython_CalculateNumChildren;
2431 g_swig_get_child_index = LLDBSwigPython_GetChildAtIndex;
2432 g_swig_get_index_child = LLDBSwigPython_GetIndexOfChildWithName;
2433 g_swig_cast_to_sbvalue = LLDBSWIGPython_CastPyObjectToSBValue;
2434 g_swig_update_provider = LLDBSwigPython_UpdateSynthProviderInstance;
2435 g_swig_call_command = LLDBSwigPythonCallCommand;
2436 g_swig_call_module_init = LLDBSwigPythonCallModuleInit;
Greg Claytone86cbb92011-03-22 01:14:58 +00002437}
2438
2439void
2440ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00002441{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002442 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
2443
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002444 // Python will muck with STDIN terminal state, so save off any current TTY
2445 // settings so we can restore them.
2446 TerminalState stdin_tty_state;
2447 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002448
Caroline Tice9d352ce2011-03-07 23:24:28 +00002449 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00002450 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002451
Greg Claytone86cbb92011-03-22 01:14:58 +00002452 // Initialize SWIG after setting up python
2453 assert (g_swig_init_callback != NULL);
2454 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002455
2456 // Update the path python uses to search for modules to include the current directory.
2457
Caroline Ticed4d92832011-06-13 21:33:00 +00002458 PyRun_SimpleString ("import sys");
2459 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00002460
2461 // Find the module that owns this code and use that path we get to
2462 // set the sys.path appropriately.
2463
2464 FileSpec file_spec;
2465 char python_dir_path[PATH_MAX];
2466 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
2467 {
2468 std::string python_path("sys.path.insert(0,\"");
2469 size_t orig_len = python_path.length();
2470 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2471 {
2472 python_path.append (python_dir_path);
2473 python_path.append ("\")");
2474 PyRun_SimpleString (python_path.c_str());
2475 python_path.resize (orig_len);
2476 }
2477
2478 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
2479 {
2480 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2481 {
2482 python_path.append (python_dir_path);
2483 python_path.append ("\")");
2484 PyRun_SimpleString (python_path.c_str());
2485 python_path.resize (orig_len);
2486 }
2487 }
2488 }
2489
Greg Clayton4e651b12012-04-25 00:58:03 +00002490 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 +00002491
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002492 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002493}
2494
Greg Claytone86cbb92011-03-22 01:14:58 +00002495//void
2496//ScriptInterpreterPython::Terminate ()
2497//{
2498// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
2499// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
2500// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
2501// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
2502// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
2503// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
2504// // within Py_Finalize, which results in a seg fault.
2505// //
2506// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
2507// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
2508// // process exits).
2509// //
2510//// Py_Finalize ();
2511//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00002512
2513#endif // #ifdef LLDB_DISABLE_PYTHON