blob: 9411e433e2476426bdd79436d32c8ded63903df1 [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
11// the *FIRST* header file included:
12
Caroline Tice5790e062010-10-28 21:51:20 +000013#if defined (__APPLE__)
14#include <Python/Python.h>
15#else
Chris Lattner24943d22010-06-08 16:52:24 +000016#include <Python.h>
Caroline Tice5790e062010-10-28 21:51:20 +000017#endif
Chris Lattner24943d22010-06-08 16:52:24 +000018
19#include "lldb/Interpreter/ScriptInterpreterPython.h"
20
21
22#include <sys/ioctl.h>
23#include <termios.h>
24#include <stdlib.h>
25#include <stdio.h>
26
27#include <string>
28
Greg Clayton5144f382010-10-07 17:14:24 +000029#include "lldb/API/SBFrame.h"
30#include "lldb/API/SBBreakpointLocation.h"
Chris Lattner24943d22010-06-08 16:52:24 +000031#include "lldb/Breakpoint/Breakpoint.h"
32#include "lldb/Breakpoint/BreakpointLocation.h"
Greg Clayton63094e02010-06-23 01:19:29 +000033#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner24943d22010-06-08 16:52:24 +000034#include "lldb/Core/Debugger.h"
35#include "lldb/Core/FileSpec.h"
36#include "lldb/Core/InputReader.h"
37#include "lldb/Core/Stream.h"
38#include "lldb/Core/StreamString.h"
39#include "lldb/Core/Timer.h"
40#include "lldb/Host/Host.h"
41#include "lldb/Interpreter/CommandInterpreter.h"
42#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton63094e02010-06-23 01:19:29 +000043#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "lldb/Target/Process.h"
Greg Clayton5144f382010-10-07 17:14:24 +000045#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000046
Greg Clayton121f3312010-07-07 18:40:03 +000047// This function is in the C++ output file generated by SWIG after it is
48// run on all of the headers in "lldb/API/SB*.h"
Chris Lattner24943d22010-06-08 16:52:24 +000049extern "C" void init_lldb (void);
50
Greg Clayton5144f382010-10-07 17:14:24 +000051extern "C" bool
52LLDBSWIGPythonBreakpointCallbackFunction
53(
54 const char *python_function_name,
Caroline Tice0aa2e552011-01-14 00:29:16 +000055 const char *session_dictionary_name,
Greg Clayton5144f382010-10-07 17:14:24 +000056 lldb::SBFrame& sb_frame,
57 lldb::SBBreakpointLocation& sb_bp_loc
58);
59
Chris Lattner24943d22010-06-08 16:52:24 +000060using namespace lldb;
61using namespace lldb_private;
62
63const char embedded_interpreter_string[] =
64"import readline\n\
65import code\n\
66import sys\n\
67import traceback\n\
68\n\
69class SimpleREPL(code.InteractiveConsole):\n\
70 def __init__(self, prompt, dict):\n\
71 code.InteractiveConsole.__init__(self,dict)\n\
72 self.prompt = prompt\n\
73 self.loop_exit = False\n\
74 self.dict = dict\n\
75\n\
76 def interact(self):\n\
77 try:\n\
78 sys.ps1\n\
79 except AttributeError:\n\
80 sys.ps1 = \">>> \"\n\
81 try:\n\
82 sys.ps2\n\
83 except AttributeError:\n\
84 sys.ps2 = \"... \"\n\
85\n\
86 while not self.loop_exit:\n\
87 try:\n\
88 self.read_py_command()\n\
89 except (SystemExit, EOFError):\n\
90 # EOF while in Python just breaks out to top level.\n\
91 self.write('\\n')\n\
92 self.loop_exit = True\n\
93 break\n\
94 except KeyboardInterrupt:\n\
95 self.write(\"\\nKeyboardInterrupt\\n\")\n\
96 self.resetbuffer()\n\
97 more = 0\n\
98 except:\n\
99 traceback.print_exc()\n\
100\n\
101 def process_input (self, in_str):\n\
102 # Canonicalize the format of the input string\n\
103 temp_str = in_str\n\
104 temp_str.strip(' \t')\n\
105 words = temp_str.split()\n\
106 temp_str = ('').join(words)\n\
107\n\
108 # Check the input string to see if it was the quit\n\
109 # command. If so, intercept it, so that it doesn't\n\
110 # close stdin on us!\n\
Jason Molendaa8a5e562010-06-09 21:56:00 +0000111 if (temp_str.lower() == \"quit()\" or temp_str.lower() == \"exit()\"):\n\
Chris Lattner24943d22010-06-08 16:52:24 +0000112 self.loop_exit = True\n\
113 in_str = \"raise SystemExit \"\n\
114 return in_str\n\
115\n\
116 def my_raw_input (self, prompt):\n\
117 stream = sys.stdout\n\
118 stream.write (prompt)\n\
119 stream.flush ()\n\
120 try:\n\
121 line = sys.stdin.readline()\n\
122 except KeyboardInterrupt:\n\
123 line = \" \\n\"\n\
124 except (SystemExit, EOFError):\n\
125 line = \"quit()\\n\"\n\
126 if not line:\n\
127 raise EOFError\n\
128 if line[-1] == '\\n':\n\
129 line = line[:-1]\n\
130 return line\n\
131\n\
132 def read_py_command(self):\n\
133 # Read off a complete Python command.\n\
134 more = 0\n\
135 while 1:\n\
136 if more:\n\
137 prompt = sys.ps2\n\
138 else:\n\
139 prompt = sys.ps1\n\
140 line = self.my_raw_input(prompt)\n\
141 # Can be None if sys.stdin was redefined\n\
142 encoding = getattr(sys.stdin, \"encoding\", None)\n\
143 if encoding and not isinstance(line, unicode):\n\
144 line = line.decode(encoding)\n\
145 line = self.process_input (line)\n\
146 more = self.push(line)\n\
147 if not more:\n\
148 break\n\
149\n\
Caroline Tice0aa2e552011-01-14 00:29:16 +0000150 def one_line (self, input):\n\
151 line = self.process_input (input)\n\
152 more = self.push(line)\n\
153 if more:\n\
154 self.write (\"Input not a complete line.\")\n\
155 self.resetbuffer()\n\
156 more = 0\n\
157\n\
Chris Lattner24943d22010-06-08 16:52:24 +0000158def run_python_interpreter (dict):\n\
159 # Pass in the dictionary, for continuity from one session to the next.\n\
160 repl = SimpleREPL('>>> ', dict)\n\
Caroline Tice0aa2e552011-01-14 00:29:16 +0000161 repl.interact()\n\
162\n\
163def run_one_line (dict, input_string):\n\
164 repl = SimpleREPL ('', dict)\n\
165 repl.one_line (input_string)\n";
Chris Lattner24943d22010-06-08 16:52:24 +0000166
167static int
168_check_and_flush (FILE *stream)
169{
170 int prev_fail = ferror (stream);
171 return fflush (stream) || prev_fail ? EOF : 0;
172}
173
Caroline Tice0aa2e552011-01-14 00:29:16 +0000174static Mutex &
175GetPythonMutex ()
176{
177 static Mutex g_python_mutex (Mutex::eMutexTypeRecursive);
178 return g_python_mutex;
179}
180
Greg Clayton63094e02010-06-23 01:19:29 +0000181ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000182 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000183 m_embedded_python_pty (),
184 m_embedded_thread_input_reader_sp (),
185 m_dbg_stdout (interpreter.GetDebugger().GetOutputFileHandle()),
186 m_new_sysout (NULL),
187 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Caroline Tice2ade6112010-11-10 19:18:14 +0000188 m_termios (),
189 m_termios_valid (false),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000190 m_session_is_active (false),
191 m_pty_slave_is_open (false),
192 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000193{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000194 Mutex::Locker locker (GetPythonMutex());
Chris Lattner24943d22010-06-08 16:52:24 +0000195
Caroline Tice0aa2e552011-01-14 00:29:16 +0000196 m_dictionary_name.append("_dict");
197 StreamString run_string;
198 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
199 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000200
Caroline Tice0aa2e552011-01-14 00:29:16 +0000201 run_string.Clear();
202 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
203 PyRun_SimpleString (run_string.GetData());
204
205 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
206 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
207 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
208 // call to Debugger::Terminate is made, the ref-count has the correct value.
209 //
210 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
211 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000212
Caroline Tice0aa2e552011-01-14 00:29:16 +0000213 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000214
Caroline Tice0aa2e552011-01-14 00:29:16 +0000215 run_string.Clear();
216 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
217 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000218
Caroline Tice0aa2e552011-01-14 00:29:16 +0000219 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000220
Caroline Tice0aa2e552011-01-14 00:29:16 +0000221 if (new_count > old_count)
222 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000223
Caroline Tice0aa2e552011-01-14 00:29:16 +0000224 run_string.Clear();
225 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
226 PyRun_SimpleString (run_string.GetData());
227
228 run_string.Clear();
229 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
230 interpreter.GetDebugger().GetID());
231 PyRun_SimpleString (run_string.GetData());
232
233 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000234 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000235 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000236 }
Chris Lattner24943d22010-06-08 16:52:24 +0000237}
238
239ScriptInterpreterPython::~ScriptInterpreterPython ()
240{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000241 Debugger &debugger = GetCommandInterpreter().GetDebugger();
242
243 if (m_embedded_thread_input_reader_sp.get() != NULL)
244 {
245 m_embedded_thread_input_reader_sp->SetIsDone (true);
246 m_embedded_python_pty.CloseSlaveFileDescriptor();
247 m_pty_slave_is_open = false;
248 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
249 m_embedded_thread_input_reader_sp.reset();
250 debugger.PopInputReader (reader_sp);
251 }
252
253 if (m_new_sysout)
254 {
255 Mutex::Locker locker(GetPythonMutex());
256 Py_DECREF (m_new_sysout);
257 }
Chris Lattner24943d22010-06-08 16:52:24 +0000258}
259
Caroline Tice0aa2e552011-01-14 00:29:16 +0000260void
261ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
262{
263 if (fh == NULL)
264 return;
265
266 m_dbg_stdout = fh;
267 Mutex::Locker locker (GetPythonMutex());
268
269 EnterSession ();
270 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
271 LeaveSession ();
272}
273
274void
275ScriptInterpreterPython::LeaveSession ()
276{
277 m_session_is_active = false;
278}
279
280void
281ScriptInterpreterPython::EnterSession ()
282{
283 // If we have already entered the session, without having officially 'left' it, then there is no need to
284 // 'enter' it again.
285
286 if (m_session_is_active)
287 return;
288
289 m_session_is_active = true;
290
291 Mutex::Locker locker (GetPythonMutex());
292
293 PyObject *sysmod = PyImport_AddModule ("sys");
294 PyObject *sysdict = PyModule_GetDict (sysmod);
295
296 if ((m_new_sysout != NULL)
297 && (sysmod != NULL)
298 && (sysdict != NULL))
299 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
300
301 if (PyErr_Occurred())
302 PyErr_Clear ();
303
304 StreamString run_string;
305 if (!m_pty_slave_is_open)
306 {
307 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
308 m_pty_slave_name.c_str());
309 PyRun_SimpleString (run_string.GetData());
310 m_pty_slave_is_open = true;
311
312 run_string.Clear();
313 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
314 PyRun_SimpleString (run_string.GetData());
315 }
316}
317
318
Johnny Chen60dde642010-07-30 22:33:14 +0000319bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000320ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000321{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000322 if (!m_valid_session)
323 return false;
324
325 EnterSession ();
326
327 Mutex::Locker locker (GetPythonMutex());
328
Caroline Tice4a461da2011-01-14 21:09:29 +0000329 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
330 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
331 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
332 // method to pass the command string directly down to Python.
333
334
335 bool success = false;
336
Greg Clayton63094e02010-06-23 01:19:29 +0000337 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000338 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000339 // Find the correct script interpreter dictionary in the main module.
340 PyObject *main_mod = PyImport_AddModule ("__main__");
341 PyObject *script_interpreter_dict = NULL;
342 if (main_mod != NULL)
343 {
344 PyObject *main_dict = PyModule_GetDict (main_mod);
345 if ((main_dict != NULL)
346 && PyDict_Check (main_dict))
347 {
348 // Go through the main dictionary looking for the correct python script interpreter dictionary
349 PyObject *key, *value;
350 Py_ssize_t pos = 0;
351
352 while (PyDict_Next (main_dict, &pos, &key, &value))
353 {
354 // We have stolen references to the key and value objects in the dictionary; we need to increment
355 // them now so that Python's garbage collector doesn't collect them out from under us.
356 Py_INCREF (key);
357 Py_INCREF (value);
358 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
359 {
360 script_interpreter_dict = value;
361 break;
362 }
363 }
364 }
365
366 if (script_interpreter_dict != NULL)
367 {
368 PyObject *pfunc = NULL;
369 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
370 if (pmod != NULL)
371 {
372 PyObject *pmod_dict = PyModule_GetDict (pmod);
373 if ((pmod_dict != NULL)
374 && PyDict_Check (pmod_dict))
375 {
376 PyObject *key, *value;
377 Py_ssize_t pos = 0;
378
379 while (PyDict_Next (pmod_dict, &pos, &key, &value))
380 {
381 Py_INCREF (key);
382 Py_INCREF (value);
383 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
384 {
385 pfunc = value;
386 break;
387 }
388 }
389
390 PyObject *string_arg = PyString_FromString (command);
391 if (pfunc && string_arg && PyCallable_Check (pfunc))
392 {
393 PyObject *pargs = PyTuple_New (2);
394 if (pargs != NULL)
395 {
396 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
397 PyTuple_SetItem (pargs, 1, string_arg);
398 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
399 Py_DECREF (pargs);
400 if (pvalue != NULL)
401 {
402 Py_DECREF (pvalue);
403 success = true;
404 }
405 else if (PyErr_Occurred ())
406 {
407 PyErr_Print();
408 PyErr_Clear();
409 }
410 }
411 }
412 }
413 }
414 Py_INCREF (script_interpreter_dict);
415 }
416 }
Greg Clayton63094e02010-06-23 01:19:29 +0000417
Caroline Tice0aa2e552011-01-14 00:29:16 +0000418 LeaveSession ();
419
Caroline Tice4a461da2011-01-14 21:09:29 +0000420 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000421 return true;
422
423 // The one-liner failed. Append the error message.
424 if (result)
425 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
426 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000427 }
Johnny Chen60dde642010-07-30 22:33:14 +0000428
Caroline Tice0aa2e552011-01-14 00:29:16 +0000429 LeaveSession ();
Johnny Chen60dde642010-07-30 22:33:14 +0000430 if (result)
431 result->AppendError ("empty command passed to python\n");
432 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000433}
434
435
436
437size_t
438ScriptInterpreterPython::InputReaderCallback
439(
440 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000441 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000442 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000443 const char *bytes,
444 size_t bytes_len
445)
446{
Caroline Tice2ade6112010-11-10 19:18:14 +0000447 lldb::thread_t embedded_interpreter_thread;
448 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
449
Chris Lattner24943d22010-06-08 16:52:24 +0000450 if (baton == NULL)
451 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000452
453 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
454
455 if (script_interpreter->m_script_lang != eScriptLanguagePython)
456 return 0;
457
Caroline Tice67637d82010-12-15 19:51:12 +0000458 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle ();
459 if (out_fh == NULL)
460 out_fh = stdout;
461
Chris Lattner24943d22010-06-08 16:52:24 +0000462 switch (notification)
463 {
464 case eInputReaderActivate:
465 {
Caroline Tice67637d82010-12-15 19:51:12 +0000466 if (out_fh)
467 {
468 ::fprintf (out_fh, "Python Interactive Interpreter. To exit Python, type 'quit()' or 'exit()'.\n");
469 ::fprintf (out_fh, "Do NOT use Ctrl-D (EOF) to exit, as that will cause the lldb debugger to hang.\n");
470 }
Chris Lattner24943d22010-06-08 16:52:24 +0000471 // Save terminal settings if we can
Caroline Ticec95c6d12010-09-14 22:49:06 +0000472 int input_fd;
Greg Clayton63094e02010-06-23 01:19:29 +0000473 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000474 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000475 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000476 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000477 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000478
Greg Clayton63094e02010-06-23 01:19:29 +0000479 script_interpreter->m_termios_valid = ::tcgetattr (input_fd, &script_interpreter->m_termios) == 0;
Greg Clayton24b48ff2010-10-17 22:03:32 +0000480
Caroline Tice2ade6112010-11-10 19:18:14 +0000481 char error_str[1024];
482 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
483 sizeof(error_str)))
484 {
485 if (log)
486 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
487 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
488 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
489 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
490 script_interpreter, NULL);
491 if (embedded_interpreter_thread != LLDB_INVALID_HOST_THREAD)
492 {
493 if (log)
494 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
495 Error detach_error;
496 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
497 }
498 else
499 {
500 if (log)
501 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
502 reader.SetIsDone (true);
503 }
504 }
505 else
506 {
507 if (log)
508 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
509 reader.SetIsDone (true);
510 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000511 script_interpreter->EnterSession ();
Caroline Tice2ade6112010-11-10 19:18:14 +0000512
Chris Lattner24943d22010-06-08 16:52:24 +0000513 }
514 break;
515
516 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000517 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000518 break;
519
520 case eInputReaderReactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000521 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000522 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000523
524 case eInputReaderInterrupt:
525 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
526 break;
527
528 case eInputReaderEndOfFile:
529 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
530 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000531
532 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000533 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000534 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000535 if (log)
536 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
537 bytes_len);
538 if (bytes && bytes_len)
539 {
540 if ((int) bytes[0] == 4)
541 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
542 else
543 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
544 }
545 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000546 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000547 else
548 {
549 if (log)
550 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
551 bytes,
552 bytes_len);
553 reader.SetIsDone (true);
554 }
555
Chris Lattner24943d22010-06-08 16:52:24 +0000556 break;
557
558 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000559 script_interpreter->LeaveSession ();
560
Chris Lattner24943d22010-06-08 16:52:24 +0000561 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000562 if (log)
563 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Greg Clayton63094e02010-06-23 01:19:29 +0000564 if (script_interpreter->m_termios_valid)
Chris Lattner24943d22010-06-08 16:52:24 +0000565 {
Caroline Ticec95c6d12010-09-14 22:49:06 +0000566 int input_fd;
567 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
568 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000569 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000570 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000571 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000572
573 ::tcsetattr (input_fd, TCSANOW, &script_interpreter->m_termios);
Chris Lattner24943d22010-06-08 16:52:24 +0000574 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000575 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000576 break;
577 }
578
579 return bytes_len;
580}
581
582
583void
Greg Clayton238c0a12010-09-18 01:14:36 +0000584ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000585{
586 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
587
Caroline Tice0aa2e552011-01-14 00:29:16 +0000588 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000589
590 // At the moment, the only time the debugger does not have an input file handle is when this is called
591 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
592 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
593 // do it.
594
595 if (debugger.GetInputFileHandle() == NULL)
596 return;
597
Greg Clayton63094e02010-06-23 01:19:29 +0000598 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000599 if (reader_sp)
600 {
601 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
602 this, // baton
603 eInputReaderGranularityLine, // token size, to pass to callback function
604 NULL, // end token
605 NULL, // prompt
606 true)); // echo input
607
608 if (error.Success())
609 {
Greg Clayton63094e02010-06-23 01:19:29 +0000610 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000611 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000612 }
613 }
614}
615
616bool
617ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
618 ScriptInterpreter::ReturnType return_type,
619 void *ret_value)
620{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000621 EnterSession ();
622
623 Mutex::Locker locker (GetPythonMutex());
624
Chris Lattner24943d22010-06-08 16:52:24 +0000625 PyObject *py_return = NULL;
626 PyObject *mainmod = PyImport_AddModule ("__main__");
627 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000628 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000629 PyObject *py_error = NULL;
630 bool ret_success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000631 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000632 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000633
634 if (PyDict_Check (globals))
635 {
636 PyObject *key, *value;
637 Py_ssize_t pos = 0;
638
639 int i = 0;
640 while (PyDict_Next (globals, &pos, &key, &value))
641 {
642 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
643 // so that Python's garbage collector doesn't collect them out from under us.
644 Py_INCREF (key);
645 Py_INCREF (value);
646 char *c_str = PyString_AsString (key);
647 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
648 locals = value;
649 ++i;
650 }
651 }
Chris Lattner24943d22010-06-08 16:52:24 +0000652
Caroline Tice0aa2e552011-01-14 00:29:16 +0000653 if (locals == NULL)
654 {
655 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
656 should_decrement_locals = true;
657 }
658
659 if (locals == NULL)
660 {
661 locals = globals;
662 should_decrement_locals = false;
663 }
664
665 py_error = PyErr_Occurred();
666 if (py_error != NULL)
667 PyErr_Clear();
668
Chris Lattner24943d22010-06-08 16:52:24 +0000669 if (in_string != NULL)
670 {
671 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
672 if (py_return == NULL)
673 {
674 py_error = PyErr_Occurred ();
675 if (py_error != NULL)
676 PyErr_Clear ();
677
678 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
679 }
680
Caroline Tice0aa2e552011-01-14 00:29:16 +0000681 if (locals != NULL
682 && should_decrement_locals)
683 Py_DECREF (locals);
684
Chris Lattner24943d22010-06-08 16:52:24 +0000685 if (py_return != NULL)
686 {
687 switch (return_type)
688 {
689 case eCharPtr: // "char *"
690 {
691 const char format[3] = "s#";
692 success = PyArg_Parse (py_return, format, (char **) &ret_value);
693 break;
694 }
695 case eBool:
696 {
697 const char format[2] = "b";
698 success = PyArg_Parse (py_return, format, (bool *) ret_value);
699 break;
700 }
701 case eShortInt:
702 {
703 const char format[2] = "h";
704 success = PyArg_Parse (py_return, format, (short *) ret_value);
705 break;
706 }
707 case eShortIntUnsigned:
708 {
709 const char format[2] = "H";
710 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
711 break;
712 }
713 case eInt:
714 {
715 const char format[2] = "i";
716 success = PyArg_Parse (py_return, format, (int *) ret_value);
717 break;
718 }
719 case eIntUnsigned:
720 {
721 const char format[2] = "I";
722 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
723 break;
724 }
725 case eLongInt:
726 {
727 const char format[2] = "l";
728 success = PyArg_Parse (py_return, format, (long *) ret_value);
729 break;
730 }
731 case eLongIntUnsigned:
732 {
733 const char format[2] = "k";
734 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
735 break;
736 }
737 case eLongLong:
738 {
739 const char format[2] = "L";
740 success = PyArg_Parse (py_return, format, (long long *) ret_value);
741 break;
742 }
743 case eLongLongUnsigned:
744 {
745 const char format[2] = "K";
746 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
747 break;
748 }
749 case eFloat:
750 {
751 const char format[2] = "f";
752 success = PyArg_Parse (py_return, format, (float *) ret_value);
753 break;
754 }
755 case eDouble:
756 {
757 const char format[2] = "d";
758 success = PyArg_Parse (py_return, format, (double *) ret_value);
759 break;
760 }
761 case eChar:
762 {
763 const char format[2] = "c";
764 success = PyArg_Parse (py_return, format, (char *) ret_value);
765 break;
766 }
767 default:
768 {}
769 }
770 Py_DECREF (py_return);
771 if (success)
772 ret_success = true;
773 else
774 ret_success = false;
775 }
776 }
777
778 py_error = PyErr_Occurred();
779 if (py_error != NULL)
780 {
781 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
782 PyErr_Print ();
783 PyErr_Clear();
784 ret_success = false;
785 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000786
787 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000788
789 return ret_success;
790}
791
792bool
793ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
794{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000795 EnterSession ();
796
797 Mutex::Locker locker (GetPythonMutex());
798
Chris Lattner24943d22010-06-08 16:52:24 +0000799 bool success = false;
800 PyObject *py_return = NULL;
801 PyObject *mainmod = PyImport_AddModule ("__main__");
802 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000803 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000804 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000805 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000806
Caroline Tice0aa2e552011-01-14 00:29:16 +0000807 if (PyDict_Check (globals))
808 {
809 PyObject *key, *value;
810 Py_ssize_t pos = 0;
811
812 while (PyDict_Next (globals, &pos, &key, &value))
813 {
814 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
815 // so that Python's garbage collector doesn't collect them out from under us.
816 Py_INCREF (key);
817 Py_INCREF (value);
818 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
819 locals = value;
820 }
821 }
822
823 if (locals == NULL)
824 {
825 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
826 should_decrement_locals = true;
827 }
828
829 if (locals == NULL)
830 {
831 locals = globals;
832 should_decrement_locals = false;
833 }
834
835 py_error = PyErr_Occurred();
836 if (py_error != NULL)
837 PyErr_Clear();
838
Chris Lattner24943d22010-06-08 16:52:24 +0000839 if (in_string != NULL)
840 {
841 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
842 if (compiled_node)
843 {
844 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
845 if (compiled_code)
846 {
847 py_return = PyEval_EvalCode (compiled_code, globals, locals);
848 if (py_return != NULL)
849 {
850 success = true;
851 Py_DECREF (py_return);
852 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000853 if (locals && should_decrement_locals)
854 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000855 }
856 }
857 }
858
859 py_error = PyErr_Occurred ();
860 if (py_error != NULL)
861 {
862 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
863 PyErr_Print ();
864 PyErr_Clear();
865 success = false;
866 }
867
Caroline Tice0aa2e552011-01-14 00:29:16 +0000868 LeaveSession ();
869
Chris Lattner24943d22010-06-08 16:52:24 +0000870 return success;
871}
872
873static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
874
875size_t
876ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
877(
878 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000879 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000880 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000881 const char *bytes,
882 size_t bytes_len
883)
884{
885 static StringList commands_in_progress;
886
Greg Clayton63094e02010-06-23 01:19:29 +0000887 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000888 if (out_fh == NULL)
889 out_fh = stdout;
890
Chris Lattner24943d22010-06-08 16:52:24 +0000891 switch (notification)
892 {
893 case eInputReaderActivate:
894 {
895 commands_in_progress.Clear();
896 if (out_fh)
897 {
898 ::fprintf (out_fh, "%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000899 if (reader.GetPrompt())
900 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +0000901 ::fflush (out_fh);
Chris Lattner24943d22010-06-08 16:52:24 +0000902 }
903 }
904 break;
905
906 case eInputReaderDeactivate:
907 break;
908
909 case eInputReaderReactivate:
Greg Clayton63094e02010-06-23 01:19:29 +0000910 if (reader.GetPrompt() && out_fh)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000911 {
Greg Clayton63094e02010-06-23 01:19:29 +0000912 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +0000913 ::fflush (out_fh);
914 }
Chris Lattner24943d22010-06-08 16:52:24 +0000915 break;
916
917 case eInputReaderGotToken:
918 {
919 std::string temp_string (bytes, bytes_len);
920 commands_in_progress.AppendString (temp_string.c_str());
Greg Clayton63094e02010-06-23 01:19:29 +0000921 if (out_fh && !reader.IsDone() && reader.GetPrompt())
Caroline Ticef81b4c52010-10-27 18:34:42 +0000922 {
Greg Clayton63094e02010-06-23 01:19:29 +0000923 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +0000924 ::fflush (out_fh);
925 }
Chris Lattner24943d22010-06-08 16:52:24 +0000926 }
927 break;
928
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000929 case eInputReaderEndOfFile:
930 case eInputReaderInterrupt:
931 // Control-c (SIGINT) & control-d both mean finish & exit.
932 reader.SetIsDone(true);
933
934 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
935 if (notification == eInputReaderInterrupt)
936 commands_in_progress.Clear();
937
938 // Fall through here...
939
Chris Lattner24943d22010-06-08 16:52:24 +0000940 case eInputReaderDone:
941 {
942 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
943 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
944 data_ap->user_source.AppendList (commands_in_progress);
945 if (data_ap.get())
946 {
Greg Clayton63094e02010-06-23 01:19:29 +0000947 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +0000948 if (interpreter)
949 {
950 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
951 data_ap->script_source))
952 {
953 if (data_ap->script_source.GetSize() == 1)
954 {
955 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
956 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
957 }
958 }
Caroline Ticeb447e842010-09-21 19:25:28 +0000959 else
Caroline Tice5136f942010-09-27 21:35:15 +0000960 ::fprintf (out_fh, "Warning: No command attached to breakpoint.\n");
Chris Lattner24943d22010-06-08 16:52:24 +0000961 }
962 else
963 {
964 // FIXME: Error processing.
965 }
966 }
967 }
968 break;
969
970 }
971
972 return bytes_len;
973}
974
975void
Greg Clayton238c0a12010-09-18 01:14:36 +0000976ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +0000977 CommandReturnObject &result)
978{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000979 Debugger &debugger = GetCommandInterpreter().GetDebugger();
980
Greg Clayton63094e02010-06-23 01:19:29 +0000981 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000982
983 if (reader_sp)
984 {
985 Error err = reader_sp->Initialize (
986 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
987 bp_options, // baton
988 eInputReaderGranularityLine, // token size, for feeding data to callback function
989 "DONE", // end token
990 "> ", // prompt
991 true); // echo input
992
993 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +0000994 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +0000995 else
996 {
997 result.AppendError (err.AsCString());
998 result.SetStatus (eReturnStatusFailed);
999 }
1000 }
1001 else
1002 {
1003 result.AppendError("out of memory");
1004 result.SetStatus (eReturnStatusFailed);
1005 }
1006}
1007
Johnny Chen3e0571b2010-09-11 00:23:59 +00001008// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001009void
Greg Clayton238c0a12010-09-18 01:14:36 +00001010ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001011 const char *oneliner)
1012{
1013 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1014
1015 // It's necessary to set both user_source and script_source to the oneliner.
1016 // The former is used to generate callback description (as in breakpoint command list)
1017 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001018
Johnny Chend1c2dca2010-09-10 18:21:10 +00001019 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001020
Caroline Tice5136f942010-09-27 21:35:15 +00001021 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1022 {
1023 if (data_ap->script_source.GetSize() == 1)
1024 {
1025 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1026 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1027 }
1028 }
1029
Johnny Chend1c2dca2010-09-10 18:21:10 +00001030 return;
1031}
1032
Chris Lattner24943d22010-06-08 16:52:24 +00001033bool
1034ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1035{
1036 // Convert StringList to one long, newline delimited, const char *.
1037 std::string function_def_string;
1038
1039 int num_lines = function_def.GetSize();
1040
1041 for (int i = 0; i < num_lines; ++i)
1042 {
1043 function_def_string.append (function_def.GetStringAtIndex(i));
1044 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1045 function_def_string.append ("\n");
1046
1047 }
1048
1049 return ExecuteMultipleLines (function_def_string.c_str());
1050}
1051
1052bool
1053ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1054{
1055 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001056 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001057 int num_lines = user_input.GetSize ();
1058 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001059
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001060 // Check to see if we have any data; if not, just return.
1061 if (user_input.GetSize() == 0)
1062 return false;
1063
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001064 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1065 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001066
Caroline Ticeb447e842010-09-21 19:25:28 +00001067
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001068 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1069 ++num_created_functions;
1070 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001071
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001072 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001073 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001074
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001075 // Create the function name & definition string.
1076
Caroline Tice0aa2e552011-01-14 00:29:16 +00001077 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001078 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001079
1080 // Pre-pend code for setting up the session dictionary.
1081
1082 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1083 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1084 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1085 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1086 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001087
1088 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001089
1090 for (int i = 0; i < num_lines; ++i)
1091 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001092 sstr.Clear ();
1093 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1094 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001095 }
Chris Lattner24943d22010-06-08 16:52:24 +00001096
Caroline Tice0aa2e552011-01-14 00:29:16 +00001097 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1098 // got written to the values in the global dictionary, not the session dictionary).
1099
1100 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1101 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1102 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1103 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1104
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001105 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001106
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001107 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001108 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001109 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001110 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001111
1112 // Store the name of the auto-generated function to be called.
1113
1114 callback_data.AppendString (auto_generated_function_name.c_str());
1115 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001116}
1117
Greg Clayton5144f382010-10-07 17:14:24 +00001118bool
1119ScriptInterpreterPython::BreakpointCallbackFunction
1120(
1121 void *baton,
1122 StoppointCallbackContext *context,
1123 user_id_t break_id,
1124 user_id_t break_loc_id
1125)
1126{
1127 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1128 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001129
1130 if (!context)
1131 return true;
1132
1133 Target *target = context->exe_ctx.target;
1134
1135 if (!target)
1136 return true;
1137
1138 Debugger &debugger = target->GetDebugger();
1139 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1140 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1141
1142 if (!script_interpreter)
1143 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001144
1145 if (python_function_name != NULL
1146 && python_function_name[0] != '\0')
1147 {
1148 Thread *thread = context->exe_ctx.thread;
1149 Target *target = context->exe_ctx.target;
1150 const StackFrameSP stop_frame_sp = thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame);
1151 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
1152 const BreakpointLocationSP bp_loc_sp = breakpoint_sp->FindLocationByID (break_loc_id);
1153
1154 SBFrame sb_frame (stop_frame_sp);
1155 SBBreakpointLocation sb_bp_loc (bp_loc_sp);
1156
1157 if (sb_bp_loc.IsValid() || sb_frame.IsValid())
Caroline Tice0aa2e552011-01-14 00:29:16 +00001158 {
1159 python_interpreter->EnterSession ();
1160 Mutex::Locker locker (GetPythonMutex());
1161 bool ret_val = LLDBSWIGPythonBreakpointCallbackFunction(python_function_name,
1162 python_interpreter->m_dictionary_name.c_str(),
1163 sb_frame, sb_bp_loc);
1164 python_interpreter->LeaveSession ();
1165 return ret_val;
1166 }
Greg Clayton5144f382010-10-07 17:14:24 +00001167 }
1168 // We currently always true so we stop in case anything goes wrong when
1169 // trying to call the script function
1170 return true;
1171}
Caroline Tice2ade6112010-11-10 19:18:14 +00001172
1173lldb::thread_result_t
1174ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1175{
1176 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1177
Caroline Tice0aa2e552011-01-14 00:29:16 +00001178 script_interpreter->EnterSession ();
1179
Caroline Tice2ade6112010-11-10 19:18:14 +00001180 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1181
1182 if (log)
1183 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1184
1185 char error_str[1024];
1186 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
1187 if (pty_slave_name != NULL)
1188 {
Caroline Tice0aa2e552011-01-14 00:29:16 +00001189 Mutex::Locker locker (GetPythonMutex());
1190
Caroline Tice2ade6112010-11-10 19:18:14 +00001191 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001192
Caroline Tice0aa2e552011-01-14 00:29:16 +00001193 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1194 PyRun_SimpleString (run_string.GetData());
1195 run_string.Clear ();
1196
1197 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1198 PyRun_SimpleString (run_string.GetData());
1199 run_string.Clear ();
1200
1201 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1202 PyRun_SimpleString (run_string.GetData());
1203 run_string.Clear ();
1204
1205 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1206 pty_slave_name);
1207 PyRun_SimpleString (run_string.GetData());
1208 run_string.Clear ();
1209
Caroline Tice2ade6112010-11-10 19:18:14 +00001210 // The following call drops into the embedded interpreter loop and stays there until the
1211 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001212
1213 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1214 PyRun_SimpleString (run_string.GetData());
1215 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001216
Caroline Tice0aa2e552011-01-14 00:29:16 +00001217 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1218 PyRun_SimpleString (run_string.GetData());
1219 run_string.Clear();
1220
1221 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1222 PyRun_SimpleString (run_string.GetData());
1223 run_string.Clear();
Caroline Tice2ade6112010-11-10 19:18:14 +00001224 }
1225
1226 if (script_interpreter->m_embedded_thread_input_reader_sp)
1227 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1228
1229 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001230
1231 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001232
1233 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1234 if (log)
1235 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1236
1237
Caroline Tice0aa2e552011-01-14 00:29:16 +00001238 // Clean up the input reader and make the debugger pop it off the stack.
1239 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001240 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1241 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1242 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001243
1244 script_interpreter->LeaveSession ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001245
1246 return NULL;
1247}
1248
1249
Caroline Tice0aa2e552011-01-14 00:29:16 +00001250void
1251ScriptInterpreterPython::Initialize ()
1252{
Caroline Tice2ade6112010-11-10 19:18:14 +00001253
Caroline Tice0aa2e552011-01-14 00:29:16 +00001254 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1255
1256 int input_fd = STDIN_FILENO;
1257
1258 struct termios stdin_termios;
1259 bool valid_termios = ::tcgetattr (input_fd, &stdin_termios) == 0;
1260
1261 // Find the module that owns this code and use that path we get to
1262 // set the PYTHONPATH appropriately.
1263
1264 FileSpec file_spec;
1265 char python_dir_path[PATH_MAX];
1266 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1267 {
1268 std::string python_path;
1269 const char *curr_python_path = ::getenv ("PYTHONPATH");
1270 if (curr_python_path)
1271 {
1272 // We have a current value for PYTHONPATH, so lets append to it
1273 python_path.append (curr_python_path);
1274 }
1275
1276 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1277 {
1278 if (!python_path.empty())
1279 python_path.append (1, ':');
1280 python_path.append (python_dir_path);
1281 }
1282
1283 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1284 {
1285 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1286 {
1287 if (!python_path.empty())
1288 python_path.append (1, ':');
1289 python_path.append (python_dir_path);
1290 }
1291 }
1292 const char *pathon_path_env_cstr = python_path.c_str();
1293 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
1294 }
1295
1296 Py_Initialize ();
1297
1298 PyObject *compiled_module = Py_CompileString (embedded_interpreter_string,
1299 "embedded_interpreter.py",
1300 Py_file_input);
1301
1302 PyObject *py_error = PyErr_Occurred ();
1303 if (py_error != NULL)
1304 {
1305 PyErr_Print();
1306 PyErr_Clear();
1307 }
1308
1309
1310 // This function is in the C++ output file generated by SWIG after it is
1311 // run on all of the headers in "lldb/API/SB*.h"
1312 init_lldb ();
1313
1314 // Update the path python uses to search for modules to include the current directory.
1315
1316 int success = PyRun_SimpleString ("import sys");
1317 success = PyRun_SimpleString ("sys.path.append ('.')");
1318
1319 PyObject *pmod = NULL;
1320
1321 if (compiled_module)
1322 {
1323 pmod = PyImport_ExecCodeModule (const_cast<char*> ("embedded_interpreter"),
1324 compiled_module);
1325 Py_DECREF (compiled_module);
1326 }
1327
1328 if (pmod != NULL)
1329 {
1330 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1331 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
1332 PyRun_SimpleString ("import sys");
1333 PyRun_SimpleString ("from termios import *");
1334 Py_DECREF (pmod);
1335 }
1336
1337 if (valid_termios)
1338 ::tcsetattr (input_fd, TCSANOW, &stdin_termios);
1339}
1340
1341void
1342ScriptInterpreterPython::Terminate ()
1343{
1344 // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1345 // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1346 // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1347 // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1348 // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1349 // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1350 // within Py_Finalize, which results in a seg fault.
1351 //
1352 // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1353 // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1354 // process exits).
1355 //
1356// Py_Finalize ();
1357}