blob: f5351d7d2ae74edaa689de85addd490aab629f79 [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;
37
Chris Lattner24943d22010-06-08 16:52:24 +000038
39static int
40_check_and_flush (FILE *stream)
41{
42 int prev_fail = ferror (stream);
43 return fflush (stream) || prev_fail ? EOF : 0;
44}
45
Caroline Tice202f6b82011-01-17 21:55:19 +000046static Predicate<lldb::tid_t> &
47PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +000048{
Caroline Tice202f6b82011-01-17 21:55:19 +000049 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
50 return g_interpreter_is_running;
51}
52
53static bool
54CurrentThreadHasPythonLock ()
55{
56 TimeValue timeout;
57
58 timeout = TimeValue::Now(); // Don't wait any time.
59
60 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
61}
62
63static bool
64GetPythonLock (uint32_t seconds_to_wait)
65{
66
67 TimeValue timeout;
68
69 if (seconds_to_wait != UINT32_MAX)
70 {
71 timeout = TimeValue::Now();
72 timeout.OffsetWithSeconds (seconds_to_wait);
73 }
74
75 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
76 Host::GetCurrentThreadID(), &timeout, NULL);
77}
78
79static void
80ReleasePythonLock ()
81{
82 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +000083}
84
Greg Clayton63094e02010-06-23 01:19:29 +000085ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +000086 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +000087 m_embedded_python_pty (),
88 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +000089 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +000090 m_new_sysout (NULL),
91 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +000092 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +000093 m_session_is_active (false),
94 m_pty_slave_is_open (false),
95 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +000096{
97
Greg Clayton7c330d62011-01-27 01:01:10 +000098 static int g_initialized = false;
99
100 if (!g_initialized)
101 {
102 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000103 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000104 }
105
Caroline Tice202f6b82011-01-17 21:55:19 +0000106 bool safe_to_run = false;
107 bool need_to_release_lock = true;
108 int interval = 5; // Number of seconds to try getting the Python lock before timing out.
109
110 // We don't dare exit this function without finishing setting up the script interpreter, so we must wait until
111 // we can get the Python lock.
112
113 if (CurrentThreadHasPythonLock())
114 {
115 safe_to_run = true;
116 need_to_release_lock = false;
117 }
118
119 while (!safe_to_run)
120 {
121 safe_to_run = GetPythonLock (interval);
122 if (!safe_to_run)
123 {
124 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
125 fprintf (tmp_fh,
126 "Python interpreter is locked on another thread; "
127 "please release interpreter in order to continue.\n");
128 interval = interval * 2;
129 }
130 }
131
Caroline Tice0aa2e552011-01-14 00:29:16 +0000132 m_dictionary_name.append("_dict");
133 StreamString run_string;
134 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
135 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000136
Caroline Tice0aa2e552011-01-14 00:29:16 +0000137 run_string.Clear();
138 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
139 PyRun_SimpleString (run_string.GetData());
140
141 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
142 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
143 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
144 // call to Debugger::Terminate is made, the ref-count has the correct value.
145 //
146 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
147 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000148
Caroline Tice0aa2e552011-01-14 00:29:16 +0000149 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000150
Caroline Tice0aa2e552011-01-14 00:29:16 +0000151 run_string.Clear();
152 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
153 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000154
Caroline Tice0aa2e552011-01-14 00:29:16 +0000155 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000156
Caroline Tice0aa2e552011-01-14 00:29:16 +0000157 if (new_count > old_count)
158 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000159
Caroline Tice0aa2e552011-01-14 00:29:16 +0000160 run_string.Clear();
161 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
162 PyRun_SimpleString (run_string.GetData());
163
164 run_string.Clear();
165 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
166 interpreter.GetDebugger().GetID());
167 PyRun_SimpleString (run_string.GetData());
168
169 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000170 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000171 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000172 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000173
174 if (need_to_release_lock)
175 ReleasePythonLock();
Chris Lattner24943d22010-06-08 16:52:24 +0000176}
177
178ScriptInterpreterPython::~ScriptInterpreterPython ()
179{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000180 Debugger &debugger = GetCommandInterpreter().GetDebugger();
181
182 if (m_embedded_thread_input_reader_sp.get() != NULL)
183 {
184 m_embedded_thread_input_reader_sp->SetIsDone (true);
185 m_embedded_python_pty.CloseSlaveFileDescriptor();
186 m_pty_slave_is_open = false;
187 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
188 m_embedded_thread_input_reader_sp.reset();
189 debugger.PopInputReader (reader_sp);
190 }
191
192 if (m_new_sysout)
193 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000194 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
195 if (!CurrentThreadHasPythonLock ())
196 {
197 while (!GetPythonLock (1))
198 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
199 Py_DECREF (m_new_sysout);
200 ReleasePythonLock ();
201 }
202 else
203 Py_DECREF (m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000204 }
Chris Lattner24943d22010-06-08 16:52:24 +0000205}
206
Caroline Tice0aa2e552011-01-14 00:29:16 +0000207void
208ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
209{
210 if (fh == NULL)
211 return;
212
213 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000214
Caroline Tice202f6b82011-01-17 21:55:19 +0000215 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
216 if (!CurrentThreadHasPythonLock ())
217 {
218 while (!GetPythonLock (1))
219 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
220 EnterSession ();
221 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
222 LeaveSession ();
223 ReleasePythonLock ();
224 }
225 else
226 {
227 EnterSession ();
228 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
229 LeaveSession ();
230 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000231}
232
233void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000234ScriptInterpreterPython::SaveTerminalState (int fd)
235{
236 // Python mucks with the terminal state of STDIN. If we can possibly avoid
237 // this by setting the file handles up correctly prior to entering the
238 // interpreter we should. For now we save and restore the terminal state
239 // on the input file handle.
240 m_terminal_state.Save (fd, false);
241}
242
243void
244ScriptInterpreterPython::RestoreTerminalState ()
245{
246 // Python mucks with the terminal state of STDIN. If we can possibly avoid
247 // this by setting the file handles up correctly prior to entering the
248 // interpreter we should. For now we save and restore the terminal state
249 // on the input file handle.
250 m_terminal_state.Restore();
251}
252
253
254
255void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000256ScriptInterpreterPython::LeaveSession ()
257{
258 m_session_is_active = false;
259}
260
261void
262ScriptInterpreterPython::EnterSession ()
263{
264 // If we have already entered the session, without having officially 'left' it, then there is no need to
265 // 'enter' it again.
266
267 if (m_session_is_active)
268 return;
269
270 m_session_is_active = true;
271
Caroline Tice202f6b82011-01-17 21:55:19 +0000272 StreamString run_string;
273
274 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
275 GetCommandInterpreter().GetDebugger().GetID());
276 PyRun_SimpleString (run_string.GetData());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000277 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +0000278
Caroline Tice0aa2e552011-01-14 00:29:16 +0000279
Caroline Tice6af65cb2011-05-03 21:21:50 +0000280 run_string.Printf ("run_one_line (%s, 'lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%d)')",
281 m_dictionary_name.c_str(),
282 GetCommandInterpreter().GetDebugger().GetID());
283 PyRun_SimpleString (run_string.GetData());
284 run_string.Clear();
285
286
287 ExecutionContext exe_ctx = m_interpreter.GetDebugger().GetSelectedExecutionContext();
288
289 if (exe_ctx.target)
290 run_string.Printf ("run_one_line (%s, 'lldb.target = lldb.debugger.GetSelectedTarget()')",
291 m_dictionary_name.c_str());
292 else
293 run_string.Printf ("run_one_line (%s, 'lldb.target = None')", m_dictionary_name.c_str());
294 PyRun_SimpleString (run_string.GetData());
295 run_string.Clear();
296
297 if (exe_ctx.process)
298 run_string.Printf ("run_one_line (%s, 'lldb.process = lldb.target.GetProcess()')", m_dictionary_name.c_str());
299 else
300 run_string.Printf ("run_one_line (%s, 'lldb.process = None')", m_dictionary_name.c_str());
301 PyRun_SimpleString (run_string.GetData());
302 run_string.Clear();
303
304 if (exe_ctx.thread)
305 run_string.Printf ("run_one_line (%s, 'lldb.thread = lldb.process.GetSelectedThread ()')",
306 m_dictionary_name.c_str());
307 else
308 run_string.Printf ("run_one_line (%s, 'lldb.thread = None')", m_dictionary_name.c_str());
309 PyRun_SimpleString (run_string.GetData());
310 run_string.Clear();
311
312 if (exe_ctx.frame)
313 run_string.Printf ("run_one_line (%s, 'lldb.frame = lldb.thread.GetSelectedFrame ()')",
314 m_dictionary_name.c_str());
315 else
316 run_string.Printf ("run_one_line (%s, 'lldb.frame = None')", m_dictionary_name.c_str());
317 PyRun_SimpleString (run_string.GetData());
318 run_string.Clear();
319
Caroline Tice0aa2e552011-01-14 00:29:16 +0000320 PyObject *sysmod = PyImport_AddModule ("sys");
321 PyObject *sysdict = PyModule_GetDict (sysmod);
322
323 if ((m_new_sysout != NULL)
324 && (sysmod != NULL)
325 && (sysdict != NULL))
326 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
327
328 if (PyErr_Occurred())
329 PyErr_Clear ();
330
Caroline Tice0aa2e552011-01-14 00:29:16 +0000331 if (!m_pty_slave_is_open)
332 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000333 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000334 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
335 m_pty_slave_name.c_str());
336 PyRun_SimpleString (run_string.GetData());
337 m_pty_slave_is_open = true;
338
339 run_string.Clear();
340 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
341 PyRun_SimpleString (run_string.GetData());
342 }
343}
344
345
Johnny Chen60dde642010-07-30 22:33:14 +0000346bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000347ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000348{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000349 if (!m_valid_session)
350 return false;
351
Caroline Tice0aa2e552011-01-14 00:29:16 +0000352
Caroline Tice0aa2e552011-01-14 00:29:16 +0000353
Caroline Tice4a461da2011-01-14 21:09:29 +0000354 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
355 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
356 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
357 // method to pass the command string directly down to Python.
358
359
Caroline Tice202f6b82011-01-17 21:55:19 +0000360 bool need_to_release_lock = true;
361
362 if (CurrentThreadHasPythonLock())
363 need_to_release_lock = false;
364 else if (!GetPythonLock (1))
365 {
366 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
367 "Python interpreter is currently locked by another thread; unable to process command.\n");
368 return false;
369 }
370
371 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000372 bool success = false;
373
Greg Clayton63094e02010-06-23 01:19:29 +0000374 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000375 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000376 // Find the correct script interpreter dictionary in the main module.
377 PyObject *main_mod = PyImport_AddModule ("__main__");
378 PyObject *script_interpreter_dict = NULL;
379 if (main_mod != NULL)
380 {
381 PyObject *main_dict = PyModule_GetDict (main_mod);
382 if ((main_dict != NULL)
383 && PyDict_Check (main_dict))
384 {
385 // Go through the main dictionary looking for the correct python script interpreter dictionary
386 PyObject *key, *value;
387 Py_ssize_t pos = 0;
388
389 while (PyDict_Next (main_dict, &pos, &key, &value))
390 {
391 // We have stolen references to the key and value objects in the dictionary; we need to increment
392 // them now so that Python's garbage collector doesn't collect them out from under us.
393 Py_INCREF (key);
394 Py_INCREF (value);
395 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
396 {
397 script_interpreter_dict = value;
398 break;
399 }
400 }
401 }
402
403 if (script_interpreter_dict != NULL)
404 {
405 PyObject *pfunc = NULL;
406 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
407 if (pmod != NULL)
408 {
409 PyObject *pmod_dict = PyModule_GetDict (pmod);
410 if ((pmod_dict != NULL)
411 && PyDict_Check (pmod_dict))
412 {
413 PyObject *key, *value;
414 Py_ssize_t pos = 0;
415
416 while (PyDict_Next (pmod_dict, &pos, &key, &value))
417 {
418 Py_INCREF (key);
419 Py_INCREF (value);
420 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
421 {
422 pfunc = value;
423 break;
424 }
425 }
426
427 PyObject *string_arg = PyString_FromString (command);
428 if (pfunc && string_arg && PyCallable_Check (pfunc))
429 {
430 PyObject *pargs = PyTuple_New (2);
431 if (pargs != NULL)
432 {
433 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
434 PyTuple_SetItem (pargs, 1, string_arg);
435 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
436 Py_DECREF (pargs);
437 if (pvalue != NULL)
438 {
439 Py_DECREF (pvalue);
440 success = true;
441 }
442 else if (PyErr_Occurred ())
443 {
444 PyErr_Print();
445 PyErr_Clear();
446 }
447 }
448 }
449 }
450 }
451 Py_INCREF (script_interpreter_dict);
452 }
453 }
Greg Clayton63094e02010-06-23 01:19:29 +0000454
Caroline Tice0aa2e552011-01-14 00:29:16 +0000455 LeaveSession ();
456
Caroline Tice202f6b82011-01-17 21:55:19 +0000457 if (need_to_release_lock)
458 ReleasePythonLock();
459
Caroline Tice4a461da2011-01-14 21:09:29 +0000460 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000461 return true;
462
463 // The one-liner failed. Append the error message.
464 if (result)
465 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
466 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000467 }
Johnny Chen60dde642010-07-30 22:33:14 +0000468
Caroline Tice0aa2e552011-01-14 00:29:16 +0000469 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000470
471 if (need_to_release_lock)
472 ReleasePythonLock ();
473
Johnny Chen60dde642010-07-30 22:33:14 +0000474 if (result)
475 result->AppendError ("empty command passed to python\n");
476 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000477}
478
479
480
481size_t
482ScriptInterpreterPython::InputReaderCallback
483(
484 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000485 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000486 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000487 const char *bytes,
488 size_t bytes_len
489)
490{
Caroline Tice2ade6112010-11-10 19:18:14 +0000491 lldb::thread_t embedded_interpreter_thread;
492 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
493
Chris Lattner24943d22010-06-08 16:52:24 +0000494 if (baton == NULL)
495 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000496
497 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
498
499 if (script_interpreter->m_script_lang != eScriptLanguagePython)
500 return 0;
501
Greg Clayton58928562011-02-09 01:08:52 +0000502 File &out_file = reader.GetDebugger().GetOutputFile();
Caroline Tice67637d82010-12-15 19:51:12 +0000503
Chris Lattner24943d22010-06-08 16:52:24 +0000504 switch (notification)
505 {
506 case eInputReaderActivate:
507 {
Greg Clayton58928562011-02-09 01:08:52 +0000508 out_file.Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
509
Chris Lattner24943d22010-06-08 16:52:24 +0000510 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000511 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
512 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000513 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000514
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000515 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000516
Caroline Tice202f6b82011-01-17 21:55:19 +0000517 if (!CurrentThreadHasPythonLock())
518 {
519 while (!GetPythonLock(1))
520 {
Greg Clayton58928562011-02-09 01:08:52 +0000521 out_file.Printf ("Python interpreter locked on another thread; waiting to acquire lock...\n");
Caroline Tice202f6b82011-01-17 21:55:19 +0000522 }
523 script_interpreter->EnterSession ();
524 ReleasePythonLock();
525 }
526 else
527 script_interpreter->EnterSession ();
528
Caroline Tice2ade6112010-11-10 19:18:14 +0000529 char error_str[1024];
530 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
531 sizeof(error_str)))
532 {
533 if (log)
534 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
535 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
536 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
537 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
538 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000539 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000540 {
541 if (log)
542 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
543 Error detach_error;
544 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
545 }
546 else
547 {
548 if (log)
549 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
550 reader.SetIsDone (true);
551 }
552 }
553 else
554 {
555 if (log)
556 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
557 reader.SetIsDone (true);
558 }
Chris Lattner24943d22010-06-08 16:52:24 +0000559 }
560 break;
561
562 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000563 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000564 break;
565
566 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000567 if (!CurrentThreadHasPythonLock())
568 {
569 while (!GetPythonLock(1))
570 {
571 // Wait until lock is acquired.
572 }
573 script_interpreter->EnterSession ();
574 ReleasePythonLock();
575 }
576 else
577 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000578 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000579
Caroline Tice4a348082011-05-02 20:41:46 +0000580 case eInputReaderAsynchronousOutputWritten:
581 break;
582
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000583 case eInputReaderInterrupt:
584 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
585 break;
586
587 case eInputReaderEndOfFile:
588 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
589 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000590
591 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000592 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000593 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000594 if (log)
595 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
596 bytes_len);
597 if (bytes && bytes_len)
598 {
599 if ((int) bytes[0] == 4)
600 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
601 else
602 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
603 }
604 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000605 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000606 else
607 {
608 if (log)
609 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
610 bytes,
611 bytes_len);
612 reader.SetIsDone (true);
613 }
614
Chris Lattner24943d22010-06-08 16:52:24 +0000615 break;
616
617 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000618 script_interpreter->LeaveSession ();
619
Chris Lattner24943d22010-06-08 16:52:24 +0000620 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000621 if (log)
622 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000623
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000624 script_interpreter->RestoreTerminalState ();
625
Caroline Tice2ade6112010-11-10 19:18:14 +0000626 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000627 break;
628 }
629
630 return bytes_len;
631}
632
633
634void
Greg Clayton238c0a12010-09-18 01:14:36 +0000635ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000636{
637 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
638
Caroline Tice0aa2e552011-01-14 00:29:16 +0000639 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000640
641 // At the moment, the only time the debugger does not have an input file handle is when this is called
642 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
643 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
644 // do it.
645
Greg Clayton58928562011-02-09 01:08:52 +0000646 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000647 return;
648
Greg Clayton63094e02010-06-23 01:19:29 +0000649 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000650 if (reader_sp)
651 {
652 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
653 this, // baton
654 eInputReaderGranularityLine, // token size, to pass to callback function
655 NULL, // end token
656 NULL, // prompt
657 true)); // echo input
658
659 if (error.Success())
660 {
Greg Clayton63094e02010-06-23 01:19:29 +0000661 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000662 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000663 }
664 }
665}
666
667bool
668ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
669 ScriptInterpreter::ReturnType return_type,
670 void *ret_value)
671{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000672
Caroline Tice202f6b82011-01-17 21:55:19 +0000673 bool need_to_release_lock = true;
674
675 if (CurrentThreadHasPythonLock())
676 need_to_release_lock = false;
677 else if (!GetPythonLock (1))
678 {
679 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
680 "Python interpreter is currently locked by another thread; unable to process command.\n");
681 return false;
682 }
683
684 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000685
Chris Lattner24943d22010-06-08 16:52:24 +0000686 PyObject *py_return = NULL;
687 PyObject *mainmod = PyImport_AddModule ("__main__");
688 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000689 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000690 PyObject *py_error = NULL;
691 bool ret_success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000692 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000693 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000694
695 if (PyDict_Check (globals))
696 {
697 PyObject *key, *value;
698 Py_ssize_t pos = 0;
699
700 int i = 0;
701 while (PyDict_Next (globals, &pos, &key, &value))
702 {
703 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
704 // so that Python's garbage collector doesn't collect them out from under us.
705 Py_INCREF (key);
706 Py_INCREF (value);
707 char *c_str = PyString_AsString (key);
708 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
709 locals = value;
710 ++i;
711 }
712 }
Chris Lattner24943d22010-06-08 16:52:24 +0000713
Caroline Tice0aa2e552011-01-14 00:29:16 +0000714 if (locals == NULL)
715 {
716 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
717 should_decrement_locals = true;
718 }
719
720 if (locals == NULL)
721 {
722 locals = globals;
723 should_decrement_locals = false;
724 }
725
726 py_error = PyErr_Occurred();
727 if (py_error != NULL)
728 PyErr_Clear();
729
Chris Lattner24943d22010-06-08 16:52:24 +0000730 if (in_string != NULL)
731 {
732 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
733 if (py_return == NULL)
734 {
735 py_error = PyErr_Occurred ();
736 if (py_error != NULL)
737 PyErr_Clear ();
738
739 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
740 }
741
Caroline Tice0aa2e552011-01-14 00:29:16 +0000742 if (locals != NULL
743 && should_decrement_locals)
744 Py_DECREF (locals);
745
Chris Lattner24943d22010-06-08 16:52:24 +0000746 if (py_return != NULL)
747 {
748 switch (return_type)
749 {
750 case eCharPtr: // "char *"
751 {
752 const char format[3] = "s#";
753 success = PyArg_Parse (py_return, format, (char **) &ret_value);
754 break;
755 }
756 case eBool:
757 {
758 const char format[2] = "b";
759 success = PyArg_Parse (py_return, format, (bool *) ret_value);
760 break;
761 }
762 case eShortInt:
763 {
764 const char format[2] = "h";
765 success = PyArg_Parse (py_return, format, (short *) ret_value);
766 break;
767 }
768 case eShortIntUnsigned:
769 {
770 const char format[2] = "H";
771 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
772 break;
773 }
774 case eInt:
775 {
776 const char format[2] = "i";
777 success = PyArg_Parse (py_return, format, (int *) ret_value);
778 break;
779 }
780 case eIntUnsigned:
781 {
782 const char format[2] = "I";
783 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
784 break;
785 }
786 case eLongInt:
787 {
788 const char format[2] = "l";
789 success = PyArg_Parse (py_return, format, (long *) ret_value);
790 break;
791 }
792 case eLongIntUnsigned:
793 {
794 const char format[2] = "k";
795 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
796 break;
797 }
798 case eLongLong:
799 {
800 const char format[2] = "L";
801 success = PyArg_Parse (py_return, format, (long long *) ret_value);
802 break;
803 }
804 case eLongLongUnsigned:
805 {
806 const char format[2] = "K";
807 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
808 break;
809 }
810 case eFloat:
811 {
812 const char format[2] = "f";
813 success = PyArg_Parse (py_return, format, (float *) ret_value);
814 break;
815 }
816 case eDouble:
817 {
818 const char format[2] = "d";
819 success = PyArg_Parse (py_return, format, (double *) ret_value);
820 break;
821 }
822 case eChar:
823 {
824 const char format[2] = "c";
825 success = PyArg_Parse (py_return, format, (char *) ret_value);
826 break;
827 }
828 default:
829 {}
830 }
831 Py_DECREF (py_return);
832 if (success)
833 ret_success = true;
834 else
835 ret_success = false;
836 }
837 }
838
839 py_error = PyErr_Occurred();
840 if (py_error != NULL)
841 {
842 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
843 PyErr_Print ();
844 PyErr_Clear();
845 ret_success = false;
846 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000847
848 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000849
Caroline Tice202f6b82011-01-17 21:55:19 +0000850 if (need_to_release_lock)
851 ReleasePythonLock();
852
Chris Lattner24943d22010-06-08 16:52:24 +0000853 return ret_success;
854}
855
856bool
857ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
858{
Caroline Tice202f6b82011-01-17 21:55:19 +0000859 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
860 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000861
Caroline Tice202f6b82011-01-17 21:55:19 +0000862 if (CurrentThreadHasPythonLock())
863 need_to_release_lock = false;
864 else
865 {
866 while (!GetPythonLock (1))
867 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
868 }
869
870 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000871
Chris Lattner24943d22010-06-08 16:52:24 +0000872 bool success = false;
873 PyObject *py_return = NULL;
874 PyObject *mainmod = PyImport_AddModule ("__main__");
875 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000876 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000877 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000878 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000879
Caroline Tice0aa2e552011-01-14 00:29:16 +0000880 if (PyDict_Check (globals))
881 {
882 PyObject *key, *value;
883 Py_ssize_t pos = 0;
884
885 while (PyDict_Next (globals, &pos, &key, &value))
886 {
887 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
888 // so that Python's garbage collector doesn't collect them out from under us.
889 Py_INCREF (key);
890 Py_INCREF (value);
891 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
892 locals = value;
893 }
894 }
895
896 if (locals == NULL)
897 {
898 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
899 should_decrement_locals = true;
900 }
901
902 if (locals == NULL)
903 {
904 locals = globals;
905 should_decrement_locals = false;
906 }
907
908 py_error = PyErr_Occurred();
909 if (py_error != NULL)
910 PyErr_Clear();
911
Chris Lattner24943d22010-06-08 16:52:24 +0000912 if (in_string != NULL)
913 {
914 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
915 if (compiled_node)
916 {
917 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
918 if (compiled_code)
919 {
920 py_return = PyEval_EvalCode (compiled_code, globals, locals);
921 if (py_return != NULL)
922 {
923 success = true;
924 Py_DECREF (py_return);
925 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000926 if (locals && should_decrement_locals)
927 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000928 }
929 }
930 }
931
932 py_error = PyErr_Occurred ();
933 if (py_error != NULL)
934 {
935 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
936 PyErr_Print ();
937 PyErr_Clear();
938 success = false;
939 }
940
Caroline Tice0aa2e552011-01-14 00:29:16 +0000941 LeaveSession ();
942
Caroline Tice202f6b82011-01-17 21:55:19 +0000943 if (need_to_release_lock)
944 ReleasePythonLock();
945
Chris Lattner24943d22010-06-08 16:52:24 +0000946 return success;
947}
948
949static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
950
951size_t
952ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
953(
954 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000955 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000956 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000957 const char *bytes,
958 size_t bytes_len
959)
960{
961 static StringList commands_in_progress;
962
Greg Clayton58928562011-02-09 01:08:52 +0000963 File &out_file = reader.GetDebugger().GetOutputFile();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000964
Chris Lattner24943d22010-06-08 16:52:24 +0000965 switch (notification)
966 {
967 case eInputReaderActivate:
968 {
969 commands_in_progress.Clear();
Greg Clayton58928562011-02-09 01:08:52 +0000970 if (out_file.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +0000971 {
Greg Clayton58928562011-02-09 01:08:52 +0000972 out_file.Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000973 if (reader.GetPrompt())
Greg Clayton58928562011-02-09 01:08:52 +0000974 out_file.Printf ("%s", reader.GetPrompt());
975 out_file.Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +0000976 }
977 }
978 break;
979
980 case eInputReaderDeactivate:
981 break;
982
983 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +0000984 if (reader.GetPrompt() && out_file.IsValid())
Caroline Ticef81b4c52010-10-27 18:34:42 +0000985 {
Greg Clayton58928562011-02-09 01:08:52 +0000986 out_file.Printf ("%s", reader.GetPrompt());
987 out_file.Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +0000988 }
Chris Lattner24943d22010-06-08 16:52:24 +0000989 break;
990
Caroline Tice4a348082011-05-02 20:41:46 +0000991 case eInputReaderAsynchronousOutputWritten:
992 break;
993
Chris Lattner24943d22010-06-08 16:52:24 +0000994 case eInputReaderGotToken:
995 {
996 std::string temp_string (bytes, bytes_len);
997 commands_in_progress.AppendString (temp_string.c_str());
Greg Clayton58928562011-02-09 01:08:52 +0000998 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Caroline Ticef81b4c52010-10-27 18:34:42 +0000999 {
Greg Clayton58928562011-02-09 01:08:52 +00001000 out_file.Printf ("%s", reader.GetPrompt());
1001 out_file.Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001002 }
Chris Lattner24943d22010-06-08 16:52:24 +00001003 }
1004 break;
1005
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001006 case eInputReaderEndOfFile:
1007 case eInputReaderInterrupt:
1008 // Control-c (SIGINT) & control-d both mean finish & exit.
1009 reader.SetIsDone(true);
1010
1011 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1012 if (notification == eInputReaderInterrupt)
1013 commands_in_progress.Clear();
1014
1015 // Fall through here...
1016
Chris Lattner24943d22010-06-08 16:52:24 +00001017 case eInputReaderDone:
1018 {
1019 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1020 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1021 data_ap->user_source.AppendList (commands_in_progress);
1022 if (data_ap.get())
1023 {
Greg Clayton63094e02010-06-23 01:19:29 +00001024 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001025 if (interpreter)
1026 {
1027 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1028 data_ap->script_source))
1029 {
1030 if (data_ap->script_source.GetSize() == 1)
1031 {
1032 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1033 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1034 }
1035 }
Caroline Ticeb447e842010-09-21 19:25:28 +00001036 else
Greg Clayton58928562011-02-09 01:08:52 +00001037 out_file.Printf ("Warning: No command attached to breakpoint.\n");
Chris Lattner24943d22010-06-08 16:52:24 +00001038 }
1039 else
1040 {
1041 // FIXME: Error processing.
1042 }
1043 }
1044 }
1045 break;
1046
1047 }
1048
1049 return bytes_len;
1050}
1051
1052void
Greg Clayton238c0a12010-09-18 01:14:36 +00001053ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001054 CommandReturnObject &result)
1055{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001056 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1057
Greg Clayton63094e02010-06-23 01:19:29 +00001058 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001059
1060 if (reader_sp)
1061 {
1062 Error err = reader_sp->Initialize (
1063 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1064 bp_options, // baton
1065 eInputReaderGranularityLine, // token size, for feeding data to callback function
1066 "DONE", // end token
1067 "> ", // prompt
1068 true); // echo input
1069
1070 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001071 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001072 else
1073 {
1074 result.AppendError (err.AsCString());
1075 result.SetStatus (eReturnStatusFailed);
1076 }
1077 }
1078 else
1079 {
1080 result.AppendError("out of memory");
1081 result.SetStatus (eReturnStatusFailed);
1082 }
1083}
1084
Johnny Chen3e0571b2010-09-11 00:23:59 +00001085// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001086void
Greg Clayton238c0a12010-09-18 01:14:36 +00001087ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001088 const char *oneliner)
1089{
1090 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1091
1092 // It's necessary to set both user_source and script_source to the oneliner.
1093 // The former is used to generate callback description (as in breakpoint command list)
1094 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001095
Johnny Chend1c2dca2010-09-10 18:21:10 +00001096 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001097
Caroline Tice5136f942010-09-27 21:35:15 +00001098 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1099 {
1100 if (data_ap->script_source.GetSize() == 1)
1101 {
1102 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1103 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1104 }
1105 }
1106
Johnny Chend1c2dca2010-09-10 18:21:10 +00001107 return;
1108}
1109
Chris Lattner24943d22010-06-08 16:52:24 +00001110bool
1111ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1112{
1113 // Convert StringList to one long, newline delimited, const char *.
1114 std::string function_def_string;
1115
1116 int num_lines = function_def.GetSize();
1117
1118 for (int i = 0; i < num_lines; ++i)
1119 {
1120 function_def_string.append (function_def.GetStringAtIndex(i));
1121 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1122 function_def_string.append ("\n");
1123
1124 }
1125
1126 return ExecuteMultipleLines (function_def_string.c_str());
1127}
1128
1129bool
1130ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1131{
1132 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001133 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001134 int num_lines = user_input.GetSize ();
1135 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001136
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001137 // Check to see if we have any data; if not, just return.
1138 if (user_input.GetSize() == 0)
1139 return false;
1140
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001141 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1142 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001143
Caroline Ticeb447e842010-09-21 19:25:28 +00001144
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001145 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1146 ++num_created_functions;
1147 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001148
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001149 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001150 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001151
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001152 // Create the function name & definition string.
1153
Caroline Tice0aa2e552011-01-14 00:29:16 +00001154 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001155 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001156
1157 // Pre-pend code for setting up the session dictionary.
1158
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.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001164
1165 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001166
1167 for (int i = 0; i < num_lines; ++i)
1168 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001169 sstr.Clear ();
1170 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1171 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001172 }
Chris Lattner24943d22010-06-08 16:52:24 +00001173
Caroline Tice0aa2e552011-01-14 00:29:16 +00001174 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1175 // got written to the values in the global dictionary, not the session dictionary).
1176
1177 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1178 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1179 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1180 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1181
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001182 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001183
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001184 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001185 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001186 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001187 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001188
1189 // Store the name of the auto-generated function to be called.
1190
1191 callback_data.AppendString (auto_generated_function_name.c_str());
1192 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001193}
1194
Greg Clayton5144f382010-10-07 17:14:24 +00001195bool
1196ScriptInterpreterPython::BreakpointCallbackFunction
1197(
1198 void *baton,
1199 StoppointCallbackContext *context,
1200 user_id_t break_id,
1201 user_id_t break_loc_id
1202)
1203{
1204 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1205 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001206
1207 if (!context)
1208 return true;
1209
1210 Target *target = context->exe_ctx.target;
1211
1212 if (!target)
1213 return true;
1214
1215 Debugger &debugger = target->GetDebugger();
1216 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1217 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1218
1219 if (!script_interpreter)
1220 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001221
1222 if (python_function_name != NULL
1223 && python_function_name[0] != '\0')
1224 {
1225 Thread *thread = context->exe_ctx.thread;
Greg Claytone86cbb92011-03-22 01:14:58 +00001226 const StackFrameSP stop_frame_sp (thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame));
Greg Clayton5144f382010-10-07 17:14:24 +00001227 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001228 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001229 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001230 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1231
1232 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001233 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001234 bool ret_val = true;
1235 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1236 if (CurrentThreadHasPythonLock())
1237 {
1238 python_interpreter->EnterSession ();
1239 ret_val = g_swig_breakpoint_callback (python_function_name,
1240 python_interpreter->m_dictionary_name.c_str(),
1241 stop_frame_sp,
1242 bp_loc_sp);
1243 python_interpreter->LeaveSession ();
1244 }
1245 else
1246 {
1247 while (!GetPythonLock (1))
1248 fprintf (tmp_fh,
1249 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1250 python_interpreter->EnterSession ();
1251 ret_val = g_swig_breakpoint_callback (python_function_name,
1252 python_interpreter->m_dictionary_name.c_str(),
1253 stop_frame_sp,
1254 bp_loc_sp);
1255 python_interpreter->LeaveSession ();
1256 ReleasePythonLock ();
1257 }
1258 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001259 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001260 }
Greg Clayton5144f382010-10-07 17:14:24 +00001261 }
1262 // We currently always true so we stop in case anything goes wrong when
1263 // trying to call the script function
1264 return true;
1265}
Caroline Tice2ade6112010-11-10 19:18:14 +00001266
1267lldb::thread_result_t
1268ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1269{
1270 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1271
1272 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1273
1274 if (log)
1275 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1276
1277 char error_str[1024];
1278 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001279 bool need_to_release_lock = true;
1280 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001281
Caroline Tice202f6b82011-01-17 21:55:19 +00001282 if (CurrentThreadHasPythonLock())
1283 {
1284 safe_to_run = true;
1285 need_to_release_lock = false;
1286 }
1287 else
1288 {
1289 int interval = 1;
1290 safe_to_run = GetPythonLock (interval);
1291 while (!safe_to_run)
1292 {
1293 interval = interval * 2;
1294 safe_to_run = GetPythonLock (interval);
1295 }
1296 }
1297
1298 if (pty_slave_name != NULL && safe_to_run)
1299 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001300 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001301
Caroline Tice202f6b82011-01-17 21:55:19 +00001302 script_interpreter->EnterSession ();
1303
Caroline Tice0aa2e552011-01-14 00:29:16 +00001304 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1305 PyRun_SimpleString (run_string.GetData());
1306 run_string.Clear ();
1307
1308 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1309 PyRun_SimpleString (run_string.GetData());
1310 run_string.Clear ();
1311
1312 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1313 PyRun_SimpleString (run_string.GetData());
1314 run_string.Clear ();
1315
1316 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1317 pty_slave_name);
1318 PyRun_SimpleString (run_string.GetData());
1319 run_string.Clear ();
1320
Johnny Chen8054ba32011-03-11 00:28:50 +00001321 // The following call drops into the embedded interpreter loop and stays there until the
1322 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001323
Caroline Ticece207c12011-03-11 00:21:55 +00001324 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001325 // 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 +00001326 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1327
1328 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1329 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1330 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1331 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1332 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1333 // hang (it's happened before).
1334
Caroline Tice9d352ce2011-03-07 23:24:28 +00001335 Py_BEGIN_ALLOW_THREADS
1336 PyGILState_STATE gstate = PyGILState_Ensure();
1337
Caroline Tice0aa2e552011-01-14 00:29:16 +00001338 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1339 PyRun_SimpleString (run_string.GetData());
1340 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001341
Caroline Tice9d352ce2011-03-07 23:24:28 +00001342 PyGILState_Release (gstate);
1343 Py_END_ALLOW_THREADS
1344
Caroline Tice0aa2e552011-01-14 00:29:16 +00001345 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1346 PyRun_SimpleString (run_string.GetData());
1347 run_string.Clear();
1348
1349 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1350 PyRun_SimpleString (run_string.GetData());
1351 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001352
1353 script_interpreter->LeaveSession ();
1354
Caroline Tice2ade6112010-11-10 19:18:14 +00001355 }
1356
Caroline Tice202f6b82011-01-17 21:55:19 +00001357 if (!safe_to_run)
1358 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1359 "Python interpreter locked on another thread; unable to acquire lock.\n");
1360
1361 if (need_to_release_lock)
1362 ReleasePythonLock ();
1363
Caroline Tice2ade6112010-11-10 19:18:14 +00001364 if (script_interpreter->m_embedded_thread_input_reader_sp)
1365 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1366
1367 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001368
1369 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001370
1371 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1372 if (log)
1373 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1374
1375
Johnny Chen8054ba32011-03-11 00:28:50 +00001376 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001377 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001378 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1379 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1380 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001381
Caroline Tice2ade6112010-11-10 19:18:14 +00001382 return NULL;
1383}
1384
1385
Caroline Tice0aa2e552011-01-14 00:29:16 +00001386void
Greg Claytone86cbb92011-03-22 01:14:58 +00001387ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
1388 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback)
1389{
1390 g_swig_init_callback = python_swig_init_callback;
1391 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1392}
1393
1394void
1395ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001396{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001397 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1398
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001399 // Python will muck with STDIN terminal state, so save off any current TTY
1400 // settings so we can restore them.
1401 TerminalState stdin_tty_state;
1402 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001403
1404 // Find the module that owns this code and use that path we get to
1405 // set the PYTHONPATH appropriately.
1406
1407 FileSpec file_spec;
1408 char python_dir_path[PATH_MAX];
1409 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1410 {
1411 std::string python_path;
1412 const char *curr_python_path = ::getenv ("PYTHONPATH");
1413 if (curr_python_path)
1414 {
1415 // We have a current value for PYTHONPATH, so lets append to it
1416 python_path.append (curr_python_path);
1417 }
1418
1419 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1420 {
1421 if (!python_path.empty())
1422 python_path.append (1, ':');
1423 python_path.append (python_dir_path);
1424 }
1425
1426 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1427 {
1428 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1429 {
1430 if (!python_path.empty())
1431 python_path.append (1, ':');
1432 python_path.append (python_dir_path);
1433 }
1434 }
1435 const char *pathon_path_env_cstr = python_path.c_str();
1436 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
1437 }
1438
Caroline Tice9d352ce2011-03-07 23:24:28 +00001439 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001440 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001441
Greg Claytone86cbb92011-03-22 01:14:58 +00001442 // Initialize SWIG after setting up python
1443 assert (g_swig_init_callback != NULL);
1444 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001445
1446 // Update the path python uses to search for modules to include the current directory.
1447
Caroline Ticed4d92832011-06-13 21:33:00 +00001448 PyRun_SimpleString ("import sys");
1449 PyRun_SimpleString ("sys.path.append ('.')");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001450
Caroline Ticed4d92832011-06-13 21:33:00 +00001451 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001452
Caroline Ticed4d92832011-06-13 21:33:00 +00001453 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1454 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
1455 PyRun_SimpleString ("import sys");
1456 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001457
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001458 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001459}
1460
Greg Claytone86cbb92011-03-22 01:14:58 +00001461//void
1462//ScriptInterpreterPython::Terminate ()
1463//{
1464// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1465// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1466// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1467// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1468// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1469// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1470// // within Py_Finalize, which results in a seg fault.
1471// //
1472// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1473// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1474// // process exits).
1475// //
1476//// Py_Finalize ();
1477//}