blob: e1aa378f138e3f8d9c6f96b0e742d5a8f7ee5ed0 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ScriptInterpreterPython.cpp -----------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// In order to guarantee correct working with Python, Python.h *MUST* be
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +000011// the *FIRST* header file included here.
Greg Clayton3e4238d2011-11-04 03:34:56 +000012#ifdef LLDB_DISABLE_PYTHON
13
14// Python is disabled in this build
15
16#else
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +000017
18#if defined (__APPLE__)
19#include <Python/Python.h>
20#else
21#include <Python.h>
22#endif
Chris Lattner24943d22010-06-08 16:52:24 +000023
24#include "lldb/Interpreter/ScriptInterpreterPython.h"
25
Chris Lattner24943d22010-06-08 16:52:24 +000026#include <stdlib.h>
27#include <stdio.h>
28
29#include <string>
30
Enrico Granata91544802011-09-06 19:20:51 +000031#include "lldb/API/SBValue.h"
Greg Clayton987c7eb2011-09-17 08:33:22 +000032#include "lldb/Breakpoint/BreakpointLocation.h"
Greg Clayton63094e02010-06-23 01:19:29 +000033#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner24943d22010-06-08 16:52:24 +000034#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000035#include "lldb/Core/Timer.h"
36#include "lldb/Host/Host.h"
37#include "lldb/Interpreter/CommandInterpreter.h"
38#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton5144f382010-10-07 17:14:24 +000039#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040
Chris Lattner24943d22010-06-08 16:52:24 +000041using namespace lldb;
42using namespace lldb_private;
43
Greg Claytone86cbb92011-03-22 01:14:58 +000044
45static ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL;
46static ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL;
Enrico Granataf7a9b142011-07-15 02:26:42 +000047static ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL;
Enrico Granata9ae7cef2011-07-24 00:14:56 +000048static ScriptInterpreter::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = NULL;
49static ScriptInterpreter::SWIGPythonCalculateNumChildren g_swig_calc_children = NULL;
50static ScriptInterpreter::SWIGPythonGetChildAtIndex g_swig_get_child_index = NULL;
51static ScriptInterpreter::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = NULL;
52static ScriptInterpreter::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = NULL;
Enrico Granata979e20d2011-07-29 19:53:35 +000053static ScriptInterpreter::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = NULL;
Enrico Granatac2a28252011-08-16 16:49:25 +000054static ScriptInterpreter::SWIGPythonCallCommand g_swig_call_command = NULL;
Enrico Granata59df36f2011-10-17 21:45:27 +000055static ScriptInterpreter::SWIGPythonCallModuleInit g_swig_call_module_init = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +000056
Enrico Granata1328b142012-02-29 03:28:49 +000057// these are the Pythonic implementations of the required callbacks
58// these are scripting-language specific, which is why they belong here
59// we still need to use function pointers to them instead of relying
60// on linkage-time resolution because the SWIG stuff and this file
61// get built at different times
62extern "C" bool
63LLDBSwigPythonBreakpointCallbackFunction
64(
65 const char *python_function_name,
66 const char *session_dictionary_name,
67 const lldb::StackFrameSP& sb_frame,
68 const lldb::BreakpointLocationSP& sb_bp_loc
69 );
70
71extern "C" bool
72LLDBSwigPythonCallTypeScript
73(
74 const char *python_function_name,
75 void *session_dictionary,
76 const lldb::ValueObjectSP& valobj_sp,
77 void** pyfunct_wrapper,
78 std::string& retval
79 );
80
81extern "C" void*
82LLDBSwigPythonCreateSyntheticProvider
83(
84 const std::string python_class_name,
85 const char *session_dictionary_name,
86 const lldb::ValueObjectSP& valobj_sp
87 );
88
89
90extern "C" uint32_t LLDBSwigPython_CalculateNumChildren (void *implementor);
91extern "C" void* LLDBSwigPython_GetChildAtIndex (void *implementor, uint32_t idx);
92extern "C" int LLDBSwigPython_GetIndexOfChildWithName (void *implementor, const char* child_name);
93extern "C" void* LLDBSWIGPython_CastPyObjectToSBValue (void* data);
Enrico Granatacf09f882012-03-19 22:58:49 +000094extern "C" bool LLDBSwigPython_UpdateSynthProviderInstance (void* implementor);
Enrico Granata1328b142012-02-29 03:28:49 +000095
96extern "C" bool LLDBSwigPythonCallCommand
97(
98 const char *python_function_name,
99 const char *session_dictionary_name,
100 lldb::DebuggerSP& debugger,
101 const char* args,
102 std::string& err_msg,
103 lldb_private::CommandReturnObject& cmd_retobj
104 );
105
106extern "C" bool LLDBSwigPythonCallModuleInit
107(
108 const std::string python_module_name,
109 const char *session_dictionary_name,
110 lldb::DebuggerSP& debugger
111 );
112
Chris Lattner24943d22010-06-08 16:52:24 +0000113static int
114_check_and_flush (FILE *stream)
115{
116 int prev_fail = ferror (stream);
117 return fflush (stream) || prev_fail ? EOF : 0;
118}
119
Caroline Tice202f6b82011-01-17 21:55:19 +0000120static Predicate<lldb::tid_t> &
121PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +0000122{
Caroline Tice202f6b82011-01-17 21:55:19 +0000123 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
124 return g_interpreter_is_running;
125}
126
Enrico Granatafa1f6172011-10-24 17:22:21 +0000127bool
128ScriptInterpreterPython::Locker::CurrentThreadHasPythonLock ()
Caroline Tice202f6b82011-01-17 21:55:19 +0000129{
130 TimeValue timeout;
131
132 timeout = TimeValue::Now(); // Don't wait any time.
133
134 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
135}
136
Enrico Granatafa1f6172011-10-24 17:22:21 +0000137bool
138ScriptInterpreterPython::Locker::TryGetPythonLock (uint32_t seconds_to_wait)
Caroline Tice202f6b82011-01-17 21:55:19 +0000139{
140
141 TimeValue timeout;
142
143 if (seconds_to_wait != UINT32_MAX)
144 {
145 timeout = TimeValue::Now();
146 timeout.OffsetWithSeconds (seconds_to_wait);
147 }
148
149 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
150 Host::GetCurrentThreadID(), &timeout, NULL);
151}
152
Enrico Granatafa1f6172011-10-24 17:22:21 +0000153void
154ScriptInterpreterPython::Locker::ReleasePythonLock ()
Caroline Tice202f6b82011-01-17 21:55:19 +0000155{
156 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000157}
158
Enrico Granatafa1f6172011-10-24 17:22:21 +0000159ScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *py_interpreter,
160 uint16_t on_entry,
161 uint16_t on_leave,
162 FILE* wait_msg_handle) :
163 m_need_session( (on_leave & TearDownSession) == TearDownSession ),
164 m_release_lock ( false ), // decide in constructor body
165 m_python_interpreter(py_interpreter),
166 m_tmp_fh(wait_msg_handle)
Enrico Granata91544802011-09-06 19:20:51 +0000167{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000168 if (m_python_interpreter && !m_tmp_fh)
169 m_tmp_fh = (m_python_interpreter->m_dbg_stdout ? m_python_interpreter->m_dbg_stdout : stdout);
170
171 if ( (on_entry & AcquireLock) == AcquireLock )
172 {
173 if (CurrentThreadHasPythonLock())
174 {
175 if ( (on_leave & FreeLock) == FreeLock )
176 m_release_lock = true;
177 }
178 else
179 {
180 DoAcquireLock();
181 if ( (on_leave & FreeLock) == FreeLock )
182 m_release_lock = true;
183 if ( (on_leave & FreeAcquiredLock) == FreeAcquiredLock )
184 m_release_lock = true;
185 }
186 }
187 if ( (on_entry & InitSession) == InitSession )
188 DoInitSession();
189}
190
191bool
192ScriptInterpreterPython::Locker::DoAcquireLock()
193{
Enrico Granata91544802011-09-06 19:20:51 +0000194 if (!CurrentThreadHasPythonLock())
195 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000196 while (!TryGetPythonLock (1))
197 if (m_tmp_fh)
198 fprintf (m_tmp_fh,
Enrico Granata91544802011-09-06 19:20:51 +0000199 "Python interpreter locked on another thread; waiting to acquire lock...\n");
Enrico Granata91544802011-09-06 19:20:51 +0000200 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000201 return true;
202}
203
204bool
205ScriptInterpreterPython::Locker::DoInitSession()
206{
207 if (!m_python_interpreter)
208 return false;
209 m_python_interpreter->EnterSession ();
210 return true;
211}
212
213bool
214ScriptInterpreterPython::Locker::DoFreeLock()
215{
216 ReleasePythonLock ();
217 return true;
218}
219
220bool
221ScriptInterpreterPython::Locker::DoTearDownSession()
222{
223 if (!m_python_interpreter)
224 return false;
225 m_python_interpreter->LeaveSession ();
226 return true;
Enrico Granata91544802011-09-06 19:20:51 +0000227}
228
229ScriptInterpreterPython::Locker::~Locker()
230{
231 if (m_need_session)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000232 DoTearDownSession();
Enrico Granata91544802011-09-06 19:20:51 +0000233 if (m_release_lock)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000234 DoFreeLock();
Enrico Granata91544802011-09-06 19:20:51 +0000235}
236
Enrico Granatadba1de82012-03-27 02:35:13 +0000237class ForceDisableSyntheticChildren
238{
239public:
240 ForceDisableSyntheticChildren (Target* target) :
241 m_target(target)
242 {
243 m_old_value = target->GetSuppressSyntheticValue();
244 target->SetSuppressSyntheticValue(true);
245 }
246 ~ForceDisableSyntheticChildren ()
247 {
248 m_target->SetSuppressSyntheticValue(m_old_value);
249 }
250private:
251 Target* m_target;
252 bool m_old_value;
253};
254
Enrico Granataa1ba3142012-06-07 00:17:18 +0000255ScriptInterpreterPython::PythonInputReaderManager::PythonInputReaderManager (ScriptInterpreterPython *interpreter) :
256m_interpreter(interpreter),
257m_debugger_sp(),
258m_reader_sp(),
259m_error(false)
260{
261 if (m_interpreter == NULL)
262 {
263 m_error = true;
264 return;
265 }
266
267 m_debugger_sp = m_interpreter->GetCommandInterpreter().GetDebugger().shared_from_this();
268
269 if (!m_debugger_sp)
270 {
271 m_error = true;
272 return;
273 }
274
275 m_reader_sp = InputReaderSP(new InputReader(*m_debugger_sp.get()));
276
277 if (!m_reader_sp)
278 {
279 m_error = true;
280 return;
281 }
282
283 Error error (m_reader_sp->Initialize (ScriptInterpreterPython::PythonInputReaderManager::InputReaderCallback,
284 m_interpreter, // baton
285 eInputReaderGranularityLine, // token size, to pass to callback function
286 NULL, // end token
287 NULL, // prompt
288 true)); // echo input
289 if (error.Fail())
290 m_error = true;
291 else
292 {
293 m_debugger_sp->PushInputReader (m_reader_sp);
294 m_interpreter->m_embedded_thread_input_reader_sp = m_reader_sp;
295 }
296}
297
298ScriptInterpreterPython::PythonInputReaderManager::~PythonInputReaderManager()
299{
300 if (m_interpreter)
301 {
302 if (m_interpreter->m_embedded_thread_input_reader_sp)
303 m_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
304 m_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
305 }
306
307
308 if (m_reader_sp)
309 {
310 m_reader_sp->SetIsDone (true);
311 if (m_debugger_sp)
312 m_debugger_sp->PopInputReader(m_reader_sp);
313 }
314
315 if (m_interpreter)
316 m_interpreter->m_embedded_thread_input_reader_sp.reset();
317}
318
319size_t
320ScriptInterpreterPython::PythonInputReaderManager::InputReaderCallback
321(
322 void *baton,
323 InputReader &reader,
324 InputReaderAction notification,
325 const char *bytes,
326 size_t bytes_len
327 )
328{
329 lldb::thread_t embedded_interpreter_thread;
330 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
331
332 if (baton == NULL)
333 return 0;
334
335 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
336
337 if (script_interpreter->m_script_lang != eScriptLanguagePython)
338 return 0;
339
340 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
341
342 switch (notification)
343 {
344 case eInputReaderActivate:
345 {
346 // Save terminal settings if we can
347 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
348 if (input_fd == File::kInvalidDescriptor)
349 input_fd = STDIN_FILENO;
350
351 script_interpreter->SaveTerminalState(input_fd);
352
353 {
354 ScriptInterpreterPython::Locker locker(script_interpreter,
355 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
356 ScriptInterpreterPython::Locker::FreeAcquiredLock);
357 }
358
359 char error_str[1024];
360 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
361 sizeof(error_str)))
362 {
363 if (log)
364 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
365 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
366 {
367 StreamString run_string;
368 char error_str[1024];
369 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
370 if (pty_slave_name != NULL)
371 {
372 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
373 PyRun_SimpleString (run_string.GetData());
374 run_string.Clear ();
375
376 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
377 PyRun_SimpleString (run_string.GetData());
378 run_string.Clear ();
379
380 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
381 PyRun_SimpleString (run_string.GetData());
382 run_string.Clear ();
383
384 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
385 pty_slave_name);
386 PyRun_SimpleString (run_string.GetData());
387 run_string.Clear ();
388 }
389 }
390 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.noninteractive-python>",
391 ScriptInterpreterPython::PythonInputReaderManager::RunPythonInputReader,
392 script_interpreter, NULL);
393 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
394 {
395 if (log)
396 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
397 Error detach_error;
398 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
399 }
400 else
401 {
402 if (log)
403 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, failed in creating thread");
404 reader.SetIsDone (true);
405 }
406 }
407 else
408 {
409 if (log)
410 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, failed to open master pty ");
411 reader.SetIsDone (true);
412 }
413 }
414 break;
415
416 case eInputReaderDeactivate:
417 // When another input reader is pushed, don't leave the session...
418 //script_interpreter->LeaveSession ();
419 break;
420
421 case eInputReaderReactivate:
422 {
423 // Don't try and acquire the interpreter lock here because code like
424 // this:
425 //
426 // (lldb) script
427 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
428 //
429 // This will cause the process to run. The interpreter lock is taken
430 // by the input reader for the "script" command. If we try and acquire
431 // the lock here, when the process runs it might deactivate this input
432 // reader (if STDIN is hooked up to the inferior process) and
433 // reactivate it when the process stops which will deadlock.
434 //ScriptInterpreterPython::Locker locker(script_interpreter,
435 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
436 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
437 }
438 break;
439
440 case eInputReaderAsynchronousOutputWritten:
441 break;
442
443 case eInputReaderInterrupt:
444 reader.SetIsDone(true);
445 break;
446
447 case eInputReaderEndOfFile:
448 reader.SetIsDone(true);
449 break;
450
451 case eInputReaderGotToken:
452 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
453 {
454 if (log)
455 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
456 bytes_len);
457 if (bytes && bytes_len)
458 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
459 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
460 }
461 else
462 {
463 if (log)
464 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
465 bytes,
466 bytes_len);
467 reader.SetIsDone (true);
468 }
469
470 break;
471
472 case eInputReaderDone:
473 {
474 StreamString run_string;
475 char error_str[1024];
476 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
477 if (pty_slave_name != NULL)
478 {
479 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
480 PyRun_SimpleString (run_string.GetData());
481 run_string.Clear();
482
483 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
484 PyRun_SimpleString (run_string.GetData());
485 run_string.Clear();
486 }
487 }
488
489 // Restore terminal settings if they were validly saved
490 if (log)
491 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Done, closing down input reader.");
492
493 script_interpreter->RestoreTerminalState ();
494
495 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
496 break;
497 }
498
499 return bytes_len;
500}
501
Greg Clayton63094e02010-06-23 01:19:29 +0000502ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000503 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000504 m_embedded_python_pty (),
505 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +0000506 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000507 m_new_sysout (NULL),
Johnny Chenc65046d2012-03-08 20:53:04 +0000508 m_old_sysout (NULL),
509 m_old_syserr (NULL),
Enrico Granata400105d2012-03-06 23:42:15 +0000510 m_run_one_line (NULL),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000511 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000512 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000513 m_session_is_active (false),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000514 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000515{
516
Greg Clayton7c330d62011-01-27 01:01:10 +0000517 static int g_initialized = false;
518
519 if (!g_initialized)
520 {
521 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000522 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000523 }
Enrico Granatafa1f6172011-10-24 17:22:21 +0000524
525 Locker locker(this,
526 ScriptInterpreterPython::Locker::AcquireLock,
527 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Greg Clayton7c330d62011-01-27 01:01:10 +0000528
Caroline Tice0aa2e552011-01-14 00:29:16 +0000529 m_dictionary_name.append("_dict");
530 StreamString run_string;
531 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
532 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000533
Caroline Tice0aa2e552011-01-14 00:29:16 +0000534 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000535
536 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
537 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
538 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
539 // call to Debugger::Terminate is made, the ref-count has the correct value.
540 //
541 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
542 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000543
Caroline Tice0aa2e552011-01-14 00:29:16 +0000544 int old_count = Debugger::TestDebuggerRefCount();
Greg Claytonb302dff2012-02-01 08:09:32 +0000545
Greg Clayton4e651b12012-04-25 00:58:03 +0000546 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 +0000547 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000548
Enrico Granata8f84cfb2012-02-23 23:10:03 +0000549 // WARNING: temporary code that loads Cocoa formatters - this should be done on a per-platform basis rather than loading the whole set
550 // and letting the individual formatter classes exploit APIs to check whether they can/cannot do their task
551 run_string.Clear();
Greg Clayton4e651b12012-04-25 00:58:03 +0000552 //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 +0000553 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 +0000554 PyRun_SimpleString (run_string.GetData());
Greg Claytonb302dff2012-02-01 08:09:32 +0000555
Caroline Tice0aa2e552011-01-14 00:29:16 +0000556 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000557
Caroline Tice0aa2e552011-01-14 00:29:16 +0000558 if (new_count > old_count)
559 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000560
Caroline Tice0aa2e552011-01-14 00:29:16 +0000561 run_string.Clear();
Greg Clayton444e35b2011-10-19 18:09:39 +0000562 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000563 interpreter.GetDebugger().GetID());
564 PyRun_SimpleString (run_string.GetData());
565
566 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000567 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000568 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000569 }
Chris Lattner24943d22010-06-08 16:52:24 +0000570}
571
572ScriptInterpreterPython::~ScriptInterpreterPython ()
573{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000574 Debugger &debugger = GetCommandInterpreter().GetDebugger();
575
576 if (m_embedded_thread_input_reader_sp.get() != NULL)
577 {
578 m_embedded_thread_input_reader_sp->SetIsDone (true);
579 m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000580 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
581 m_embedded_thread_input_reader_sp.reset();
582 debugger.PopInputReader (reader_sp);
583 }
584
585 if (m_new_sysout)
586 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000587 Locker locker(this,
588 ScriptInterpreterPython::Locker::AcquireLock,
589 ScriptInterpreterPython::Locker::FreeLock);
590 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000591 }
Chris Lattner24943d22010-06-08 16:52:24 +0000592}
593
Caroline Tice0aa2e552011-01-14 00:29:16 +0000594void
595ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
596{
597 if (fh == NULL)
598 return;
599
600 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000601
Johnny Chenc65046d2012-03-08 20:53:04 +0000602 Locker locker(this,
603 ScriptInterpreterPython::Locker::AcquireLock,
604 ScriptInterpreterPython::Locker::FreeAcquiredLock);
605
Enrico Granata91544802011-09-06 19:20:51 +0000606 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000607}
608
609void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000610ScriptInterpreterPython::SaveTerminalState (int fd)
611{
612 // Python mucks with the terminal state of STDIN. If we can possibly avoid
613 // this by setting the file handles up correctly prior to entering the
614 // interpreter we should. For now we save and restore the terminal state
615 // on the input file handle.
616 m_terminal_state.Save (fd, false);
617}
618
619void
620ScriptInterpreterPython::RestoreTerminalState ()
621{
622 // Python mucks with the terminal state of STDIN. If we can possibly avoid
623 // this by setting the file handles up correctly prior to entering the
624 // interpreter we should. For now we save and restore the terminal state
625 // on the input file handle.
626 m_terminal_state.Restore();
627}
628
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000629void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000630ScriptInterpreterPython::LeaveSession ()
631{
Enrico Granata7aa754c2012-04-04 17:31:29 +0000632 // checking that we have a valid thread state - since we use our own threading and locking
633 // in some (rare) cases during cleanup Python may end up believing we have no thread state
634 // and PyImport_AddModule will crash if that is the case - since that seems to only happen
635 // when destroying the SBDebugger, we can make do without clearing up stdout and stderr
Johnny Chen2b536952012-05-04 20:37:11 +0000636
637 // rdar://problem/11292882
638 // When the current thread state is NULL, PyThreadState_Get() issues a fatal error.
639 if (PyThreadState_GetDict())
Johnny Chen41641f92012-02-29 01:52:13 +0000640 {
Enrico Granata7aa754c2012-04-04 17:31:29 +0000641 PyObject *sysmod = PyImport_AddModule ("sys");
642 PyObject *sysdict = PyModule_GetDict (sysmod);
643
644 if (m_new_sysout && sysmod && sysdict)
645 {
646 if (m_old_sysout)
647 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_old_sysout);
648 if (m_old_syserr)
649 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_old_syserr);
650 }
Johnny Chen41641f92012-02-29 01:52:13 +0000651 }
652
Caroline Tice0aa2e552011-01-14 00:29:16 +0000653 m_session_is_active = false;
654}
655
656void
657ScriptInterpreterPython::EnterSession ()
658{
659 // If we have already entered the session, without having officially 'left' it, then there is no need to
660 // 'enter' it again.
661
662 if (m_session_is_active)
663 return;
664
665 m_session_is_active = true;
666
Caroline Tice202f6b82011-01-17 21:55:19 +0000667 StreamString run_string;
668
Greg Clayton2fecc452012-01-28 02:11:02 +0000669 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %llu", m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
670 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)", GetCommandInterpreter().GetDebugger().GetID());
671 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
672 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
673 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
674 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
675 // Make sure STDIN is closed since when we run this as an embedded
676 // interpreter we don't want someone to call "line = sys.stdin.readline()"
677 // and lock up. We don't have multiple windows and when the interpreter is
678 // embedded we don't know we should be feeding input to the embedded
679 // interpreter or to the python sys.stdin. We also don't want to let python
680 // play with the real stdin from this process, so we need to close it...
Greg Clayton3eeaf6e2012-02-03 01:30:30 +0000681 //run_string.PutCString ("; sys.stdin.close()");
Greg Clayton2fecc452012-01-28 02:11:02 +0000682 run_string.PutCString ("')");
Caroline Tice0aa2e552011-01-14 00:29:16 +0000683
Caroline Tice6af65cb2011-05-03 21:21:50 +0000684 PyRun_SimpleString (run_string.GetData());
685 run_string.Clear();
Johnny Chen41641f92012-02-29 01:52:13 +0000686
Caroline Tice0aa2e552011-01-14 00:29:16 +0000687 PyObject *sysmod = PyImport_AddModule ("sys");
688 PyObject *sysdict = PyModule_GetDict (sysmod);
Johnny Chen41641f92012-02-29 01:52:13 +0000689
Greg Clayton2fecc452012-01-28 02:11:02 +0000690 if (m_new_sysout && sysmod && sysdict)
691 {
Johnny Chen41641f92012-02-29 01:52:13 +0000692 m_old_sysout = PyDict_GetItemString(sysdict, "stdout");
693 m_old_syserr = PyDict_GetItemString(sysdict, "stderr");
Johnny Chenc65046d2012-03-08 20:53:04 +0000694 if (m_new_sysout)
695 {
696 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
697 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
698 }
Greg Clayton2fecc452012-01-28 02:11:02 +0000699 }
Johnny Chen41641f92012-02-29 01:52:13 +0000700
Caroline Tice0aa2e552011-01-14 00:29:16 +0000701 if (PyErr_Occurred())
702 PyErr_Clear ();
Greg Clayton2fecc452012-01-28 02:11:02 +0000703}
Caroline Tice0aa2e552011-01-14 00:29:16 +0000704
Enrico Granata400105d2012-03-06 23:42:15 +0000705static PyObject*
706FindSessionDictionary (const char* dict_name)
707{
708 static std::map<ConstString,PyObject*> g_dict_map;
709
710 ConstString dict(dict_name);
711
712 std::map<ConstString,PyObject*>::iterator iter = g_dict_map.find(dict);
713
714 if (iter != g_dict_map.end())
715 return iter->second;
716
717 PyObject *main_mod = PyImport_AddModule ("__main__");
718 if (main_mod != NULL)
719 {
720 PyObject *main_dict = PyModule_GetDict (main_mod);
721 if ((main_dict != NULL)
722 && PyDict_Check (main_dict))
723 {
724 // Go through the main dictionary looking for the correct python script interpreter dictionary
725 PyObject *key, *value;
726 Py_ssize_t pos = 0;
727
728 while (PyDict_Next (main_dict, &pos, &key, &value))
729 {
730 // We have stolen references to the key and value objects in the dictionary; we need to increment
731 // them now so that Python's garbage collector doesn't collect them out from under us.
732 Py_INCREF (key);
733 Py_INCREF (value);
734 if (strcmp (PyString_AsString (key), dict_name) == 0)
735 {
736 g_dict_map[dict] = value;
737 return value;
738 }
739 }
740 }
741 }
742 return NULL;
743}
744
745static std::string
746GenerateUniqueName (const char* base_name_wanted,
747 uint32_t& functions_counter,
748 void* name_token = NULL)
749{
750 StreamString sstr;
751
752 if (!base_name_wanted)
753 return std::string();
754
755 if (!name_token)
756 sstr.Printf ("%s_%d", base_name_wanted, functions_counter++);
757 else
758 sstr.Printf ("%s_%p", base_name_wanted, name_token);
759
760 return sstr.GetString();
761}
762
Johnny Chen60dde642010-07-30 22:33:14 +0000763bool
Enrico Granataa1ba3142012-06-07 00:17:18 +0000764ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result, bool enable_io)
Chris Lattner24943d22010-06-08 16:52:24 +0000765{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000766 if (!m_valid_session)
767 return false;
768
Caroline Tice4a461da2011-01-14 21:09:29 +0000769 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
770 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
771 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
772 // method to pass the command string directly down to Python.
773
Enrico Granatafa1f6172011-10-24 17:22:21 +0000774 Locker locker(this,
775 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
776 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000777
778 bool success = false;
779
Greg Clayton63094e02010-06-23 01:19:29 +0000780 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000781 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000782 // Find the correct script interpreter dictionary in the main module.
Enrico Granata400105d2012-03-06 23:42:15 +0000783 PyObject *script_interpreter_dict = FindSessionDictionary(m_dictionary_name.c_str());
784 if (script_interpreter_dict != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000785 {
Enrico Granata400105d2012-03-06 23:42:15 +0000786 PyObject *pfunc = (PyObject*)m_run_one_line;
Greg Clayton6f2f0ab2012-04-25 01:49:50 +0000787 PyObject *pmod = PyImport_AddModule ("lldb.embedded_interpreter");
Enrico Granata400105d2012-03-06 23:42:15 +0000788 if (pmod != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000789 {
Enrico Granata400105d2012-03-06 23:42:15 +0000790 PyObject *pmod_dict = PyModule_GetDict (pmod);
791 if ((pmod_dict != NULL)
792 && PyDict_Check (pmod_dict))
Caroline Tice4a461da2011-01-14 21:09:29 +0000793 {
Enrico Granata400105d2012-03-06 23:42:15 +0000794 if (!pfunc)
Caroline Tice4a461da2011-01-14 21:09:29 +0000795 {
796 PyObject *key, *value;
797 Py_ssize_t pos = 0;
798
799 while (PyDict_Next (pmod_dict, &pos, &key, &value))
800 {
801 Py_INCREF (key);
802 Py_INCREF (value);
803 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
804 {
805 pfunc = value;
806 break;
807 }
808 }
Enrico Granata400105d2012-03-06 23:42:15 +0000809 m_run_one_line = pfunc;
810 }
811
812 if (pfunc && PyCallable_Check (pfunc))
813 {
814 PyObject *pargs = Py_BuildValue("(Os)",script_interpreter_dict,command);
815 if (pargs != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000816 {
Enrico Granataa1ba3142012-06-07 00:17:18 +0000817 PyObject *pvalue = NULL;
818 { // scope for PythonInputReaderManager
819 PythonInputReaderManager py_input(enable_io ? this : NULL);
820 pvalue = PyObject_CallObject (pfunc, pargs);
821 }
Enrico Granata400105d2012-03-06 23:42:15 +0000822 Py_DECREF (pargs);
823 if (pvalue != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000824 {
Enrico Granata400105d2012-03-06 23:42:15 +0000825 Py_DECREF (pvalue);
826 success = true;
827 }
828 else if (PyErr_Occurred ())
829 {
830 PyErr_Print();
831 PyErr_Clear();
Caroline Tice4a461da2011-01-14 21:09:29 +0000832 }
833 }
834 }
835 }
Caroline Tice4a461da2011-01-14 21:09:29 +0000836 }
Enrico Granata400105d2012-03-06 23:42:15 +0000837 Py_INCREF (script_interpreter_dict);
Caroline Tice4a461da2011-01-14 21:09:29 +0000838 }
Greg Clayton63094e02010-06-23 01:19:29 +0000839
Caroline Tice4a461da2011-01-14 21:09:29 +0000840 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000841 return true;
842
843 // The one-liner failed. Append the error message.
844 if (result)
845 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
846 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000847 }
Johnny Chen60dde642010-07-30 22:33:14 +0000848
849 if (result)
850 result->AppendError ("empty command passed to python\n");
851 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000852}
853
Chris Lattner24943d22010-06-08 16:52:24 +0000854size_t
855ScriptInterpreterPython::InputReaderCallback
856(
857 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000858 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000859 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000860 const char *bytes,
861 size_t bytes_len
862)
863{
Caroline Tice2ade6112010-11-10 19:18:14 +0000864 lldb::thread_t embedded_interpreter_thread;
865 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
866
Chris Lattner24943d22010-06-08 16:52:24 +0000867 if (baton == NULL)
868 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000869
870 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000871
Caroline Tice0aa2e552011-01-14 00:29:16 +0000872 if (script_interpreter->m_script_lang != eScriptLanguagePython)
873 return 0;
874
Caroline Tice892fadd2011-06-16 16:27:19 +0000875 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
876 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
877
Chris Lattner24943d22010-06-08 16:52:24 +0000878 switch (notification)
879 {
880 case eInputReaderActivate:
881 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000882 if (!batch_mode)
883 {
884 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
885 out_stream->Flush();
886 }
Greg Clayton58928562011-02-09 01:08:52 +0000887
Chris Lattner24943d22010-06-08 16:52:24 +0000888 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000889 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
890 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000891 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000892
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000893 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000894
Caroline Tice202f6b82011-01-17 21:55:19 +0000895 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000896 ScriptInterpreterPython::Locker locker(script_interpreter,
897 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
898 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000899 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000900
Caroline Tice2ade6112010-11-10 19:18:14 +0000901 char error_str[1024];
902 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
903 sizeof(error_str)))
904 {
905 if (log)
906 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
907 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
908 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
909 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
910 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000911 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000912 {
913 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000914 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000915 Error detach_error;
916 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
917 }
918 else
919 {
920 if (log)
921 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
922 reader.SetIsDone (true);
923 }
924 }
925 else
926 {
927 if (log)
928 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
929 reader.SetIsDone (true);
930 }
Chris Lattner24943d22010-06-08 16:52:24 +0000931 }
932 break;
933
934 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000935 // When another input reader is pushed, don't leave the session...
936 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000937 break;
938
939 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000940 {
Greg Claytona1cec242012-01-06 00:47:38 +0000941 // Don't try and acquire the interpreter lock here because code like
942 // this:
943 //
944 // (lldb) script
945 // >>> v = lldb.frame.EvaluateExpression("collection->get_at_index(12)")
946 //
947 // This will cause the process to run. The interpreter lock is taken
948 // by the input reader for the "script" command. If we try and acquire
949 // the lock here, when the process runs it might deactivate this input
950 // reader (if STDIN is hooked up to the inferior process) and
951 // reactivate it when the process stops which will deadlock.
952 //ScriptInterpreterPython::Locker locker(script_interpreter,
953 // ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
954 // ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000955 }
Chris Lattner24943d22010-06-08 16:52:24 +0000956 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000957
Caroline Tice4a348082011-05-02 20:41:46 +0000958 case eInputReaderAsynchronousOutputWritten:
959 break;
960
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000961 case eInputReaderInterrupt:
962 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
963 break;
964
965 case eInputReaderEndOfFile:
966 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
967 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000968
969 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000970 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000971 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000972 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000973 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000974 bytes_len);
975 if (bytes && bytes_len)
976 {
977 if ((int) bytes[0] == 4)
978 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
979 else
980 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
981 }
982 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000983 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000984 else
985 {
986 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000987 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000988 bytes,
989 bytes_len);
990 reader.SetIsDone (true);
991 }
992
Chris Lattner24943d22010-06-08 16:52:24 +0000993 break;
994
995 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000996 script_interpreter->LeaveSession ();
997
Chris Lattner24943d22010-06-08 16:52:24 +0000998 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000999 if (log)
1000 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +00001001
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001002 script_interpreter->RestoreTerminalState ();
1003
Caroline Tice2ade6112010-11-10 19:18:14 +00001004 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +00001005 break;
1006 }
1007
1008 return bytes_len;
1009}
1010
1011
1012void
Greg Clayton238c0a12010-09-18 01:14:36 +00001013ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +00001014{
1015 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1016
Caroline Tice0aa2e552011-01-14 00:29:16 +00001017 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +00001018
1019 // At the moment, the only time the debugger does not have an input file handle is when this is called
1020 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
1021 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
1022 // do it.
1023
Greg Clayton58928562011-02-09 01:08:52 +00001024 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +00001025 return;
1026
Greg Clayton63094e02010-06-23 01:19:29 +00001027 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001028 if (reader_sp)
1029 {
1030 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
1031 this, // baton
1032 eInputReaderGranularityLine, // token size, to pass to callback function
1033 NULL, // end token
1034 NULL, // prompt
1035 true)); // echo input
1036
1037 if (error.Success())
1038 {
Greg Clayton63094e02010-06-23 01:19:29 +00001039 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +00001040 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001041 }
1042 }
1043}
1044
1045bool
1046ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +00001047 ScriptInterpreter::ScriptReturnType return_type,
Enrico Granataa1ba3142012-06-07 00:17:18 +00001048 void *ret_value,
1049 bool enable_io)
Chris Lattner24943d22010-06-08 16:52:24 +00001050{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001051
Enrico Granatafa1f6172011-10-24 17:22:21 +00001052 Locker locker(this,
1053 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1054 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001055
Chris Lattner24943d22010-06-08 16:52:24 +00001056 PyObject *py_return = NULL;
1057 PyObject *mainmod = PyImport_AddModule ("__main__");
1058 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001059 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001060 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +00001061 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001062 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001063 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001064
Enrico Granata400105d2012-03-06 23:42:15 +00001065 locals = FindSessionDictionary(m_dictionary_name.c_str());
1066
Caroline Tice0aa2e552011-01-14 00:29:16 +00001067 if (locals == NULL)
1068 {
1069 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
1070 should_decrement_locals = true;
1071 }
1072
1073 if (locals == NULL)
1074 {
1075 locals = globals;
1076 should_decrement_locals = false;
1077 }
1078
1079 py_error = PyErr_Occurred();
1080 if (py_error != NULL)
1081 PyErr_Clear();
1082
Chris Lattner24943d22010-06-08 16:52:24 +00001083 if (in_string != NULL)
1084 {
Enrico Granataa1ba3142012-06-07 00:17:18 +00001085 { // scope for PythonInputReaderManager
1086 PythonInputReaderManager py_input(enable_io ? this : NULL);
1087 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
1088 if (py_return == NULL)
1089 {
1090 py_error = PyErr_Occurred ();
1091 if (py_error != NULL)
1092 PyErr_Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +00001093
Enrico Granataa1ba3142012-06-07 00:17:18 +00001094 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
1095 }
Chris Lattner24943d22010-06-08 16:52:24 +00001096 }
1097
Caroline Tice0aa2e552011-01-14 00:29:16 +00001098 if (locals != NULL
1099 && should_decrement_locals)
1100 Py_DECREF (locals);
1101
Chris Lattner24943d22010-06-08 16:52:24 +00001102 if (py_return != NULL)
1103 {
1104 switch (return_type)
1105 {
Enrico Granata59df36f2011-10-17 21:45:27 +00001106 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +00001107 {
1108 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001109 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +00001110 break;
1111 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001112 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +00001113 {
1114 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001115 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +00001116 break;
1117 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001118 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +00001119 {
1120 const char format[2] = "b";
1121 success = PyArg_Parse (py_return, format, (bool *) ret_value);
1122 break;
1123 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001124 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +00001125 {
1126 const char format[2] = "h";
1127 success = PyArg_Parse (py_return, format, (short *) ret_value);
1128 break;
1129 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001130 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001131 {
1132 const char format[2] = "H";
1133 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
1134 break;
1135 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001136 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +00001137 {
1138 const char format[2] = "i";
1139 success = PyArg_Parse (py_return, format, (int *) ret_value);
1140 break;
1141 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001142 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001143 {
1144 const char format[2] = "I";
1145 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
1146 break;
1147 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001148 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +00001149 {
1150 const char format[2] = "l";
1151 success = PyArg_Parse (py_return, format, (long *) ret_value);
1152 break;
1153 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001154 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001155 {
1156 const char format[2] = "k";
1157 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
1158 break;
1159 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001160 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +00001161 {
1162 const char format[2] = "L";
1163 success = PyArg_Parse (py_return, format, (long long *) ret_value);
1164 break;
1165 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001166 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001167 {
1168 const char format[2] = "K";
1169 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
1170 break;
1171 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001172 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +00001173 {
1174 const char format[2] = "f";
1175 success = PyArg_Parse (py_return, format, (float *) ret_value);
1176 break;
1177 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001178 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +00001179 {
1180 const char format[2] = "d";
1181 success = PyArg_Parse (py_return, format, (double *) ret_value);
1182 break;
1183 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001184 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +00001185 {
1186 const char format[2] = "c";
1187 success = PyArg_Parse (py_return, format, (char *) ret_value);
1188 break;
1189 }
1190 default:
1191 {}
1192 }
1193 Py_DECREF (py_return);
1194 if (success)
1195 ret_success = true;
1196 else
1197 ret_success = false;
1198 }
1199 }
1200
1201 py_error = PyErr_Occurred();
1202 if (py_error != NULL)
1203 {
1204 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1205 PyErr_Print ();
1206 PyErr_Clear();
1207 ret_success = false;
1208 }
Caroline Tice202f6b82011-01-17 21:55:19 +00001209
Chris Lattner24943d22010-06-08 16:52:24 +00001210 return ret_success;
1211}
1212
1213bool
Enrico Granataa1ba3142012-06-07 00:17:18 +00001214ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string, bool enable_io)
Chris Lattner24943d22010-06-08 16:52:24 +00001215{
Enrico Granatafa1f6172011-10-24 17:22:21 +00001216
1217
1218 Locker locker(this,
1219 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1220 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001221
Chris Lattner24943d22010-06-08 16:52:24 +00001222 bool success = false;
1223 PyObject *py_return = NULL;
1224 PyObject *mainmod = PyImport_AddModule ("__main__");
1225 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001226 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001227 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001228 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001229
Enrico Granata400105d2012-03-06 23:42:15 +00001230 locals = FindSessionDictionary(m_dictionary_name.c_str());
1231
Caroline Tice0aa2e552011-01-14 00:29:16 +00001232 if (locals == NULL)
1233 {
1234 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
1235 should_decrement_locals = true;
1236 }
1237
1238 if (locals == NULL)
1239 {
1240 locals = globals;
1241 should_decrement_locals = false;
1242 }
1243
1244 py_error = PyErr_Occurred();
1245 if (py_error != NULL)
1246 PyErr_Clear();
1247
Chris Lattner24943d22010-06-08 16:52:24 +00001248 if (in_string != NULL)
1249 {
1250 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
1251 if (compiled_node)
1252 {
1253 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
1254 if (compiled_code)
1255 {
Enrico Granataa1ba3142012-06-07 00:17:18 +00001256 { // scope for PythonInputReaderManager
1257 PythonInputReaderManager py_input(enable_io ? this : NULL);
1258 py_return = PyEval_EvalCode (compiled_code, globals, locals);
1259 }
Chris Lattner24943d22010-06-08 16:52:24 +00001260 if (py_return != NULL)
1261 {
1262 success = true;
1263 Py_DECREF (py_return);
1264 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001265 if (locals && should_decrement_locals)
1266 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +00001267 }
1268 }
1269 }
1270
1271 py_error = PyErr_Occurred ();
1272 if (py_error != NULL)
1273 {
1274 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1275 PyErr_Print ();
1276 PyErr_Clear();
1277 success = false;
1278 }
1279
1280 return success;
1281}
1282
1283static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1284
1285size_t
1286ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1287(
1288 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001289 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001290 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001291 const char *bytes,
1292 size_t bytes_len
1293)
1294{
Caroline Tice892fadd2011-06-16 16:27:19 +00001295 static StringList commands_in_progress;
1296
1297 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1298 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1299
Chris Lattner24943d22010-06-08 16:52:24 +00001300 switch (notification)
1301 {
1302 case eInputReaderActivate:
1303 {
1304 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +00001305 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +00001306 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001307 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001308 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +00001309 out_stream->Printf ("%s", reader.GetPrompt());
1310 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001311 }
1312 }
1313 break;
1314
1315 case eInputReaderDeactivate:
1316 break;
1317
1318 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001319 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001320 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001321 out_stream->Printf ("%s", reader.GetPrompt());
1322 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001323 }
Chris Lattner24943d22010-06-08 16:52:24 +00001324 break;
1325
Caroline Tice4a348082011-05-02 20:41:46 +00001326 case eInputReaderAsynchronousOutputWritten:
1327 break;
1328
Chris Lattner24943d22010-06-08 16:52:24 +00001329 case eInputReaderGotToken:
1330 {
1331 std::string temp_string (bytes, bytes_len);
1332 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001333 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001334 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001335 out_stream->Printf ("%s", reader.GetPrompt());
1336 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001337 }
Chris Lattner24943d22010-06-08 16:52:24 +00001338 }
1339 break;
1340
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001341 case eInputReaderEndOfFile:
1342 case eInputReaderInterrupt:
1343 // Control-c (SIGINT) & control-d both mean finish & exit.
1344 reader.SetIsDone(true);
1345
1346 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1347 if (notification == eInputReaderInterrupt)
1348 commands_in_progress.Clear();
1349
1350 // Fall through here...
1351
Chris Lattner24943d22010-06-08 16:52:24 +00001352 case eInputReaderDone:
1353 {
1354 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1355 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1356 data_ap->user_source.AppendList (commands_in_progress);
1357 if (data_ap.get())
1358 {
Greg Clayton63094e02010-06-23 01:19:29 +00001359 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001360 if (interpreter)
1361 {
1362 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1363 data_ap->script_source))
1364 {
Enrico Granata400105d2012-03-06 23:42:15 +00001365 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1366 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001367 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001368 else if (!batch_mode)
1369 {
1370 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1371 out_stream->Flush();
1372 }
Chris Lattner24943d22010-06-08 16:52:24 +00001373 }
1374 else
1375 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001376 if (!batch_mode)
1377 {
1378 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1379 out_stream->Flush();
1380 }
Chris Lattner24943d22010-06-08 16:52:24 +00001381 }
1382 }
1383 }
1384 break;
1385
1386 }
1387
1388 return bytes_len;
1389}
1390
1391void
Greg Clayton238c0a12010-09-18 01:14:36 +00001392ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001393 CommandReturnObject &result)
1394{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001395 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1396
Greg Clayton63094e02010-06-23 01:19:29 +00001397 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001398
1399 if (reader_sp)
1400 {
1401 Error err = reader_sp->Initialize (
1402 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1403 bp_options, // baton
1404 eInputReaderGranularityLine, // token size, for feeding data to callback function
1405 "DONE", // end token
1406 "> ", // prompt
1407 true); // echo input
1408
1409 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001410 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001411 else
1412 {
1413 result.AppendError (err.AsCString());
1414 result.SetStatus (eReturnStatusFailed);
1415 }
1416 }
1417 else
1418 {
1419 result.AppendError("out of memory");
1420 result.SetStatus (eReturnStatusFailed);
1421 }
1422}
1423
Johnny Chen3e0571b2010-09-11 00:23:59 +00001424// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001425void
Greg Clayton238c0a12010-09-18 01:14:36 +00001426ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001427 const char *oneliner)
1428{
1429 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1430
1431 // It's necessary to set both user_source and script_source to the oneliner.
1432 // The former is used to generate callback description (as in breakpoint command list)
1433 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001434
Johnny Chend1c2dca2010-09-10 18:21:10 +00001435 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001436
Caroline Tice5136f942010-09-27 21:35:15 +00001437 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1438 {
Enrico Granata400105d2012-03-06 23:42:15 +00001439 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1440 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Caroline Tice5136f942010-09-27 21:35:15 +00001441 }
1442
Johnny Chend1c2dca2010-09-10 18:21:10 +00001443 return;
1444}
1445
Chris Lattner24943d22010-06-08 16:52:24 +00001446bool
1447ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1448{
1449 // Convert StringList to one long, newline delimited, const char *.
Enrico Granata400105d2012-03-06 23:42:15 +00001450 std::string function_def_string(function_def.CopyList());
Chris Lattner24943d22010-06-08 16:52:24 +00001451
Enrico Granataa1ba3142012-06-07 00:17:18 +00001452 return ExecuteMultipleLines (function_def_string.c_str(), false);
Chris Lattner24943d22010-06-08 16:52:24 +00001453}
1454
Enrico Granataf7a9b142011-07-15 02:26:42 +00001455bool
Enrico Granata400105d2012-03-06 23:42:15 +00001456ScriptInterpreterPython::GenerateFunction(const char *signature, const StringList &input)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001457{
1458 int num_lines = input.GetSize ();
1459 if (num_lines == 0)
1460 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001461
1462 if (!signature || *signature == 0)
1463 return false;
1464
Enrico Granataf7a9b142011-07-15 02:26:42 +00001465 StreamString sstr;
1466 StringList auto_generated_function;
Enrico Granata400105d2012-03-06 23:42:15 +00001467 auto_generated_function.AppendString (signature);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001468 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1469 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1470 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1471 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1472 // global dictionary.
1473
1474 // Wrap everything up inside the function, increasing the indentation.
1475
1476 for (int i = 0; i < num_lines; ++i)
1477 {
1478 sstr.Clear ();
1479 sstr.Printf (" %s", input.GetStringAtIndex (i));
1480 auto_generated_function.AppendString (sstr.GetData());
1481 }
1482 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1483 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1484 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1485 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1486
1487 // Verify that the results are valid Python.
1488
1489 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1490 return false;
1491
1492 return true;
1493
1494}
1495
Enrico Granataf7a9b142011-07-15 02:26:42 +00001496bool
Enrico Granata400105d2012-03-06 23:42:15 +00001497ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001498{
Enrico Granata400105d2012-03-06 23:42:15 +00001499 static uint32_t num_created_functions = 0;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001500 user_input.RemoveBlankLines ();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001501 StreamString sstr;
1502
1503 // Check to see if we have any data; if not, just return.
1504 if (user_input.GetSize() == 0)
1505 return false;
1506
1507 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1508 // ValueObject as parameter to the function.
1509
Enrico Granata400105d2012-03-06 23:42:15 +00001510 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_type_print_func", num_created_functions, name_token));
Enrico Granataf7a9b142011-07-15 02:26:42 +00001511 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
Enrico Granataf7a9b142011-07-15 02:26:42 +00001512
Enrico Granata400105d2012-03-06 23:42:15 +00001513 if (!GenerateFunction(sstr.GetData(), user_input))
Enrico Granataf7a9b142011-07-15 02:26:42 +00001514 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001515
Enrico Granataf7a9b142011-07-15 02:26:42 +00001516 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001517 output.assign(auto_generated_function_name);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001518 return true;
1519}
1520
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001521bool
Enrico Granata400105d2012-03-06 23:42:15 +00001522ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, std::string &output)
Enrico Granatac2a28252011-08-16 16:49:25 +00001523{
Enrico Granata400105d2012-03-06 23:42:15 +00001524 static uint32_t num_created_functions = 0;
Enrico Granatac2a28252011-08-16 16:49:25 +00001525 user_input.RemoveBlankLines ();
Enrico Granatac2a28252011-08-16 16:49:25 +00001526 StreamString sstr;
1527
1528 // Check to see if we have any data; if not, just return.
1529 if (user_input.GetSize() == 0)
1530 return false;
1531
Enrico Granata400105d2012-03-06 23:42:15 +00001532 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_cmd_alias_func", num_created_functions));
1533
Enrico Granata271568f2011-09-09 01:41:30 +00001534 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001535
Enrico Granata400105d2012-03-06 23:42:15 +00001536 if (!GenerateFunction(sstr.GetData(),user_input))
Enrico Granatac2a28252011-08-16 16:49:25 +00001537 return false;
1538
1539 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001540 output.assign(auto_generated_function_name);
Enrico Granatac2a28252011-08-16 16:49:25 +00001541 return true;
1542}
1543
1544
1545bool
Enrico Granata400105d2012-03-06 23:42:15 +00001546ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, std::string &output, void* name_token)
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001547{
Enrico Granata400105d2012-03-06 23:42:15 +00001548 static uint32_t num_created_classes = 0;
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001549 user_input.RemoveBlankLines ();
1550 int num_lines = user_input.GetSize ();
1551 StreamString sstr;
1552
1553 // Check to see if we have any data; if not, just return.
1554 if (user_input.GetSize() == 0)
1555 return false;
1556
1557 // Wrap all user input into a Python class
1558
Enrico Granata400105d2012-03-06 23:42:15 +00001559 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 +00001560
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001561 StringList auto_generated_class;
1562
1563 // Create the function name & definition string.
1564
1565 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1566 auto_generated_class.AppendString (sstr.GetData());
1567
1568 // Wrap everything up inside the class, increasing the indentation.
1569
1570 for (int i = 0; i < num_lines; ++i)
1571 {
1572 sstr.Clear ();
1573 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1574 auto_generated_class.AppendString (sstr.GetData());
1575 }
1576
1577
1578 // Verify that the results are valid Python.
1579 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1580 // (TODO: rename that method to ExportDefinitionToInterpreter)
1581 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1582 return false;
1583
1584 // Store the name of the auto-generated class
1585
Enrico Granata400105d2012-03-06 23:42:15 +00001586 output.assign(auto_generated_class_name);
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001587 return true;
1588}
1589
Enrico Granata400105d2012-03-06 23:42:15 +00001590lldb::ScriptInterpreterObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001591ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1592 lldb::ValueObjectSP valobj)
1593{
1594 if (class_name.empty())
Enrico Granata400105d2012-03-06 23:42:15 +00001595 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001596
1597 if (!valobj.get())
Enrico Granata400105d2012-03-06 23:42:15 +00001598 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001599
Greg Claytonb4d7fc02012-02-17 07:49:44 +00001600 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1601 Target *target = exe_ctx.GetTargetPtr();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001602
1603 if (!target)
Enrico Granata400105d2012-03-06 23:42:15 +00001604 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001605
1606 Debugger &debugger = target->GetDebugger();
1607 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1608 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1609
1610 if (!script_interpreter)
Enrico Granata400105d2012-03-06 23:42:15 +00001611 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001612
1613 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001614
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001615 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001616 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001617 ForceDisableSyntheticChildren no_synthetics(target);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001618 ret_val = g_swig_synthetic_script (class_name,
1619 python_interpreter->m_dictionary_name.c_str(),
1620 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001621 }
1622
Enrico Granata400105d2012-03-06 23:42:15 +00001623 return MakeScriptObject(ret_val);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001624}
1625
Enrico Granataf7a9b142011-07-15 02:26:42 +00001626bool
Enrico Granata400105d2012-03-06 23:42:15 +00001627ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001628{
Enrico Granata16376ed2012-02-15 02:34:21 +00001629 StringList input;
1630 input.SplitIntoLines(oneliner, strlen(oneliner));
1631 return GenerateTypeScriptFunction(input, output, name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001632}
1633
Chris Lattner24943d22010-06-08 16:52:24 +00001634bool
Enrico Granata400105d2012-03-06 23:42:15 +00001635ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, std::string& output, void* name_token)
Enrico Granata16376ed2012-02-15 02:34:21 +00001636{
1637 StringList input;
1638 input.SplitIntoLines(oneliner, strlen(oneliner));
1639 return GenerateTypeSynthClass(input, output, name_token);
1640}
1641
1642
1643bool
Enrico Granata400105d2012-03-06 23:42:15 +00001644ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, std::string& output)
Chris Lattner24943d22010-06-08 16:52:24 +00001645{
Enrico Granata400105d2012-03-06 23:42:15 +00001646 static uint32_t num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001647 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001648 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001649
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001650 if (user_input.GetSize() == 0)
1651 return false;
1652
Enrico Granata400105d2012-03-06 23:42:15 +00001653 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_bp_callback_func_",num_created_functions));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001654 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001655
Enrico Granata400105d2012-03-06 23:42:15 +00001656 if (!GenerateFunction(sstr.GetData(), user_input))
Caroline Ticeb447e842010-09-21 19:25:28 +00001657 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001658
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001659 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001660 output.assign(auto_generated_function_name);
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001661 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001662}
1663
Enrico Granata1328b142012-02-29 03:28:49 +00001664bool
1665ScriptInterpreterPython::GetScriptedSummary (const char *python_function_name,
1666 lldb::ValueObjectSP valobj,
1667 lldb::ScriptInterpreterObjectSP& callee_wrapper_sp,
1668 std::string& retval)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001669{
1670
Enrico Granata1328b142012-02-29 03:28:49 +00001671 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001672
1673 if (!valobj.get())
Enrico Granata1328b142012-02-29 03:28:49 +00001674 {
1675 retval.assign("<no object>");
1676 return false;
1677 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001678
Enrico Granata1328b142012-02-29 03:28:49 +00001679 void* old_callee = (callee_wrapper_sp ? callee_wrapper_sp->GetObject() : NULL);
1680 void* new_callee = old_callee;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001681
Enrico Granata1328b142012-02-29 03:28:49 +00001682 bool ret_val;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001683 if (python_function_name
1684 && *python_function_name)
1685 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00001686 {
Enrico Granata1328b142012-02-29 03:28:49 +00001687 Locker py_lock(this);
1688 {
1689 Timer scoped_timer ("g_swig_typescript_callback","g_swig_typescript_callback");
1690 ret_val = g_swig_typescript_callback (python_function_name,
1691 FindSessionDictionary(m_dictionary_name.c_str()),
1692 valobj,
1693 &new_callee,
1694 retval);
1695 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00001696 }
1697 }
1698 else
Enrico Granata1328b142012-02-29 03:28:49 +00001699 {
1700 retval.assign("<no function name>");
1701 return false;
1702 }
1703
1704 if (new_callee && old_callee != new_callee)
1705 callee_wrapper_sp = MakeScriptObject(new_callee);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001706
1707 return ret_val;
1708
1709}
1710
Greg Clayton5144f382010-10-07 17:14:24 +00001711bool
1712ScriptInterpreterPython::BreakpointCallbackFunction
1713(
1714 void *baton,
1715 StoppointCallbackContext *context,
1716 user_id_t break_id,
1717 user_id_t break_loc_id
1718)
1719{
1720 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
Enrico Granata400105d2012-03-06 23:42:15 +00001721 const char *python_function_name = bp_option_data->script_source.c_str();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001722
1723 if (!context)
1724 return true;
1725
Greg Claytonf4124de2012-02-21 00:09:25 +00001726 ExecutionContext exe_ctx (context->exe_ctx_ref);
1727 Target *target = exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001728
1729 if (!target)
1730 return true;
1731
1732 Debugger &debugger = target->GetDebugger();
1733 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1734 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1735
1736 if (!script_interpreter)
1737 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001738
1739 if (python_function_name != NULL
1740 && python_function_name[0] != '\0')
1741 {
Greg Claytonf4124de2012-02-21 00:09:25 +00001742 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001743 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001744 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001745 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001746 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1747
1748 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001749 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001750 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00001751 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001752 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00001753 ret_val = g_swig_breakpoint_callback (python_function_name,
1754 python_interpreter->m_dictionary_name.c_str(),
1755 stop_frame_sp,
1756 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001757 }
1758 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001759 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001760 }
Greg Clayton5144f382010-10-07 17:14:24 +00001761 }
1762 // We currently always true so we stop in case anything goes wrong when
1763 // trying to call the script function
1764 return true;
1765}
Caroline Tice2ade6112010-11-10 19:18:14 +00001766
1767lldb::thread_result_t
1768ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1769{
1770 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1771
1772 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1773
1774 if (log)
1775 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1776
1777 char error_str[1024];
1778 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001779
Enrico Granatafa1f6172011-10-24 17:22:21 +00001780 Locker locker(script_interpreter,
1781 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1782 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
1783
1784 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00001785 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001786 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001787
Caroline Tice0aa2e552011-01-14 00:29:16 +00001788 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1789 PyRun_SimpleString (run_string.GetData());
1790 run_string.Clear ();
1791
1792 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1793 PyRun_SimpleString (run_string.GetData());
1794 run_string.Clear ();
1795
1796 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1797 PyRun_SimpleString (run_string.GetData());
1798 run_string.Clear ();
1799
1800 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1801 pty_slave_name);
1802 PyRun_SimpleString (run_string.GetData());
1803 run_string.Clear ();
1804
Johnny Chen8054ba32011-03-11 00:28:50 +00001805 // The following call drops into the embedded interpreter loop and stays there until the
1806 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001807
Caroline Ticece207c12011-03-11 00:21:55 +00001808 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001809 // 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 +00001810 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1811
1812 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1813 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1814 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1815 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1816 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1817 // hang (it's happened before).
1818
Caroline Tice9d352ce2011-03-07 23:24:28 +00001819 Py_BEGIN_ALLOW_THREADS
1820 PyGILState_STATE gstate = PyGILState_Ensure();
1821
Caroline Tice0aa2e552011-01-14 00:29:16 +00001822 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1823 PyRun_SimpleString (run_string.GetData());
1824 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001825
Caroline Tice9d352ce2011-03-07 23:24:28 +00001826 PyGILState_Release (gstate);
1827 Py_END_ALLOW_THREADS
1828
Caroline Tice0aa2e552011-01-14 00:29:16 +00001829 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1830 PyRun_SimpleString (run_string.GetData());
1831 run_string.Clear();
1832
1833 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1834 PyRun_SimpleString (run_string.GetData());
1835 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001836
Caroline Tice2ade6112010-11-10 19:18:14 +00001837 }
1838
1839 if (script_interpreter->m_embedded_thread_input_reader_sp)
1840 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1841
1842 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001843
Caroline Tice2ade6112010-11-10 19:18:14 +00001844 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1845 if (log)
1846 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1847
1848
Johnny Chen8054ba32011-03-11 00:28:50 +00001849 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001850 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001851 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1852 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1853 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001854
Caroline Tice2ade6112010-11-10 19:18:14 +00001855 return NULL;
1856}
1857
Enrico Granataa1ba3142012-06-07 00:17:18 +00001858lldb::thread_result_t
1859ScriptInterpreterPython::PythonInputReaderManager::RunPythonInputReader (lldb::thread_arg_t baton)
1860{
1861 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1862
1863 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1864
1865 if (reader_sp)
1866 reader_sp->WaitOnReaderIsDone();
1867
1868 return NULL;
1869}
1870
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001871uint32_t
Enrico Granata400105d2012-03-06 23:42:15 +00001872ScriptInterpreterPython::CalculateNumChildren (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001873{
Enrico Granata400105d2012-03-06 23:42:15 +00001874 if (!implementor_sp)
1875 return 0;
1876
1877 void* implementor = implementor_sp->GetObject();
1878
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001879 if (!implementor)
1880 return 0;
1881
1882 if (!g_swig_calc_children)
1883 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001884
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001885 uint32_t ret_val = 0;
1886
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001887 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001888 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001889 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001890 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001891 }
1892
1893 return ret_val;
1894}
1895
Enrico Granata91544802011-09-06 19:20:51 +00001896lldb::ValueObjectSP
Enrico Granata400105d2012-03-06 23:42:15 +00001897ScriptInterpreterPython::GetChildAtIndex (const lldb::ScriptInterpreterObjectSP& implementor_sp, uint32_t idx)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001898{
Enrico Granata400105d2012-03-06 23:42:15 +00001899 if (!implementor_sp)
1900 return lldb::ValueObjectSP();
1901
1902 void* implementor = implementor_sp->GetObject();
1903
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001904 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001905 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001906
Enrico Granata91544802011-09-06 19:20:51 +00001907 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1908 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001909
Enrico Granata91544802011-09-06 19:20:51 +00001910 void* child_ptr = NULL;
1911 lldb::SBValue* value_sb = NULL;
1912 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001913
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001914 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001915 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001916 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata91544802011-09-06 19:20:51 +00001917 child_ptr = g_swig_get_child_index (implementor,idx);
1918 if (child_ptr != NULL && child_ptr != Py_None)
1919 {
1920 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1921 if (value_sb == NULL)
1922 Py_XDECREF(child_ptr);
1923 else
1924 ret_val = value_sb->get_sp();
1925 }
1926 else
1927 {
1928 Py_XDECREF(child_ptr);
1929 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001930 }
1931
1932 return ret_val;
1933}
1934
1935int
Enrico Granata400105d2012-03-06 23:42:15 +00001936ScriptInterpreterPython::GetIndexOfChildWithName (const lldb::ScriptInterpreterObjectSP& implementor_sp, const char* child_name)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001937{
Enrico Granata400105d2012-03-06 23:42:15 +00001938 if (!implementor_sp)
1939 return UINT32_MAX;
1940
1941 void* implementor = implementor_sp->GetObject();
1942
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001943 if (!implementor)
1944 return UINT32_MAX;
1945
1946 if (!g_swig_get_index_child)
1947 return UINT32_MAX;
1948
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001949 int ret_val = UINT32_MAX;
1950
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001951 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001952 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001953 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001954 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001955 }
1956
1957 return ret_val;
1958}
1959
Enrico Granatacf09f882012-03-19 22:58:49 +00001960bool
Enrico Granata400105d2012-03-06 23:42:15 +00001961ScriptInterpreterPython::UpdateSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata979e20d2011-07-29 19:53:35 +00001962{
Enrico Granatacf09f882012-03-19 22:58:49 +00001963 bool ret_val = false;
1964
Enrico Granata400105d2012-03-06 23:42:15 +00001965 if (!implementor_sp)
Enrico Granatacf09f882012-03-19 22:58:49 +00001966 return ret_val;
Enrico Granata400105d2012-03-06 23:42:15 +00001967
1968 void* implementor = implementor_sp->GetObject();
1969
Enrico Granata979e20d2011-07-29 19:53:35 +00001970 if (!implementor)
Enrico Granatacf09f882012-03-19 22:58:49 +00001971 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001972
1973 if (!g_swig_update_provider)
Enrico Granatacf09f882012-03-19 22:58:49 +00001974 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001975
Enrico Granata979e20d2011-07-29 19:53:35 +00001976 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001977 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001978 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granatacf09f882012-03-19 22:58:49 +00001979 ret_val = g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001980 }
1981
Enrico Granatacf09f882012-03-19 22:58:49 +00001982 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00001983}
1984
Enrico Granatac2a28252011-08-16 16:49:25 +00001985bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001986ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00001987 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00001988 lldb_private::Error& error)
1989{
1990 if (!pathname || !pathname[0])
1991 {
1992 error.SetErrorString("invalid pathname");
1993 return false;
1994 }
1995
1996 if (!g_swig_call_module_init)
1997 {
1998 error.SetErrorString("internal helper function missing");
1999 return false;
2000 }
2001
Greg Clayton13d24fb2012-01-29 20:56:30 +00002002 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granatafa1f6172011-10-24 17:22:21 +00002003
Enrico Granata59df36f2011-10-17 21:45:27 +00002004 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002005 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00002006
2007 FileSpec target_file(pathname, true);
2008
2009 // TODO: would we want to reject any other value?
2010 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
2011 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
2012 {
2013 error.SetErrorString("invalid pathname");
2014 return false;
2015 }
2016
2017 const char* directory = target_file.GetDirectory().GetCString();
2018 std::string basename(target_file.GetFilename().GetCString());
2019
2020 // now make sure that Python has "directory" in the search path
2021 StreamString command_stream;
2022 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
2023 directory,
2024 directory);
Enrico Granataa1ba3142012-06-07 00:17:18 +00002025 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData(), false);
Enrico Granata59df36f2011-10-17 21:45:27 +00002026 if (!syspath_retval)
2027 {
2028 error.SetErrorString("Python sys.path handling failed");
2029 return false;
2030 }
2031
2032 // strip .py or .pyc extension
2033 ConstString extension = target_file.GetFileNameExtension();
2034 if (::strcmp(extension.GetCString(), "py") == 0)
2035 basename.resize(basename.length()-3);
2036 else if(::strcmp(extension.GetCString(), "pyc") == 0)
2037 basename.resize(basename.length()-4);
2038
2039 // check if the module is already import-ed
2040 command_stream.Clear();
2041 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
2042 int refcount = 0;
2043 // this call will fail if the module does not exist (because the parameter to it is not a string
2044 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00002045 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
Enrico Granataa1ba3142012-06-07 00:17:18 +00002046 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount, false) && refcount > 0);
Enrico Granata6010ace2011-11-07 22:57:04 +00002047 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00002048 {
2049 error.SetErrorString("module already imported");
2050 return false;
2051 }
2052
2053 // now actually do the import
2054 command_stream.Clear();
2055 command_stream.Printf("import %s",basename.c_str());
Enrico Granataa1ba3142012-06-07 00:17:18 +00002056 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL, false);
Enrico Granata59df36f2011-10-17 21:45:27 +00002057 if (!import_retval)
2058 {
2059 error.SetErrorString("Python import statement failed");
2060 return false;
2061 }
2062
Enrico Granata16376ed2012-02-15 02:34:21 +00002063 // call __lldb_init_module(debugger,dict)
Enrico Granata59df36f2011-10-17 21:45:27 +00002064 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00002065 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00002066 debugger_sp))
2067 {
Enrico Granata16376ed2012-02-15 02:34:21 +00002068 error.SetErrorString("calling __lldb_init_module failed");
Enrico Granata59df36f2011-10-17 21:45:27 +00002069 return false;
2070 }
2071 return true;
2072 }
2073}
2074
Enrico Granata1328b142012-02-29 03:28:49 +00002075lldb::ScriptInterpreterObjectSP
2076ScriptInterpreterPython::MakeScriptObject (void* object)
2077{
2078 return lldb::ScriptInterpreterObjectSP(new ScriptInterpreterPythonObject(object));
2079}
2080
Enrico Granata6010ace2011-11-07 22:57:04 +00002081ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
2082 ScriptedCommandSynchronicity synchro) :
2083 m_debugger_sp(debugger_sp),
2084 m_synch_wanted(synchro),
2085 m_old_asynch(debugger_sp->GetAsyncExecution())
2086{
2087 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2088 m_debugger_sp->SetAsyncExecution(false);
2089 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2090 m_debugger_sp->SetAsyncExecution(true);
2091}
2092
2093ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
2094{
2095 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2096 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2097}
2098
Enrico Granata59df36f2011-10-17 21:45:27 +00002099bool
Enrico Granatac2a28252011-08-16 16:49:25 +00002100ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
2101 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00002102 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00002103 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00002104 Error& error)
2105{
2106 if (!impl_function)
2107 {
2108 error.SetErrorString("no function to execute");
2109 return false;
2110 }
2111
2112 if (!g_swig_call_command)
2113 {
2114 error.SetErrorString("no helper function to run scripted commands");
2115 return false;
2116 }
2117
Greg Clayton13d24fb2012-01-29 20:56:30 +00002118 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata6010ace2011-11-07 22:57:04 +00002119
2120 if (!debugger_sp.get())
2121 {
2122 error.SetErrorString("invalid Debugger pointer");
2123 return false;
2124 }
Enrico Granatac2a28252011-08-16 16:49:25 +00002125
2126 bool ret_val;
2127
2128 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00002129
Enrico Granatac2a28252011-08-16 16:49:25 +00002130 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002131 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00002132 SynchronicityHandler synch_handler(debugger_sp,
2133 synchronicity);
2134
Enrico Granataa1ba3142012-06-07 00:17:18 +00002135 PythonInputReaderManager py_input(this);
2136
Enrico Granatac2a28252011-08-16 16:49:25 +00002137 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00002138 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00002139 debugger_sp,
2140 args,
2141 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00002142 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00002143 }
Enrico Granata6010ace2011-11-07 22:57:04 +00002144
Enrico Granatac2a28252011-08-16 16:49:25 +00002145 if (!ret_val)
2146 error.SetErrorString(err_msg.c_str());
2147 else
2148 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00002149
Enrico Granatac2a28252011-08-16 16:49:25 +00002150 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00002151}
2152
Enrico Granatae5e34cb2011-08-17 01:30:04 +00002153// in Python, a special attribute __doc__ contains the docstring
2154// for an object (function, method, class, ...) if any is defined
2155// Otherwise, the attribute's value is None
2156std::string
2157ScriptInterpreterPython::GetDocumentationForItem(const char* item)
2158{
2159 std::string command(item);
2160 command += ".__doc__";
2161
2162 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
2163
2164 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00002165 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granataa1ba3142012-06-07 00:17:18 +00002166 &result_ptr, false) && result_ptr)
Enrico Granatae5e34cb2011-08-17 01:30:04 +00002167 {
2168 return std::string(result_ptr);
2169 }
2170 else
2171 return std::string("");
2172}
Caroline Tice2ade6112010-11-10 19:18:14 +00002173
Caroline Tice0aa2e552011-01-14 00:29:16 +00002174void
Enrico Granata1328b142012-02-29 03:28:49 +00002175ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback)
Greg Claytone86cbb92011-03-22 01:14:58 +00002176{
2177 g_swig_init_callback = python_swig_init_callback;
Enrico Granata1328b142012-02-29 03:28:49 +00002178 g_swig_breakpoint_callback = LLDBSwigPythonBreakpointCallbackFunction;
2179 g_swig_typescript_callback = LLDBSwigPythonCallTypeScript;
2180 g_swig_synthetic_script = LLDBSwigPythonCreateSyntheticProvider;
2181 g_swig_calc_children = LLDBSwigPython_CalculateNumChildren;
2182 g_swig_get_child_index = LLDBSwigPython_GetChildAtIndex;
2183 g_swig_get_index_child = LLDBSwigPython_GetIndexOfChildWithName;
2184 g_swig_cast_to_sbvalue = LLDBSWIGPython_CastPyObjectToSBValue;
2185 g_swig_update_provider = LLDBSwigPython_UpdateSynthProviderInstance;
2186 g_swig_call_command = LLDBSwigPythonCallCommand;
2187 g_swig_call_module_init = LLDBSwigPythonCallModuleInit;
Greg Claytone86cbb92011-03-22 01:14:58 +00002188}
2189
2190void
2191ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00002192{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002193 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
2194
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002195 // Python will muck with STDIN terminal state, so save off any current TTY
2196 // settings so we can restore them.
2197 TerminalState stdin_tty_state;
2198 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002199
Caroline Tice9d352ce2011-03-07 23:24:28 +00002200 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00002201 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002202
Greg Claytone86cbb92011-03-22 01:14:58 +00002203 // Initialize SWIG after setting up python
2204 assert (g_swig_init_callback != NULL);
2205 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002206
2207 // Update the path python uses to search for modules to include the current directory.
2208
Caroline Ticed4d92832011-06-13 21:33:00 +00002209 PyRun_SimpleString ("import sys");
2210 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00002211
2212 // Find the module that owns this code and use that path we get to
2213 // set the sys.path appropriately.
2214
2215 FileSpec file_spec;
2216 char python_dir_path[PATH_MAX];
2217 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
2218 {
2219 std::string python_path("sys.path.insert(0,\"");
2220 size_t orig_len = python_path.length();
2221 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2222 {
2223 python_path.append (python_dir_path);
2224 python_path.append ("\")");
2225 PyRun_SimpleString (python_path.c_str());
2226 python_path.resize (orig_len);
2227 }
2228
2229 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
2230 {
2231 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2232 {
2233 python_path.append (python_dir_path);
2234 python_path.append ("\")");
2235 PyRun_SimpleString (python_path.c_str());
2236 python_path.resize (orig_len);
2237 }
2238 }
2239 }
2240
Greg Clayton4e651b12012-04-25 00:58:03 +00002241 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 +00002242
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002243 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002244}
2245
Greg Claytone86cbb92011-03-22 01:14:58 +00002246//void
2247//ScriptInterpreterPython::Terminate ()
2248//{
2249// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
2250// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
2251// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
2252// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
2253// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
2254// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
2255// // within Py_Finalize, which results in a seg fault.
2256// //
2257// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
2258// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
2259// // process exits).
2260// //
2261//// Py_Finalize ();
2262//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00002263
2264#endif // #ifdef LLDB_DISABLE_PYTHON