blob: 03eadc6f5496674c3f7311c8a371f735b2dfbe56 [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
Greg Clayton17f5afe2011-02-05 02:56:16 +000011// the *FIRST* header file included in ScriptInterpreterPython.h, and that
12// must be the *FIRST* header file included here.
Chris Lattner24943d22010-06-08 16:52:24 +000013
14#include "lldb/Interpreter/ScriptInterpreterPython.h"
15
Chris Lattner24943d22010-06-08 16:52:24 +000016#include <stdlib.h>
17#include <stdio.h>
18
19#include <string>
20
Greg Clayton5144f382010-10-07 17:14:24 +000021#include "lldb/API/SBFrame.h"
22#include "lldb/API/SBBreakpointLocation.h"
Greg Clayton63094e02010-06-23 01:19:29 +000023#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000025#include "lldb/Core/Timer.h"
26#include "lldb/Host/Host.h"
27#include "lldb/Interpreter/CommandInterpreter.h"
28#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton5144f382010-10-07 17:14:24 +000029#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030
Chris Lattner24943d22010-06-08 16:52:24 +000031using namespace lldb;
32using namespace lldb_private;
33
Greg Claytone86cbb92011-03-22 01:14:58 +000034
35static ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL;
36static ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL;
Enrico Granataf7a9b142011-07-15 02:26:42 +000037static ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL;
Enrico Granata9ae7cef2011-07-24 00:14:56 +000038static ScriptInterpreter::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = NULL;
39static ScriptInterpreter::SWIGPythonCalculateNumChildren g_swig_calc_children = NULL;
40static ScriptInterpreter::SWIGPythonGetChildAtIndex g_swig_get_child_index = NULL;
41static ScriptInterpreter::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = NULL;
42static ScriptInterpreter::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +000043
44static int
45_check_and_flush (FILE *stream)
46{
47 int prev_fail = ferror (stream);
48 return fflush (stream) || prev_fail ? EOF : 0;
49}
50
Caroline Tice202f6b82011-01-17 21:55:19 +000051static Predicate<lldb::tid_t> &
52PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +000053{
Caroline Tice202f6b82011-01-17 21:55:19 +000054 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
55 return g_interpreter_is_running;
56}
57
58static bool
59CurrentThreadHasPythonLock ()
60{
61 TimeValue timeout;
62
63 timeout = TimeValue::Now(); // Don't wait any time.
64
65 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
66}
67
68static bool
69GetPythonLock (uint32_t seconds_to_wait)
70{
71
72 TimeValue timeout;
73
74 if (seconds_to_wait != UINT32_MAX)
75 {
76 timeout = TimeValue::Now();
77 timeout.OffsetWithSeconds (seconds_to_wait);
78 }
79
80 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
81 Host::GetCurrentThreadID(), &timeout, NULL);
82}
83
84static void
85ReleasePythonLock ()
86{
87 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +000088}
89
Greg Clayton63094e02010-06-23 01:19:29 +000090ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +000091 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +000092 m_embedded_python_pty (),
93 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +000094 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +000095 m_new_sysout (NULL),
96 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +000097 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +000098 m_session_is_active (false),
99 m_pty_slave_is_open (false),
100 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000101{
102
Greg Clayton7c330d62011-01-27 01:01:10 +0000103 static int g_initialized = false;
104
105 if (!g_initialized)
106 {
107 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000108 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000109 }
110
Caroline Tice202f6b82011-01-17 21:55:19 +0000111 bool safe_to_run = false;
112 bool need_to_release_lock = true;
113 int interval = 5; // Number of seconds to try getting the Python lock before timing out.
114
115 // We don't dare exit this function without finishing setting up the script interpreter, so we must wait until
116 // we can get the Python lock.
117
118 if (CurrentThreadHasPythonLock())
119 {
120 safe_to_run = true;
121 need_to_release_lock = false;
122 }
123
124 while (!safe_to_run)
125 {
126 safe_to_run = GetPythonLock (interval);
127 if (!safe_to_run)
128 {
129 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
130 fprintf (tmp_fh,
131 "Python interpreter is locked on another thread; "
132 "please release interpreter in order to continue.\n");
133 interval = interval * 2;
134 }
135 }
136
Caroline Tice0aa2e552011-01-14 00:29:16 +0000137 m_dictionary_name.append("_dict");
138 StreamString run_string;
139 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
140 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000141
Caroline Tice0aa2e552011-01-14 00:29:16 +0000142 run_string.Clear();
143 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
144 PyRun_SimpleString (run_string.GetData());
145
146 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
147 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
148 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
149 // call to Debugger::Terminate is made, the ref-count has the correct value.
150 //
151 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
152 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000153
Caroline Tice0aa2e552011-01-14 00:29:16 +0000154 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000155
Caroline Tice0aa2e552011-01-14 00:29:16 +0000156 run_string.Clear();
157 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
158 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000159
Caroline Tice0aa2e552011-01-14 00:29:16 +0000160 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000161
Caroline Tice0aa2e552011-01-14 00:29:16 +0000162 if (new_count > old_count)
163 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000164
Caroline Tice0aa2e552011-01-14 00:29:16 +0000165 run_string.Clear();
166 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
167 PyRun_SimpleString (run_string.GetData());
168
169 run_string.Clear();
170 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
171 interpreter.GetDebugger().GetID());
172 PyRun_SimpleString (run_string.GetData());
173
174 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000175 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000176 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000177 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000178
179 if (need_to_release_lock)
180 ReleasePythonLock();
Chris Lattner24943d22010-06-08 16:52:24 +0000181}
182
183ScriptInterpreterPython::~ScriptInterpreterPython ()
184{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000185 Debugger &debugger = GetCommandInterpreter().GetDebugger();
186
187 if (m_embedded_thread_input_reader_sp.get() != NULL)
188 {
189 m_embedded_thread_input_reader_sp->SetIsDone (true);
190 m_embedded_python_pty.CloseSlaveFileDescriptor();
191 m_pty_slave_is_open = false;
192 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
193 m_embedded_thread_input_reader_sp.reset();
194 debugger.PopInputReader (reader_sp);
195 }
196
197 if (m_new_sysout)
198 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000199 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
200 if (!CurrentThreadHasPythonLock ())
201 {
202 while (!GetPythonLock (1))
203 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
204 Py_DECREF (m_new_sysout);
205 ReleasePythonLock ();
206 }
207 else
208 Py_DECREF (m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000209 }
Chris Lattner24943d22010-06-08 16:52:24 +0000210}
211
Caroline Tice0aa2e552011-01-14 00:29:16 +0000212void
213ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
214{
215 if (fh == NULL)
216 return;
217
218 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000219
Caroline Tice202f6b82011-01-17 21:55:19 +0000220 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
221 if (!CurrentThreadHasPythonLock ())
222 {
223 while (!GetPythonLock (1))
224 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
225 EnterSession ();
226 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
227 LeaveSession ();
228 ReleasePythonLock ();
229 }
230 else
231 {
232 EnterSession ();
233 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
234 LeaveSession ();
235 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000236}
237
238void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000239ScriptInterpreterPython::SaveTerminalState (int fd)
240{
241 // Python mucks with the terminal state of STDIN. If we can possibly avoid
242 // this by setting the file handles up correctly prior to entering the
243 // interpreter we should. For now we save and restore the terminal state
244 // on the input file handle.
245 m_terminal_state.Save (fd, false);
246}
247
248void
249ScriptInterpreterPython::RestoreTerminalState ()
250{
251 // Python mucks with the terminal state of STDIN. If we can possibly avoid
252 // this by setting the file handles up correctly prior to entering the
253 // interpreter we should. For now we save and restore the terminal state
254 // on the input file handle.
255 m_terminal_state.Restore();
256}
257
258
259
260void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000261ScriptInterpreterPython::LeaveSession ()
262{
263 m_session_is_active = false;
264}
265
266void
267ScriptInterpreterPython::EnterSession ()
268{
269 // If we have already entered the session, without having officially 'left' it, then there is no need to
270 // 'enter' it again.
271
272 if (m_session_is_active)
273 return;
274
275 m_session_is_active = true;
276
Caroline Tice202f6b82011-01-17 21:55:19 +0000277 StreamString run_string;
278
279 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
280 GetCommandInterpreter().GetDebugger().GetID());
281 PyRun_SimpleString (run_string.GetData());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000282 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +0000283
Caroline Tice0aa2e552011-01-14 00:29:16 +0000284
Caroline Tice6af65cb2011-05-03 21:21:50 +0000285 run_string.Printf ("run_one_line (%s, 'lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%d)')",
286 m_dictionary_name.c_str(),
287 GetCommandInterpreter().GetDebugger().GetID());
288 PyRun_SimpleString (run_string.GetData());
289 run_string.Clear();
290
291
292 ExecutionContext exe_ctx = m_interpreter.GetDebugger().GetSelectedExecutionContext();
293
294 if (exe_ctx.target)
295 run_string.Printf ("run_one_line (%s, 'lldb.target = lldb.debugger.GetSelectedTarget()')",
296 m_dictionary_name.c_str());
297 else
298 run_string.Printf ("run_one_line (%s, 'lldb.target = None')", m_dictionary_name.c_str());
299 PyRun_SimpleString (run_string.GetData());
300 run_string.Clear();
301
302 if (exe_ctx.process)
303 run_string.Printf ("run_one_line (%s, 'lldb.process = lldb.target.GetProcess()')", m_dictionary_name.c_str());
304 else
305 run_string.Printf ("run_one_line (%s, 'lldb.process = None')", m_dictionary_name.c_str());
306 PyRun_SimpleString (run_string.GetData());
307 run_string.Clear();
308
309 if (exe_ctx.thread)
310 run_string.Printf ("run_one_line (%s, 'lldb.thread = lldb.process.GetSelectedThread ()')",
311 m_dictionary_name.c_str());
312 else
313 run_string.Printf ("run_one_line (%s, 'lldb.thread = None')", m_dictionary_name.c_str());
314 PyRun_SimpleString (run_string.GetData());
315 run_string.Clear();
316
317 if (exe_ctx.frame)
318 run_string.Printf ("run_one_line (%s, 'lldb.frame = lldb.thread.GetSelectedFrame ()')",
319 m_dictionary_name.c_str());
320 else
321 run_string.Printf ("run_one_line (%s, 'lldb.frame = None')", m_dictionary_name.c_str());
322 PyRun_SimpleString (run_string.GetData());
323 run_string.Clear();
324
Caroline Tice0aa2e552011-01-14 00:29:16 +0000325 PyObject *sysmod = PyImport_AddModule ("sys");
326 PyObject *sysdict = PyModule_GetDict (sysmod);
327
328 if ((m_new_sysout != NULL)
329 && (sysmod != NULL)
330 && (sysdict != NULL))
331 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
332
333 if (PyErr_Occurred())
334 PyErr_Clear ();
335
Caroline Tice0aa2e552011-01-14 00:29:16 +0000336 if (!m_pty_slave_is_open)
337 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000338 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000339 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
340 m_pty_slave_name.c_str());
341 PyRun_SimpleString (run_string.GetData());
342 m_pty_slave_is_open = true;
343
344 run_string.Clear();
345 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
346 PyRun_SimpleString (run_string.GetData());
347 }
348}
349
350
Johnny Chen60dde642010-07-30 22:33:14 +0000351bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000352ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000353{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000354 if (!m_valid_session)
355 return false;
356
Caroline Tice0aa2e552011-01-14 00:29:16 +0000357
Caroline Tice0aa2e552011-01-14 00:29:16 +0000358
Caroline Tice4a461da2011-01-14 21:09:29 +0000359 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
360 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
361 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
362 // method to pass the command string directly down to Python.
363
364
Caroline Tice202f6b82011-01-17 21:55:19 +0000365 bool need_to_release_lock = true;
366
367 if (CurrentThreadHasPythonLock())
368 need_to_release_lock = false;
369 else if (!GetPythonLock (1))
370 {
371 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
372 "Python interpreter is currently locked by another thread; unable to process command.\n");
373 return false;
374 }
375
376 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000377 bool success = false;
378
Greg Clayton63094e02010-06-23 01:19:29 +0000379 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000380 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000381 // Find the correct script interpreter dictionary in the main module.
382 PyObject *main_mod = PyImport_AddModule ("__main__");
383 PyObject *script_interpreter_dict = NULL;
384 if (main_mod != NULL)
385 {
386 PyObject *main_dict = PyModule_GetDict (main_mod);
387 if ((main_dict != NULL)
388 && PyDict_Check (main_dict))
389 {
390 // Go through the main dictionary looking for the correct python script interpreter dictionary
391 PyObject *key, *value;
392 Py_ssize_t pos = 0;
393
394 while (PyDict_Next (main_dict, &pos, &key, &value))
395 {
396 // We have stolen references to the key and value objects in the dictionary; we need to increment
397 // them now so that Python's garbage collector doesn't collect them out from under us.
398 Py_INCREF (key);
399 Py_INCREF (value);
400 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
401 {
402 script_interpreter_dict = value;
403 break;
404 }
405 }
406 }
407
408 if (script_interpreter_dict != NULL)
409 {
410 PyObject *pfunc = NULL;
411 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
412 if (pmod != NULL)
413 {
414 PyObject *pmod_dict = PyModule_GetDict (pmod);
415 if ((pmod_dict != NULL)
416 && PyDict_Check (pmod_dict))
417 {
418 PyObject *key, *value;
419 Py_ssize_t pos = 0;
420
421 while (PyDict_Next (pmod_dict, &pos, &key, &value))
422 {
423 Py_INCREF (key);
424 Py_INCREF (value);
425 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
426 {
427 pfunc = value;
428 break;
429 }
430 }
431
432 PyObject *string_arg = PyString_FromString (command);
433 if (pfunc && string_arg && PyCallable_Check (pfunc))
434 {
435 PyObject *pargs = PyTuple_New (2);
436 if (pargs != NULL)
437 {
438 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
439 PyTuple_SetItem (pargs, 1, string_arg);
440 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
441 Py_DECREF (pargs);
442 if (pvalue != NULL)
443 {
444 Py_DECREF (pvalue);
445 success = true;
446 }
447 else if (PyErr_Occurred ())
448 {
449 PyErr_Print();
450 PyErr_Clear();
451 }
452 }
453 }
454 }
455 }
456 Py_INCREF (script_interpreter_dict);
457 }
458 }
Greg Clayton63094e02010-06-23 01:19:29 +0000459
Caroline Tice0aa2e552011-01-14 00:29:16 +0000460 LeaveSession ();
461
Caroline Tice202f6b82011-01-17 21:55:19 +0000462 if (need_to_release_lock)
463 ReleasePythonLock();
464
Caroline Tice4a461da2011-01-14 21:09:29 +0000465 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000466 return true;
467
468 // The one-liner failed. Append the error message.
469 if (result)
470 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
471 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000472 }
Johnny Chen60dde642010-07-30 22:33:14 +0000473
Caroline Tice0aa2e552011-01-14 00:29:16 +0000474 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000475
476 if (need_to_release_lock)
477 ReleasePythonLock ();
478
Johnny Chen60dde642010-07-30 22:33:14 +0000479 if (result)
480 result->AppendError ("empty command passed to python\n");
481 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000482}
483
484
485
486size_t
487ScriptInterpreterPython::InputReaderCallback
488(
489 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000490 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000491 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000492 const char *bytes,
493 size_t bytes_len
494)
495{
Caroline Tice2ade6112010-11-10 19:18:14 +0000496 lldb::thread_t embedded_interpreter_thread;
497 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
498
Chris Lattner24943d22010-06-08 16:52:24 +0000499 if (baton == NULL)
500 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000501
502 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
503
504 if (script_interpreter->m_script_lang != eScriptLanguagePython)
505 return 0;
506
Caroline Tice892fadd2011-06-16 16:27:19 +0000507 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
508 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
509
Chris Lattner24943d22010-06-08 16:52:24 +0000510 switch (notification)
511 {
512 case eInputReaderActivate:
513 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000514 if (!batch_mode)
515 {
516 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
517 out_stream->Flush();
518 }
Greg Clayton58928562011-02-09 01:08:52 +0000519
Chris Lattner24943d22010-06-08 16:52:24 +0000520 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000521 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
522 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000523 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000524
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000525 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000526
Caroline Tice202f6b82011-01-17 21:55:19 +0000527 if (!CurrentThreadHasPythonLock())
528 {
529 while (!GetPythonLock(1))
530 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000531 out_stream->Printf ("Python interpreter locked on another thread; waiting to acquire lock...\n");
532 out_stream->Flush();
Caroline Tice202f6b82011-01-17 21:55:19 +0000533 }
534 script_interpreter->EnterSession ();
535 ReleasePythonLock();
536 }
537 else
538 script_interpreter->EnterSession ();
539
Caroline Tice2ade6112010-11-10 19:18:14 +0000540 char error_str[1024];
541 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
542 sizeof(error_str)))
543 {
544 if (log)
545 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
546 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
547 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
548 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
549 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000550 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000551 {
552 if (log)
553 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
554 Error detach_error;
555 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
556 }
557 else
558 {
559 if (log)
560 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
561 reader.SetIsDone (true);
562 }
563 }
564 else
565 {
566 if (log)
567 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
568 reader.SetIsDone (true);
569 }
Chris Lattner24943d22010-06-08 16:52:24 +0000570 }
571 break;
572
573 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000574 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000575 break;
576
577 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000578 if (!CurrentThreadHasPythonLock())
579 {
580 while (!GetPythonLock(1))
581 {
582 // Wait until lock is acquired.
583 }
584 script_interpreter->EnterSession ();
585 ReleasePythonLock();
586 }
587 else
588 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000589 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000590
Caroline Tice4a348082011-05-02 20:41:46 +0000591 case eInputReaderAsynchronousOutputWritten:
592 break;
593
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000594 case eInputReaderInterrupt:
595 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
596 break;
597
598 case eInputReaderEndOfFile:
599 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
600 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000601
602 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000603 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000604 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000605 if (log)
606 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
607 bytes_len);
608 if (bytes && bytes_len)
609 {
610 if ((int) bytes[0] == 4)
611 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
612 else
613 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
614 }
615 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000616 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000617 else
618 {
619 if (log)
620 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
621 bytes,
622 bytes_len);
623 reader.SetIsDone (true);
624 }
625
Chris Lattner24943d22010-06-08 16:52:24 +0000626 break;
627
628 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000629 script_interpreter->LeaveSession ();
630
Chris Lattner24943d22010-06-08 16:52:24 +0000631 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000632 if (log)
633 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000634
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000635 script_interpreter->RestoreTerminalState ();
636
Caroline Tice2ade6112010-11-10 19:18:14 +0000637 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000638 break;
639 }
640
641 return bytes_len;
642}
643
644
645void
Greg Clayton238c0a12010-09-18 01:14:36 +0000646ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000647{
648 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
649
Caroline Tice0aa2e552011-01-14 00:29:16 +0000650 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000651
652 // At the moment, the only time the debugger does not have an input file handle is when this is called
653 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
654 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
655 // do it.
656
Greg Clayton58928562011-02-09 01:08:52 +0000657 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000658 return;
659
Greg Clayton63094e02010-06-23 01:19:29 +0000660 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000661 if (reader_sp)
662 {
663 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
664 this, // baton
665 eInputReaderGranularityLine, // token size, to pass to callback function
666 NULL, // end token
667 NULL, // prompt
668 true)); // echo input
669
670 if (error.Success())
671 {
Greg Clayton63094e02010-06-23 01:19:29 +0000672 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000673 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000674 }
675 }
676}
677
678bool
679ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
680 ScriptInterpreter::ReturnType return_type,
681 void *ret_value)
682{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000683
Caroline Tice202f6b82011-01-17 21:55:19 +0000684 bool need_to_release_lock = true;
685
686 if (CurrentThreadHasPythonLock())
687 need_to_release_lock = false;
688 else if (!GetPythonLock (1))
689 {
690 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
691 "Python interpreter is currently locked by another thread; unable to process command.\n");
692 return false;
693 }
694
695 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000696
Chris Lattner24943d22010-06-08 16:52:24 +0000697 PyObject *py_return = NULL;
698 PyObject *mainmod = PyImport_AddModule ("__main__");
699 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000700 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000701 PyObject *py_error = NULL;
702 bool ret_success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000703 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000704 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000705
706 if (PyDict_Check (globals))
707 {
708 PyObject *key, *value;
709 Py_ssize_t pos = 0;
710
711 int i = 0;
712 while (PyDict_Next (globals, &pos, &key, &value))
713 {
714 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
715 // so that Python's garbage collector doesn't collect them out from under us.
716 Py_INCREF (key);
717 Py_INCREF (value);
718 char *c_str = PyString_AsString (key);
719 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
720 locals = value;
721 ++i;
722 }
723 }
Chris Lattner24943d22010-06-08 16:52:24 +0000724
Caroline Tice0aa2e552011-01-14 00:29:16 +0000725 if (locals == NULL)
726 {
727 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
728 should_decrement_locals = true;
729 }
730
731 if (locals == NULL)
732 {
733 locals = globals;
734 should_decrement_locals = false;
735 }
736
737 py_error = PyErr_Occurred();
738 if (py_error != NULL)
739 PyErr_Clear();
740
Chris Lattner24943d22010-06-08 16:52:24 +0000741 if (in_string != NULL)
742 {
743 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
744 if (py_return == NULL)
745 {
746 py_error = PyErr_Occurred ();
747 if (py_error != NULL)
748 PyErr_Clear ();
749
750 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
751 }
752
Caroline Tice0aa2e552011-01-14 00:29:16 +0000753 if (locals != NULL
754 && should_decrement_locals)
755 Py_DECREF (locals);
756
Chris Lattner24943d22010-06-08 16:52:24 +0000757 if (py_return != NULL)
758 {
759 switch (return_type)
760 {
761 case eCharPtr: // "char *"
762 {
763 const char format[3] = "s#";
764 success = PyArg_Parse (py_return, format, (char **) &ret_value);
765 break;
766 }
767 case eBool:
768 {
769 const char format[2] = "b";
770 success = PyArg_Parse (py_return, format, (bool *) ret_value);
771 break;
772 }
773 case eShortInt:
774 {
775 const char format[2] = "h";
776 success = PyArg_Parse (py_return, format, (short *) ret_value);
777 break;
778 }
779 case eShortIntUnsigned:
780 {
781 const char format[2] = "H";
782 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
783 break;
784 }
785 case eInt:
786 {
787 const char format[2] = "i";
788 success = PyArg_Parse (py_return, format, (int *) ret_value);
789 break;
790 }
791 case eIntUnsigned:
792 {
793 const char format[2] = "I";
794 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
795 break;
796 }
797 case eLongInt:
798 {
799 const char format[2] = "l";
800 success = PyArg_Parse (py_return, format, (long *) ret_value);
801 break;
802 }
803 case eLongIntUnsigned:
804 {
805 const char format[2] = "k";
806 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
807 break;
808 }
809 case eLongLong:
810 {
811 const char format[2] = "L";
812 success = PyArg_Parse (py_return, format, (long long *) ret_value);
813 break;
814 }
815 case eLongLongUnsigned:
816 {
817 const char format[2] = "K";
818 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
819 break;
820 }
821 case eFloat:
822 {
823 const char format[2] = "f";
824 success = PyArg_Parse (py_return, format, (float *) ret_value);
825 break;
826 }
827 case eDouble:
828 {
829 const char format[2] = "d";
830 success = PyArg_Parse (py_return, format, (double *) ret_value);
831 break;
832 }
833 case eChar:
834 {
835 const char format[2] = "c";
836 success = PyArg_Parse (py_return, format, (char *) ret_value);
837 break;
838 }
839 default:
840 {}
841 }
842 Py_DECREF (py_return);
843 if (success)
844 ret_success = true;
845 else
846 ret_success = false;
847 }
848 }
849
850 py_error = PyErr_Occurred();
851 if (py_error != NULL)
852 {
853 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
854 PyErr_Print ();
855 PyErr_Clear();
856 ret_success = false;
857 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000858
859 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000860
Caroline Tice202f6b82011-01-17 21:55:19 +0000861 if (need_to_release_lock)
862 ReleasePythonLock();
863
Chris Lattner24943d22010-06-08 16:52:24 +0000864 return ret_success;
865}
866
867bool
868ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
869{
Caroline Tice202f6b82011-01-17 21:55:19 +0000870 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
871 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000872
Caroline Tice202f6b82011-01-17 21:55:19 +0000873 if (CurrentThreadHasPythonLock())
874 need_to_release_lock = false;
875 else
876 {
877 while (!GetPythonLock (1))
878 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
879 }
880
881 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000882
Chris Lattner24943d22010-06-08 16:52:24 +0000883 bool success = false;
884 PyObject *py_return = NULL;
885 PyObject *mainmod = PyImport_AddModule ("__main__");
886 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000887 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000888 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000889 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000890
Caroline Tice0aa2e552011-01-14 00:29:16 +0000891 if (PyDict_Check (globals))
892 {
893 PyObject *key, *value;
894 Py_ssize_t pos = 0;
895
896 while (PyDict_Next (globals, &pos, &key, &value))
897 {
898 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
899 // so that Python's garbage collector doesn't collect them out from under us.
900 Py_INCREF (key);
901 Py_INCREF (value);
902 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
903 locals = value;
904 }
905 }
906
907 if (locals == NULL)
908 {
909 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
910 should_decrement_locals = true;
911 }
912
913 if (locals == NULL)
914 {
915 locals = globals;
916 should_decrement_locals = false;
917 }
918
919 py_error = PyErr_Occurred();
920 if (py_error != NULL)
921 PyErr_Clear();
922
Chris Lattner24943d22010-06-08 16:52:24 +0000923 if (in_string != NULL)
924 {
925 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
926 if (compiled_node)
927 {
928 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
929 if (compiled_code)
930 {
931 py_return = PyEval_EvalCode (compiled_code, globals, locals);
932 if (py_return != NULL)
933 {
934 success = true;
935 Py_DECREF (py_return);
936 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000937 if (locals && should_decrement_locals)
938 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000939 }
940 }
941 }
942
943 py_error = PyErr_Occurred ();
944 if (py_error != NULL)
945 {
946 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
947 PyErr_Print ();
948 PyErr_Clear();
949 success = false;
950 }
951
Caroline Tice0aa2e552011-01-14 00:29:16 +0000952 LeaveSession ();
953
Caroline Tice202f6b82011-01-17 21:55:19 +0000954 if (need_to_release_lock)
955 ReleasePythonLock();
956
Chris Lattner24943d22010-06-08 16:52:24 +0000957 return success;
958}
959
960static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
961
962size_t
963ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
964(
965 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000966 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000967 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000968 const char *bytes,
969 size_t bytes_len
970)
971{
Caroline Tice892fadd2011-06-16 16:27:19 +0000972 static StringList commands_in_progress;
973
974 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
975 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
976
Chris Lattner24943d22010-06-08 16:52:24 +0000977 switch (notification)
978 {
979 case eInputReaderActivate:
980 {
981 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +0000982 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +0000983 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000984 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000985 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +0000986 out_stream->Printf ("%s", reader.GetPrompt());
987 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +0000988 }
989 }
990 break;
991
992 case eInputReaderDeactivate:
993 break;
994
995 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +0000996 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000997 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000998 out_stream->Printf ("%s", reader.GetPrompt());
999 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001000 }
Chris Lattner24943d22010-06-08 16:52:24 +00001001 break;
1002
Caroline Tice4a348082011-05-02 20:41:46 +00001003 case eInputReaderAsynchronousOutputWritten:
1004 break;
1005
Chris Lattner24943d22010-06-08 16:52:24 +00001006 case eInputReaderGotToken:
1007 {
1008 std::string temp_string (bytes, bytes_len);
1009 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001010 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001011 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001012 out_stream->Printf ("%s", reader.GetPrompt());
1013 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001014 }
Chris Lattner24943d22010-06-08 16:52:24 +00001015 }
1016 break;
1017
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001018 case eInputReaderEndOfFile:
1019 case eInputReaderInterrupt:
1020 // Control-c (SIGINT) & control-d both mean finish & exit.
1021 reader.SetIsDone(true);
1022
1023 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1024 if (notification == eInputReaderInterrupt)
1025 commands_in_progress.Clear();
1026
1027 // Fall through here...
1028
Chris Lattner24943d22010-06-08 16:52:24 +00001029 case eInputReaderDone:
1030 {
1031 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1032 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1033 data_ap->user_source.AppendList (commands_in_progress);
1034 if (data_ap.get())
1035 {
Greg Clayton63094e02010-06-23 01:19:29 +00001036 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001037 if (interpreter)
1038 {
1039 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1040 data_ap->script_source))
1041 {
1042 if (data_ap->script_source.GetSize() == 1)
1043 {
1044 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1045 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1046 }
1047 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001048 else if (!batch_mode)
1049 {
1050 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1051 out_stream->Flush();
1052 }
Chris Lattner24943d22010-06-08 16:52:24 +00001053 }
1054 else
1055 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001056 if (!batch_mode)
1057 {
1058 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1059 out_stream->Flush();
1060 }
Chris Lattner24943d22010-06-08 16:52:24 +00001061 }
1062 }
1063 }
1064 break;
1065
1066 }
1067
1068 return bytes_len;
1069}
1070
1071void
Greg Clayton238c0a12010-09-18 01:14:36 +00001072ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001073 CommandReturnObject &result)
1074{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001075 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1076
Greg Clayton63094e02010-06-23 01:19:29 +00001077 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001078
1079 if (reader_sp)
1080 {
1081 Error err = reader_sp->Initialize (
1082 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1083 bp_options, // baton
1084 eInputReaderGranularityLine, // token size, for feeding data to callback function
1085 "DONE", // end token
1086 "> ", // prompt
1087 true); // echo input
1088
1089 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001090 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001091 else
1092 {
1093 result.AppendError (err.AsCString());
1094 result.SetStatus (eReturnStatusFailed);
1095 }
1096 }
1097 else
1098 {
1099 result.AppendError("out of memory");
1100 result.SetStatus (eReturnStatusFailed);
1101 }
1102}
1103
Johnny Chen3e0571b2010-09-11 00:23:59 +00001104// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001105void
Greg Clayton238c0a12010-09-18 01:14:36 +00001106ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001107 const char *oneliner)
1108{
1109 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1110
1111 // It's necessary to set both user_source and script_source to the oneliner.
1112 // The former is used to generate callback description (as in breakpoint command list)
1113 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001114
Johnny Chend1c2dca2010-09-10 18:21:10 +00001115 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001116
Caroline Tice5136f942010-09-27 21:35:15 +00001117 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1118 {
1119 if (data_ap->script_source.GetSize() == 1)
1120 {
1121 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1122 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1123 }
1124 }
1125
Johnny Chend1c2dca2010-09-10 18:21:10 +00001126 return;
1127}
1128
Chris Lattner24943d22010-06-08 16:52:24 +00001129bool
1130ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1131{
1132 // Convert StringList to one long, newline delimited, const char *.
1133 std::string function_def_string;
1134
1135 int num_lines = function_def.GetSize();
1136
1137 for (int i = 0; i < num_lines; ++i)
1138 {
1139 function_def_string.append (function_def.GetStringAtIndex(i));
1140 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1141 function_def_string.append ("\n");
1142
1143 }
1144
1145 return ExecuteMultipleLines (function_def_string.c_str());
1146}
1147
Enrico Granataf7a9b142011-07-15 02:26:42 +00001148// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1149// use this code to generate their functions
1150bool
1151ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1152{
1153 int num_lines = input.GetSize ();
1154 if (num_lines == 0)
1155 return false;
1156 StreamString sstr;
1157 StringList auto_generated_function;
1158 auto_generated_function.AppendString (signature.c_str());
1159 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1160 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1161 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1162 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1163 // global dictionary.
1164
1165 // Wrap everything up inside the function, increasing the indentation.
1166
1167 for (int i = 0; i < num_lines; ++i)
1168 {
1169 sstr.Clear ();
1170 sstr.Printf (" %s", input.GetStringAtIndex (i));
1171 auto_generated_function.AppendString (sstr.GetData());
1172 }
1173 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1174 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1175 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1176 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1177
1178 // Verify that the results are valid Python.
1179
1180 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1181 return false;
1182
1183 return true;
1184
1185}
1186
1187// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1188// given to generated functions, of course)
1189bool
1190ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output)
1191{
1192 static int num_created_functions = 0;
1193 user_input.RemoveBlankLines ();
1194 int num_lines = user_input.GetSize ();
1195 StreamString sstr;
1196
1197 // Check to see if we have any data; if not, just return.
1198 if (user_input.GetSize() == 0)
1199 return false;
1200
1201 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1202 // ValueObject as parameter to the function.
1203
1204 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1205 ++num_created_functions;
1206 std::string auto_generated_function_name = sstr.GetData();
1207
1208 sstr.Clear();
1209 StringList auto_generated_function;
1210
1211 // Create the function name & definition string.
1212
1213 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1214 auto_generated_function.AppendString (sstr.GetData());
1215
1216 // Pre-pend code for setting up the session dictionary.
1217
1218 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1219 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1220 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1221 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1222 // global dictionary.
1223
1224 // Wrap everything up inside the function, increasing the indentation.
1225
1226 for (int i = 0; i < num_lines; ++i)
1227 {
1228 sstr.Clear ();
1229 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1230 auto_generated_function.AppendString (sstr.GetData());
1231 }
1232
1233 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1234 // got written to the values in the global dictionary, not the session dictionary).
1235
1236 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1237 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1238 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1239 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1240
1241 // Verify that the results are valid Python.
1242
1243 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1244 return false;
1245
1246 // Store the name of the auto-generated function to be called.
1247
1248 output.AppendString (auto_generated_function_name.c_str());
1249 return true;
1250}
1251
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001252void*
1253ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1254 lldb::ValueObjectSP valobj)
1255{
1256 if (class_name.empty())
1257 return NULL;
1258
1259 if (!valobj.get())
1260 return NULL;
1261
1262 Target *target = valobj->GetUpdatePoint().GetTarget();
1263
1264 if (!target)
1265 return NULL;
1266
1267 Debugger &debugger = target->GetDebugger();
1268 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1269 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1270
1271 if (!script_interpreter)
1272 return NULL;
1273
1274 void* ret_val;
1275
1276 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1277 if (CurrentThreadHasPythonLock())
1278 {
1279 python_interpreter->EnterSession ();
1280 ret_val = g_swig_synthetic_script (class_name,
1281 python_interpreter->m_dictionary_name.c_str(),
1282 valobj);
1283 python_interpreter->LeaveSession ();
1284 }
1285 else
1286 {
1287 while (!GetPythonLock (1))
1288 fprintf (tmp_fh,
1289 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1290 python_interpreter->EnterSession ();
1291 ret_val = g_swig_synthetic_script (class_name,
1292 python_interpreter->m_dictionary_name.c_str(),
1293 valobj);
1294 python_interpreter->LeaveSession ();
1295 ReleasePythonLock ();
1296 }
1297
1298 return ret_val;
1299}
1300
Enrico Granataf7a9b142011-07-15 02:26:42 +00001301bool
1302ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output)
1303{
1304 StringList input(oneliner);
1305 return GenerateTypeScriptFunction(input, output);
1306}
1307
Chris Lattner24943d22010-06-08 16:52:24 +00001308bool
1309ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1310{
1311 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001312 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001313 int num_lines = user_input.GetSize ();
1314 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001315
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001316 // Check to see if we have any data; if not, just return.
1317 if (user_input.GetSize() == 0)
1318 return false;
1319
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001320 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1321 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001322
Caroline Ticeb447e842010-09-21 19:25:28 +00001323
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001324 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1325 ++num_created_functions;
1326 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001327
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001328 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001329 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001330
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001331 // Create the function name & definition string.
1332
Caroline Tice0aa2e552011-01-14 00:29:16 +00001333 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001334 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001335
1336 // Pre-pend code for setting up the session dictionary.
1337
1338 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1339 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1340 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1341 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1342 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001343
1344 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001345
1346 for (int i = 0; i < num_lines; ++i)
1347 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001348 sstr.Clear ();
1349 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1350 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001351 }
Chris Lattner24943d22010-06-08 16:52:24 +00001352
Caroline Tice0aa2e552011-01-14 00:29:16 +00001353 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1354 // got written to the values in the global dictionary, not the session dictionary).
1355
1356 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1357 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1358 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1359 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1360
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001361 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001362
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001363 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001364 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001365 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001366 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001367
1368 // Store the name of the auto-generated function to be called.
1369
1370 callback_data.AppendString (auto_generated_function_name.c_str());
1371 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001372}
1373
Enrico Granataf7a9b142011-07-15 02:26:42 +00001374std::string
1375ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1376 lldb::ValueObjectSP valobj)
1377{
1378
1379 if (!python_function_name || !(*python_function_name))
1380 return "<no function>";
1381
1382 if (!valobj.get())
1383 return "<no object>";
1384
1385 Target *target = valobj->GetUpdatePoint().GetTarget();
1386
1387 if (!target)
1388 return "<no target>";
1389
1390 Debugger &debugger = target->GetDebugger();
1391 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1392 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1393
1394 if (!script_interpreter)
1395 return "<no python>";
1396
1397 std::string ret_val;
1398
1399 if (python_function_name
1400 && *python_function_name)
1401 {
1402 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1403 if (CurrentThreadHasPythonLock())
1404 {
1405 python_interpreter->EnterSession ();
1406 ret_val = g_swig_typescript_callback (python_function_name,
1407 python_interpreter->m_dictionary_name.c_str(),
1408 valobj);
1409 python_interpreter->LeaveSession ();
1410 }
1411 else
1412 {
1413 while (!GetPythonLock (1))
1414 fprintf (tmp_fh,
1415 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1416 python_interpreter->EnterSession ();
1417 ret_val = g_swig_typescript_callback (python_function_name,
1418 python_interpreter->m_dictionary_name.c_str(),
1419 valobj);
1420 python_interpreter->LeaveSession ();
1421 ReleasePythonLock ();
1422 }
1423 }
1424 else
1425 return "<no function name>";
1426
1427 return ret_val;
1428
1429}
1430
Greg Clayton5144f382010-10-07 17:14:24 +00001431bool
1432ScriptInterpreterPython::BreakpointCallbackFunction
1433(
1434 void *baton,
1435 StoppointCallbackContext *context,
1436 user_id_t break_id,
1437 user_id_t break_loc_id
1438)
1439{
1440 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1441 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001442
1443 if (!context)
1444 return true;
1445
1446 Target *target = context->exe_ctx.target;
1447
1448 if (!target)
1449 return true;
1450
1451 Debugger &debugger = target->GetDebugger();
1452 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1453 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1454
1455 if (!script_interpreter)
1456 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001457
1458 if (python_function_name != NULL
1459 && python_function_name[0] != '\0')
1460 {
1461 Thread *thread = context->exe_ctx.thread;
Greg Claytone86cbb92011-03-22 01:14:58 +00001462 const StackFrameSP stop_frame_sp (thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame));
Greg Clayton5144f382010-10-07 17:14:24 +00001463 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001464 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001465 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001466 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1467
1468 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001469 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001470 bool ret_val = true;
1471 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1472 if (CurrentThreadHasPythonLock())
1473 {
1474 python_interpreter->EnterSession ();
1475 ret_val = g_swig_breakpoint_callback (python_function_name,
1476 python_interpreter->m_dictionary_name.c_str(),
1477 stop_frame_sp,
1478 bp_loc_sp);
1479 python_interpreter->LeaveSession ();
1480 }
1481 else
1482 {
1483 while (!GetPythonLock (1))
1484 fprintf (tmp_fh,
1485 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1486 python_interpreter->EnterSession ();
1487 ret_val = g_swig_breakpoint_callback (python_function_name,
1488 python_interpreter->m_dictionary_name.c_str(),
1489 stop_frame_sp,
1490 bp_loc_sp);
1491 python_interpreter->LeaveSession ();
1492 ReleasePythonLock ();
1493 }
1494 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001495 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001496 }
Greg Clayton5144f382010-10-07 17:14:24 +00001497 }
1498 // We currently always true so we stop in case anything goes wrong when
1499 // trying to call the script function
1500 return true;
1501}
Caroline Tice2ade6112010-11-10 19:18:14 +00001502
1503lldb::thread_result_t
1504ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1505{
1506 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1507
1508 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1509
1510 if (log)
1511 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1512
1513 char error_str[1024];
1514 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001515 bool need_to_release_lock = true;
1516 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001517
Caroline Tice202f6b82011-01-17 21:55:19 +00001518 if (CurrentThreadHasPythonLock())
1519 {
1520 safe_to_run = true;
1521 need_to_release_lock = false;
1522 }
1523 else
1524 {
1525 int interval = 1;
1526 safe_to_run = GetPythonLock (interval);
1527 while (!safe_to_run)
1528 {
1529 interval = interval * 2;
1530 safe_to_run = GetPythonLock (interval);
1531 }
1532 }
1533
1534 if (pty_slave_name != NULL && safe_to_run)
1535 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001536 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001537
Caroline Tice202f6b82011-01-17 21:55:19 +00001538 script_interpreter->EnterSession ();
1539
Caroline Tice0aa2e552011-01-14 00:29:16 +00001540 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1541 PyRun_SimpleString (run_string.GetData());
1542 run_string.Clear ();
1543
1544 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1545 PyRun_SimpleString (run_string.GetData());
1546 run_string.Clear ();
1547
1548 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1549 PyRun_SimpleString (run_string.GetData());
1550 run_string.Clear ();
1551
1552 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1553 pty_slave_name);
1554 PyRun_SimpleString (run_string.GetData());
1555 run_string.Clear ();
1556
Johnny Chen8054ba32011-03-11 00:28:50 +00001557 // The following call drops into the embedded interpreter loop and stays there until the
1558 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001559
Caroline Ticece207c12011-03-11 00:21:55 +00001560 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001561 // 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 +00001562 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1563
1564 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1565 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1566 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1567 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1568 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1569 // hang (it's happened before).
1570
Caroline Tice9d352ce2011-03-07 23:24:28 +00001571 Py_BEGIN_ALLOW_THREADS
1572 PyGILState_STATE gstate = PyGILState_Ensure();
1573
Caroline Tice0aa2e552011-01-14 00:29:16 +00001574 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1575 PyRun_SimpleString (run_string.GetData());
1576 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001577
Caroline Tice9d352ce2011-03-07 23:24:28 +00001578 PyGILState_Release (gstate);
1579 Py_END_ALLOW_THREADS
1580
Caroline Tice0aa2e552011-01-14 00:29:16 +00001581 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1582 PyRun_SimpleString (run_string.GetData());
1583 run_string.Clear();
1584
1585 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1586 PyRun_SimpleString (run_string.GetData());
1587 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001588
1589 script_interpreter->LeaveSession ();
1590
Caroline Tice2ade6112010-11-10 19:18:14 +00001591 }
1592
Caroline Tice202f6b82011-01-17 21:55:19 +00001593 if (!safe_to_run)
1594 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1595 "Python interpreter locked on another thread; unable to acquire lock.\n");
1596
1597 if (need_to_release_lock)
1598 ReleasePythonLock ();
1599
Caroline Tice2ade6112010-11-10 19:18:14 +00001600 if (script_interpreter->m_embedded_thread_input_reader_sp)
1601 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1602
1603 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001604
1605 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001606
1607 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1608 if (log)
1609 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1610
1611
Johnny Chen8054ba32011-03-11 00:28:50 +00001612 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001613 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001614 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1615 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1616 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001617
Caroline Tice2ade6112010-11-10 19:18:14 +00001618 return NULL;
1619}
1620
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001621uint32_t
1622ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1623{
1624 if (!implementor)
1625 return 0;
1626
1627 if (!g_swig_calc_children)
1628 return 0;
1629
1630 ScriptInterpreterPython *python_interpreter = this;
1631
1632 uint32_t ret_val = 0;
1633
1634 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1635 if (CurrentThreadHasPythonLock())
1636 {
1637 python_interpreter->EnterSession ();
1638 ret_val = g_swig_calc_children (implementor);
1639 python_interpreter->LeaveSession ();
1640 }
1641 else
1642 {
1643 while (!GetPythonLock (1))
1644 fprintf (tmp_fh,
1645 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1646 python_interpreter->EnterSession ();
1647 ret_val = g_swig_calc_children (implementor);
1648 python_interpreter->LeaveSession ();
1649 ReleasePythonLock ();
1650 }
1651
1652 return ret_val;
1653}
1654
1655void*
1656ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1657{
1658 if (!implementor)
1659 return 0;
1660
1661 if (!g_swig_get_child_index)
1662 return 0;
1663
1664 ScriptInterpreterPython *python_interpreter = this;
1665
1666 void* ret_val = NULL;
1667
1668 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1669 if (CurrentThreadHasPythonLock())
1670 {
1671 python_interpreter->EnterSession ();
1672 ret_val = g_swig_get_child_index (implementor,idx);
1673 python_interpreter->LeaveSession ();
1674 }
1675 else
1676 {
1677 while (!GetPythonLock (1))
1678 fprintf (tmp_fh,
1679 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1680 python_interpreter->EnterSession ();
1681 ret_val = g_swig_get_child_index (implementor,idx);
1682 python_interpreter->LeaveSession ();
1683 ReleasePythonLock ();
1684 }
1685
1686 return ret_val;
1687}
1688
1689int
1690ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1691{
1692 if (!implementor)
1693 return UINT32_MAX;
1694
1695 if (!g_swig_get_index_child)
1696 return UINT32_MAX;
1697
1698 ScriptInterpreterPython *python_interpreter = this;
1699
1700 int ret_val = UINT32_MAX;
1701
1702 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1703 if (CurrentThreadHasPythonLock())
1704 {
1705 python_interpreter->EnterSession ();
1706 ret_val = g_swig_get_index_child (implementor, child_name);
1707 python_interpreter->LeaveSession ();
1708 }
1709 else
1710 {
1711 while (!GetPythonLock (1))
1712 fprintf (tmp_fh,
1713 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1714 python_interpreter->EnterSession ();
1715 ret_val = g_swig_get_index_child (implementor, child_name);
1716 python_interpreter->LeaveSession ();
1717 ReleasePythonLock ();
1718 }
1719
1720 return ret_val;
1721}
1722
1723lldb::SBValue*
1724ScriptInterpreterPython::CastPyObjectToSBValue (void* data)
1725{
1726 if (!data)
1727 return NULL;
1728
1729 if (!g_swig_cast_to_sbvalue)
1730 return NULL;
1731
1732 ScriptInterpreterPython *python_interpreter = this;
1733
1734 lldb::SBValue* ret_val = NULL;
1735
1736 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1737 if (CurrentThreadHasPythonLock())
1738 {
1739 python_interpreter->EnterSession ();
1740 ret_val = g_swig_cast_to_sbvalue (data);
1741 python_interpreter->LeaveSession ();
1742 }
1743 else
1744 {
1745 while (!GetPythonLock (1))
1746 fprintf (tmp_fh,
1747 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1748 python_interpreter->EnterSession ();
1749 ret_val = g_swig_cast_to_sbvalue (data);
1750 python_interpreter->LeaveSession ();
1751 ReleasePythonLock ();
1752 }
1753
1754 return ret_val;
1755}
1756
Caroline Tice2ade6112010-11-10 19:18:14 +00001757
Caroline Tice0aa2e552011-01-14 00:29:16 +00001758void
Greg Claytone86cbb92011-03-22 01:14:58 +00001759ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00001760 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001761 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
1762 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
1763 SWIGPythonCalculateNumChildren python_swig_calc_children,
1764 SWIGPythonGetChildAtIndex python_swig_get_child_index,
1765 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
1766 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue)
Greg Claytone86cbb92011-03-22 01:14:58 +00001767{
1768 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001769 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1770 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001771 g_swig_synthetic_script = python_swig_synthetic_script;
1772 g_swig_calc_children = python_swig_calc_children;
1773 g_swig_get_child_index = python_swig_get_child_index;
1774 g_swig_get_index_child = python_swig_get_index_child;
1775 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Greg Claytone86cbb92011-03-22 01:14:58 +00001776}
1777
1778void
1779ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001780{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001781 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1782
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001783 // Python will muck with STDIN terminal state, so save off any current TTY
1784 // settings so we can restore them.
1785 TerminalState stdin_tty_state;
1786 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001787
1788 // Find the module that owns this code and use that path we get to
1789 // set the PYTHONPATH appropriately.
1790
1791 FileSpec file_spec;
1792 char python_dir_path[PATH_MAX];
1793 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1794 {
1795 std::string python_path;
1796 const char *curr_python_path = ::getenv ("PYTHONPATH");
1797 if (curr_python_path)
1798 {
1799 // We have a current value for PYTHONPATH, so lets append to it
1800 python_path.append (curr_python_path);
1801 }
1802
1803 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1804 {
1805 if (!python_path.empty())
1806 python_path.append (1, ':');
1807 python_path.append (python_dir_path);
1808 }
1809
1810 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1811 {
1812 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1813 {
1814 if (!python_path.empty())
1815 python_path.append (1, ':');
1816 python_path.append (python_dir_path);
1817 }
1818 }
1819 const char *pathon_path_env_cstr = python_path.c_str();
1820 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
1821 }
1822
Caroline Tice9d352ce2011-03-07 23:24:28 +00001823 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001824 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001825
Greg Claytone86cbb92011-03-22 01:14:58 +00001826 // Initialize SWIG after setting up python
1827 assert (g_swig_init_callback != NULL);
1828 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001829
1830 // Update the path python uses to search for modules to include the current directory.
1831
Caroline Ticed4d92832011-06-13 21:33:00 +00001832 PyRun_SimpleString ("import sys");
1833 PyRun_SimpleString ("sys.path.append ('.')");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001834
Caroline Ticed4d92832011-06-13 21:33:00 +00001835 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001836
Caroline Ticed4d92832011-06-13 21:33:00 +00001837 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1838 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
1839 PyRun_SimpleString ("import sys");
1840 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001841
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001842 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001843}
1844
Greg Claytone86cbb92011-03-22 01:14:58 +00001845//void
1846//ScriptInterpreterPython::Terminate ()
1847//{
1848// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1849// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1850// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1851// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1852// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1853// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1854// // within Py_Finalize, which results in a seg fault.
1855// //
1856// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1857// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1858// // process exits).
1859// //
1860//// Py_Finalize ();
1861//}