blob: 1927531fb8907b0883a9353c20bd0a2225abebd3 [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,
55 lldb::SBFrame& sb_frame,
56 lldb::SBBreakpointLocation& sb_bp_loc
57);
58
Chris Lattner24943d22010-06-08 16:52:24 +000059using namespace lldb;
60using namespace lldb_private;
61
62const char embedded_interpreter_string[] =
63"import readline\n\
64import code\n\
65import sys\n\
66import traceback\n\
67\n\
68class SimpleREPL(code.InteractiveConsole):\n\
69 def __init__(self, prompt, dict):\n\
70 code.InteractiveConsole.__init__(self,dict)\n\
71 self.prompt = prompt\n\
72 self.loop_exit = False\n\
73 self.dict = dict\n\
74\n\
75 def interact(self):\n\
76 try:\n\
77 sys.ps1\n\
78 except AttributeError:\n\
79 sys.ps1 = \">>> \"\n\
80 try:\n\
81 sys.ps2\n\
82 except AttributeError:\n\
83 sys.ps2 = \"... \"\n\
84\n\
85 while not self.loop_exit:\n\
86 try:\n\
87 self.read_py_command()\n\
88 except (SystemExit, EOFError):\n\
89 # EOF while in Python just breaks out to top level.\n\
90 self.write('\\n')\n\
91 self.loop_exit = True\n\
92 break\n\
93 except KeyboardInterrupt:\n\
94 self.write(\"\\nKeyboardInterrupt\\n\")\n\
95 self.resetbuffer()\n\
96 more = 0\n\
97 except:\n\
98 traceback.print_exc()\n\
99\n\
100 def process_input (self, in_str):\n\
101 # Canonicalize the format of the input string\n\
102 temp_str = in_str\n\
103 temp_str.strip(' \t')\n\
104 words = temp_str.split()\n\
105 temp_str = ('').join(words)\n\
106\n\
107 # Check the input string to see if it was the quit\n\
108 # command. If so, intercept it, so that it doesn't\n\
109 # close stdin on us!\n\
Jason Molendaa8a5e562010-06-09 21:56:00 +0000110 if (temp_str.lower() == \"quit()\" or temp_str.lower() == \"exit()\"):\n\
Chris Lattner24943d22010-06-08 16:52:24 +0000111 self.loop_exit = True\n\
112 in_str = \"raise SystemExit \"\n\
113 return in_str\n\
114\n\
115 def my_raw_input (self, prompt):\n\
116 stream = sys.stdout\n\
117 stream.write (prompt)\n\
118 stream.flush ()\n\
119 try:\n\
120 line = sys.stdin.readline()\n\
121 except KeyboardInterrupt:\n\
122 line = \" \\n\"\n\
123 except (SystemExit, EOFError):\n\
124 line = \"quit()\\n\"\n\
125 if not line:\n\
126 raise EOFError\n\
127 if line[-1] == '\\n':\n\
128 line = line[:-1]\n\
129 return line\n\
130\n\
131 def read_py_command(self):\n\
132 # Read off a complete Python command.\n\
133 more = 0\n\
134 while 1:\n\
135 if more:\n\
136 prompt = sys.ps2\n\
137 else:\n\
138 prompt = sys.ps1\n\
139 line = self.my_raw_input(prompt)\n\
140 # Can be None if sys.stdin was redefined\n\
141 encoding = getattr(sys.stdin, \"encoding\", None)\n\
142 if encoding and not isinstance(line, unicode):\n\
143 line = line.decode(encoding)\n\
144 line = self.process_input (line)\n\
145 more = self.push(line)\n\
146 if not more:\n\
147 break\n\
148\n\
149def run_python_interpreter (dict):\n\
150 # Pass in the dictionary, for continuity from one session to the next.\n\
151 repl = SimpleREPL('>>> ', dict)\n\
152 repl.interact()\n";
153
154static int
155_check_and_flush (FILE *stream)
156{
157 int prev_fail = ferror (stream);
158 return fflush (stream) || prev_fail ? EOF : 0;
159}
160
Greg Clayton63094e02010-06-23 01:19:29 +0000161ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000162 ScriptInterpreter (interpreter, eScriptLanguagePython),
Chris Lattner24943d22010-06-08 16:52:24 +0000163 m_compiled_module (NULL),
Caroline Tice2ade6112010-11-10 19:18:14 +0000164 m_termios (),
165 m_termios_valid (false),
166 m_embedded_python_pty (),
167 m_embedded_thread_input_reader_sp ()
Chris Lattner24943d22010-06-08 16:52:24 +0000168{
169
170 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000171
172 // Save terminal settings if we can
173 int input_fd;
174 FILE *input_fh = m_interpreter.GetDebugger().GetInputFileHandle();
175 if (input_fh != NULL)
176 input_fd = ::fileno (input_fh);
177 else
178 input_fd = STDIN_FILENO;
179
180 m_termios_valid = ::tcgetattr (input_fd, &m_termios) == 0;
181
Chris Lattner24943d22010-06-08 16:52:24 +0000182 // Find the module that owns this code and use that path we get to
183 // set the PYTHONPATH appropriately.
184
Greg Clayton24b48ff2010-10-17 22:03:32 +0000185 FileSpec file_spec;
186 char python_dir_path[PATH_MAX];
187 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +0000188 {
Greg Clayton24b48ff2010-10-17 22:03:32 +0000189 std::string python_path;
190 const char *curr_python_path = ::getenv ("PYTHONPATH");
191 if (curr_python_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000192 {
Greg Clayton24b48ff2010-10-17 22:03:32 +0000193 // We have a current value for PYTHONPATH, so lets append to it
194 python_path.append (curr_python_path);
Chris Lattner24943d22010-06-08 16:52:24 +0000195 }
Greg Clayton24b48ff2010-10-17 22:03:32 +0000196
197 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
198 {
199 if (!python_path.empty())
200 python_path.append (1, ':');
201 python_path.append (python_dir_path);
202 }
203
204 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
205 {
206 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
207 {
208 if (!python_path.empty())
209 python_path.append (1, ':');
210 python_path.append (python_dir_path);
211 }
212 }
213 const char *pathon_path_env_cstr = python_path.c_str();
214 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000215 }
216
217 Py_Initialize ();
218
Greg Clayton24b48ff2010-10-17 22:03:32 +0000219 PyObject *compiled_module = Py_CompileString (embedded_interpreter_string,
220 "embedded_interpreter.py",
Chris Lattner24943d22010-06-08 16:52:24 +0000221 Py_file_input);
222
Eli Friedman3c90d992010-06-09 18:31:38 +0000223 m_compiled_module = static_cast<void*>(compiled_module);
Chris Lattner24943d22010-06-08 16:52:24 +0000224
Greg Clayton121f3312010-07-07 18:40:03 +0000225 // This function is in the C++ output file generated by SWIG after it is
226 // run on all of the headers in "lldb/API/SB*.h"
Chris Lattner24943d22010-06-08 16:52:24 +0000227 init_lldb ();
228
229 // Update the path python uses to search for modules to include the current directory.
230
231 int success = PyRun_SimpleString ("import sys");
232 success = PyRun_SimpleString ("sys.path.append ('.')");
233 if (success == 0)
234 {
235 // Import the Script Bridge module.
Johnny Chen98bea862010-09-10 16:19:10 +0000236 success = PyRun_SimpleString ("import lldb");
Chris Lattner24943d22010-06-08 16:52:24 +0000237 }
238
239 const char *pty_slave_name = GetScriptInterpreterPtyName ();
Greg Clayton63094e02010-06-23 01:19:29 +0000240 FILE *out_fh = interpreter.GetDebugger().GetOutputFileHandle();
Chris Lattner24943d22010-06-08 16:52:24 +0000241
Caroline Tice5867f6b2010-10-18 18:24:17 +0000242 PyObject *pmod = PyImport_ExecCodeModule (const_cast<char*> ("embedded_interpreter"),
243 static_cast<PyObject*>(m_compiled_module));
244
Chris Lattner24943d22010-06-08 16:52:24 +0000245 if (pmod != NULL)
246 {
247 PyRun_SimpleString ("ConsoleDict = locals()");
248 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
249 PyRun_SimpleString ("import sys");
250 PyRun_SimpleString ("from termios import *");
Chris Lattner24943d22010-06-08 16:52:24 +0000251
Chris Lattner24943d22010-06-08 16:52:24 +0000252 if (out_fh != NULL)
253 {
254 PyObject *new_sysout = PyFile_FromFile (out_fh, (char *) "", (char *) "w",
255 _check_and_flush);
256 PyObject *sysmod = PyImport_AddModule ("sys");
257 PyObject *sysdict = PyModule_GetDict (sysmod);
258
259 if ((new_sysout != NULL)
260 && (sysmod != NULL)
261 && (sysdict != NULL))
262 {
263 PyDict_SetItemString (sysdict, "stdout", new_sysout);
264 }
265
266 if (PyErr_Occurred())
267 PyErr_Clear();
268 }
269
Caroline Tice5867f6b2010-10-18 18:24:17 +0000270 StreamString run_string;
271 run_string.Printf ("new_stdin = open('%s', 'r')", pty_slave_name);
272 PyRun_SimpleString (run_string.GetData());
273 PyRun_SimpleString ("sys.stdin = new_stdin");
274
Chris Lattner24943d22010-06-08 16:52:24 +0000275 PyRun_SimpleString ("new_mode = tcgetattr(new_stdin)");
276 PyRun_SimpleString ("new_mode[3] = new_mode[3] | ECHO | ICANON");
277 PyRun_SimpleString ("new_mode[6][VEOF] = 255");
278 PyRun_SimpleString ("tcsetattr (new_stdin, TCSANOW, new_mode)");
Caroline Tice558be582010-06-30 16:22:25 +0000279
280 run_string.Clear();
Johnny Chen98bea862010-09-10 16:19:10 +0000281 run_string.Printf ("lldb.debugger_unique_id = %d", interpreter.GetDebugger().GetID());
Caroline Tice558be582010-06-30 16:22:25 +0000282 PyRun_SimpleString (run_string.GetData());
Chris Lattner24943d22010-06-08 16:52:24 +0000283 }
284
285
Caroline Tice5867f6b2010-10-18 18:24:17 +0000286 // Restore terminal settings if they were validly saved
287 if (m_termios_valid)
288 {
289 ::tcsetattr (input_fd, TCSANOW, &m_termios);
290 }
Chris Lattner24943d22010-06-08 16:52:24 +0000291}
292
293ScriptInterpreterPython::~ScriptInterpreterPython ()
294{
Chris Lattner24943d22010-06-08 16:52:24 +0000295 Py_Finalize ();
296}
297
Johnny Chen60dde642010-07-30 22:33:14 +0000298bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000299ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000300{
Greg Clayton63094e02010-06-23 01:19:29 +0000301 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000302 {
Greg Clayton63094e02010-06-23 01:19:29 +0000303 int success;
304
Caroline Tice5867f6b2010-10-18 18:24:17 +0000305
306 // Save the current input file handle state before executing the command.
307 int input_fd;
308 struct termios tmp_termios;
309 bool valid_termios = false;
310 FILE *input_fh = m_interpreter.GetDebugger().GetInputFileHandle();
311 if (input_fh != NULL)
312 {
313 input_fd = ::fileno (input_fh);
314 valid_termios = ::tcgetattr (input_fd, &tmp_termios) == 0;
315 }
316
Greg Clayton63094e02010-06-23 01:19:29 +0000317 success = PyRun_SimpleString (command);
Johnny Chen60dde642010-07-30 22:33:14 +0000318 if (success == 0)
319 return true;
320
Caroline Tice5867f6b2010-10-18 18:24:17 +0000321 // Restore the input file handle state after executing the command.
322 if (valid_termios)
323 ::tcsetattr (input_fd, TCSANOW, &tmp_termios);
324
Johnny Chen60dde642010-07-30 22:33:14 +0000325 // The one-liner failed. Append the error message.
326 if (result)
327 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
328 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000329 }
Johnny Chen60dde642010-07-30 22:33:14 +0000330
331 if (result)
332 result->AppendError ("empty command passed to python\n");
333 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000334}
335
336
337
338size_t
339ScriptInterpreterPython::InputReaderCallback
340(
341 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000342 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000343 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000344 const char *bytes,
345 size_t bytes_len
346)
347{
Caroline Tice2ade6112010-11-10 19:18:14 +0000348 lldb::thread_t embedded_interpreter_thread;
349 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
350
Chris Lattner24943d22010-06-08 16:52:24 +0000351 if (baton == NULL)
352 return 0;
353
Greg Clayton63094e02010-06-23 01:19:29 +0000354 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Chris Lattner24943d22010-06-08 16:52:24 +0000355 switch (notification)
356 {
357 case eInputReaderActivate:
358 {
359 // Save terminal settings if we can
Caroline Ticec95c6d12010-09-14 22:49:06 +0000360 int input_fd;
Greg Clayton63094e02010-06-23 01:19:29 +0000361 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000362 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000363 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000364 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000365 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000366
Greg Clayton63094e02010-06-23 01:19:29 +0000367 script_interpreter->m_termios_valid = ::tcgetattr (input_fd, &script_interpreter->m_termios) == 0;
Greg Clayton24b48ff2010-10-17 22:03:32 +0000368
369 if (script_interpreter->m_termios_valid)
Chris Lattner24943d22010-06-08 16:52:24 +0000370 {
Greg Clayton24b48ff2010-10-17 22:03:32 +0000371 struct termios tmp_termios = script_interpreter->m_termios;
Chris Lattner24943d22010-06-08 16:52:24 +0000372 tmp_termios.c_cc[VEOF] = _POSIX_VDISABLE;
Greg Clayton63094e02010-06-23 01:19:29 +0000373 ::tcsetattr (input_fd, TCSANOW, &tmp_termios);
Chris Lattner24943d22010-06-08 16:52:24 +0000374 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000375 char error_str[1024];
376 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
377 sizeof(error_str)))
378 {
379 if (log)
380 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
381 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
382 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
383 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
384 script_interpreter, NULL);
385 if (embedded_interpreter_thread != LLDB_INVALID_HOST_THREAD)
386 {
387 if (log)
388 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
389 Error detach_error;
390 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
391 }
392 else
393 {
394 if (log)
395 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
396 reader.SetIsDone (true);
397 }
398 }
399 else
400 {
401 if (log)
402 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
403 reader.SetIsDone (true);
404 }
405
Chris Lattner24943d22010-06-08 16:52:24 +0000406 }
407 break;
408
409 case eInputReaderDeactivate:
410 break;
411
412 case eInputReaderReactivate:
413 break;
414
415 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000416 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000417 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000418 if (log)
419 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
420 bytes_len);
421 if (bytes && bytes_len)
422 {
423 if ((int) bytes[0] == 4)
424 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
425 else
426 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
427 }
428 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000429 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000430 else
431 {
432 if (log)
433 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
434 bytes,
435 bytes_len);
436 reader.SetIsDone (true);
437 }
438
Chris Lattner24943d22010-06-08 16:52:24 +0000439 break;
440
441 case eInputReaderDone:
442 // Send a control D to the script interpreter
443 //::write (interpreter->GetMasterFileDescriptor(), "\nquit()\n", strlen("\nquit()\n"));
444 // Write a newline out to the reader output
445 //::fwrite ("\n", 1, 1, out_fh);
446 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000447 if (log)
448 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Greg Clayton63094e02010-06-23 01:19:29 +0000449 if (script_interpreter->m_termios_valid)
Chris Lattner24943d22010-06-08 16:52:24 +0000450 {
Caroline Ticec95c6d12010-09-14 22:49:06 +0000451 int input_fd;
452 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
453 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000454 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000455 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000456 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000457
458 ::tcsetattr (input_fd, TCSANOW, &script_interpreter->m_termios);
Chris Lattner24943d22010-06-08 16:52:24 +0000459 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000460 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000461 break;
462 }
463
464 return bytes_len;
465}
466
467
468void
Greg Clayton238c0a12010-09-18 01:14:36 +0000469ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000470{
471 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
472
Greg Clayton238c0a12010-09-18 01:14:36 +0000473 Debugger &debugger = m_interpreter.GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000474
475 // At the moment, the only time the debugger does not have an input file handle is when this is called
476 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
477 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
478 // do it.
479
480 if (debugger.GetInputFileHandle() == NULL)
481 return;
482
Greg Clayton63094e02010-06-23 01:19:29 +0000483 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000484 if (reader_sp)
485 {
486 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
487 this, // baton
488 eInputReaderGranularityLine, // token size, to pass to callback function
489 NULL, // end token
490 NULL, // prompt
491 true)); // echo input
492
493 if (error.Success())
494 {
Greg Clayton63094e02010-06-23 01:19:29 +0000495 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000496 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000497 }
498 }
499}
500
501bool
502ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
503 ScriptInterpreter::ReturnType return_type,
504 void *ret_value)
505{
506 PyObject *py_return = NULL;
507 PyObject *mainmod = PyImport_AddModule ("__main__");
508 PyObject *globals = PyModule_GetDict (mainmod);
509 PyObject *locals = globals;
510 PyObject *py_error = NULL;
511 bool ret_success;
512 int success;
513
514 if (in_string != NULL)
515 {
516 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
517 if (py_return == NULL)
518 {
519 py_error = PyErr_Occurred ();
520 if (py_error != NULL)
521 PyErr_Clear ();
522
523 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
524 }
525
526 if (py_return != NULL)
527 {
528 switch (return_type)
529 {
530 case eCharPtr: // "char *"
531 {
532 const char format[3] = "s#";
533 success = PyArg_Parse (py_return, format, (char **) &ret_value);
534 break;
535 }
536 case eBool:
537 {
538 const char format[2] = "b";
539 success = PyArg_Parse (py_return, format, (bool *) ret_value);
540 break;
541 }
542 case eShortInt:
543 {
544 const char format[2] = "h";
545 success = PyArg_Parse (py_return, format, (short *) ret_value);
546 break;
547 }
548 case eShortIntUnsigned:
549 {
550 const char format[2] = "H";
551 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
552 break;
553 }
554 case eInt:
555 {
556 const char format[2] = "i";
557 success = PyArg_Parse (py_return, format, (int *) ret_value);
558 break;
559 }
560 case eIntUnsigned:
561 {
562 const char format[2] = "I";
563 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
564 break;
565 }
566 case eLongInt:
567 {
568 const char format[2] = "l";
569 success = PyArg_Parse (py_return, format, (long *) ret_value);
570 break;
571 }
572 case eLongIntUnsigned:
573 {
574 const char format[2] = "k";
575 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
576 break;
577 }
578 case eLongLong:
579 {
580 const char format[2] = "L";
581 success = PyArg_Parse (py_return, format, (long long *) ret_value);
582 break;
583 }
584 case eLongLongUnsigned:
585 {
586 const char format[2] = "K";
587 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
588 break;
589 }
590 case eFloat:
591 {
592 const char format[2] = "f";
593 success = PyArg_Parse (py_return, format, (float *) ret_value);
594 break;
595 }
596 case eDouble:
597 {
598 const char format[2] = "d";
599 success = PyArg_Parse (py_return, format, (double *) ret_value);
600 break;
601 }
602 case eChar:
603 {
604 const char format[2] = "c";
605 success = PyArg_Parse (py_return, format, (char *) ret_value);
606 break;
607 }
608 default:
609 {}
610 }
611 Py_DECREF (py_return);
612 if (success)
613 ret_success = true;
614 else
615 ret_success = false;
616 }
617 }
618
619 py_error = PyErr_Occurred();
620 if (py_error != NULL)
621 {
622 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
623 PyErr_Print ();
624 PyErr_Clear();
625 ret_success = false;
626 }
627
628 return ret_success;
629}
630
631bool
632ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
633{
634 bool success = false;
635 PyObject *py_return = NULL;
636 PyObject *mainmod = PyImport_AddModule ("__main__");
637 PyObject *globals = PyModule_GetDict (mainmod);
638 PyObject *locals = globals;
639 PyObject *py_error = NULL;
640
641 if (in_string != NULL)
642 {
643 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
644 if (compiled_node)
645 {
646 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
647 if (compiled_code)
648 {
649 py_return = PyEval_EvalCode (compiled_code, globals, locals);
650 if (py_return != NULL)
651 {
652 success = true;
653 Py_DECREF (py_return);
654 }
655 }
656 }
657 }
658
659 py_error = PyErr_Occurred ();
660 if (py_error != NULL)
661 {
662 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
663 PyErr_Print ();
664 PyErr_Clear();
665 success = false;
666 }
667
668 return success;
669}
670
671static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
672
673size_t
674ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
675(
676 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000677 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000678 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000679 const char *bytes,
680 size_t bytes_len
681)
682{
683 static StringList commands_in_progress;
684
Greg Clayton63094e02010-06-23 01:19:29 +0000685 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000686 if (out_fh == NULL)
687 out_fh = stdout;
688
Chris Lattner24943d22010-06-08 16:52:24 +0000689 switch (notification)
690 {
691 case eInputReaderActivate:
692 {
693 commands_in_progress.Clear();
694 if (out_fh)
695 {
696 ::fprintf (out_fh, "%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000697 if (reader.GetPrompt())
698 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +0000699 ::fflush (out_fh);
Chris Lattner24943d22010-06-08 16:52:24 +0000700 }
701 }
702 break;
703
704 case eInputReaderDeactivate:
705 break;
706
707 case eInputReaderReactivate:
Greg Clayton63094e02010-06-23 01:19:29 +0000708 if (reader.GetPrompt() && out_fh)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000709 {
Greg Clayton63094e02010-06-23 01:19:29 +0000710 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +0000711 ::fflush (out_fh);
712 }
Chris Lattner24943d22010-06-08 16:52:24 +0000713 break;
714
715 case eInputReaderGotToken:
716 {
717 std::string temp_string (bytes, bytes_len);
718 commands_in_progress.AppendString (temp_string.c_str());
Greg Clayton63094e02010-06-23 01:19:29 +0000719 if (out_fh && !reader.IsDone() && reader.GetPrompt())
Caroline Ticef81b4c52010-10-27 18:34:42 +0000720 {
Greg Clayton63094e02010-06-23 01:19:29 +0000721 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +0000722 ::fflush (out_fh);
723 }
Chris Lattner24943d22010-06-08 16:52:24 +0000724 }
725 break;
726
727 case eInputReaderDone:
728 {
729 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
730 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
731 data_ap->user_source.AppendList (commands_in_progress);
732 if (data_ap.get())
733 {
Greg Clayton63094e02010-06-23 01:19:29 +0000734 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +0000735 if (interpreter)
736 {
737 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
738 data_ap->script_source))
739 {
740 if (data_ap->script_source.GetSize() == 1)
741 {
742 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
743 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
744 }
745 }
Caroline Ticeb447e842010-09-21 19:25:28 +0000746 else
Caroline Tice5136f942010-09-27 21:35:15 +0000747 ::fprintf (out_fh, "Warning: No command attached to breakpoint.\n");
Chris Lattner24943d22010-06-08 16:52:24 +0000748 }
749 else
750 {
751 // FIXME: Error processing.
752 }
753 }
754 }
755 break;
756
757 }
758
759 return bytes_len;
760}
761
762void
Greg Clayton238c0a12010-09-18 01:14:36 +0000763ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +0000764 CommandReturnObject &result)
765{
Greg Clayton238c0a12010-09-18 01:14:36 +0000766 Debugger &debugger = m_interpreter.GetDebugger();
Greg Clayton63094e02010-06-23 01:19:29 +0000767 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000768
769 if (reader_sp)
770 {
771 Error err = reader_sp->Initialize (
772 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
773 bp_options, // baton
774 eInputReaderGranularityLine, // token size, for feeding data to callback function
775 "DONE", // end token
776 "> ", // prompt
777 true); // echo input
778
779 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +0000780 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +0000781 else
782 {
783 result.AppendError (err.AsCString());
784 result.SetStatus (eReturnStatusFailed);
785 }
786 }
787 else
788 {
789 result.AppendError("out of memory");
790 result.SetStatus (eReturnStatusFailed);
791 }
792}
793
Johnny Chen3e0571b2010-09-11 00:23:59 +0000794// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +0000795void
Greg Clayton238c0a12010-09-18 01:14:36 +0000796ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +0000797 const char *oneliner)
798{
799 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
800
801 // It's necessary to set both user_source and script_source to the oneliner.
802 // The former is used to generate callback description (as in breakpoint command list)
803 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +0000804
Johnny Chend1c2dca2010-09-10 18:21:10 +0000805 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +0000806
Caroline Tice5136f942010-09-27 21:35:15 +0000807 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
808 {
809 if (data_ap->script_source.GetSize() == 1)
810 {
811 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
812 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
813 }
814 }
815
Johnny Chend1c2dca2010-09-10 18:21:10 +0000816 return;
817}
818
Chris Lattner24943d22010-06-08 16:52:24 +0000819bool
820ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
821{
822 // Convert StringList to one long, newline delimited, const char *.
823 std::string function_def_string;
824
825 int num_lines = function_def.GetSize();
826
827 for (int i = 0; i < num_lines; ++i)
828 {
829 function_def_string.append (function_def.GetStringAtIndex(i));
830 if (function_def_string.at (function_def_string.length() - 1) != '\n')
831 function_def_string.append ("\n");
832
833 }
834
835 return ExecuteMultipleLines (function_def_string.c_str());
836}
837
838bool
839ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
840{
841 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000842 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000843 int num_lines = user_input.GetSize ();
844 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +0000845
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000846 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
847 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +0000848
Caroline Ticeb447e842010-09-21 19:25:28 +0000849
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000850 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
851 ++num_created_functions;
852 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +0000853
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000854 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +0000855 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +0000856
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000857 // Create the function name & definition string.
858
859 sstr.Printf ("def %s (frame, bp_loc):", auto_generated_function_name.c_str());
860 auto_generated_function.AppendString (sstr.GetData());
861
862 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +0000863
864 for (int i = 0; i < num_lines; ++i)
865 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000866 sstr.Clear ();
867 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
868 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +0000869 }
Chris Lattner24943d22010-06-08 16:52:24 +0000870
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000871 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +0000872
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000873 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +0000874 {
Caroline Ticeb447e842010-09-21 19:25:28 +0000875 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000876 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000877
878 // Store the name of the auto-generated function to be called.
879
880 callback_data.AppendString (auto_generated_function_name.c_str());
881 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000882}
883
Greg Clayton5144f382010-10-07 17:14:24 +0000884bool
885ScriptInterpreterPython::BreakpointCallbackFunction
886(
887 void *baton,
888 StoppointCallbackContext *context,
889 user_id_t break_id,
890 user_id_t break_loc_id
891)
892{
893 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
894 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
895
896 if (python_function_name != NULL
897 && python_function_name[0] != '\0')
898 {
899 Thread *thread = context->exe_ctx.thread;
900 Target *target = context->exe_ctx.target;
901 const StackFrameSP stop_frame_sp = thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame);
902 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
903 const BreakpointLocationSP bp_loc_sp = breakpoint_sp->FindLocationByID (break_loc_id);
904
905 SBFrame sb_frame (stop_frame_sp);
906 SBBreakpointLocation sb_bp_loc (bp_loc_sp);
907
908 if (sb_bp_loc.IsValid() || sb_frame.IsValid())
909 return LLDBSWIGPythonBreakpointCallbackFunction (python_function_name, sb_frame, sb_bp_loc);
910 }
911 // We currently always true so we stop in case anything goes wrong when
912 // trying to call the script function
913 return true;
914}
Caroline Tice2ade6112010-11-10 19:18:14 +0000915
916lldb::thread_result_t
917ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
918{
919 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
920
921 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
922
923 if (log)
924 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
925
926 char error_str[1024];
927 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
928 if (pty_slave_name != NULL)
929 {
930 StreamString run_string;
931 PyRun_SimpleString ("save_stderr = sys.stderr");
932 PyRun_SimpleString ("sys.stderr = sys.stdout");
933 PyRun_SimpleString ("save_stdin = sys.stdin");
934 run_string.Printf ("sys.stdin = open ('%s', 'r')", pty_slave_name);
935 PyRun_SimpleString (run_string.GetData());
936 PyRun_SimpleString ("new_mode = tcgetattr(sys.stdin)");
937 PyRun_SimpleString ("new_mode[3] = new_mode[3] | ECHO | ICANON");
938 PyRun_SimpleString ("new_mode[6][VEOF] = 255");
939 PyRun_SimpleString ("tcsetattr (sys.stdin, TCSANOW, new_mode)");
940
941 // The following call drops into the embedded interpreter loop and stays there until the
942 // user chooses to exit from the Python interpreter.
943 script_interpreter->ExecuteOneLine ("run_python_interpreter(ConsoleDict)", NULL);
944
945 PyRun_SimpleString ("sys.stdin = save_stdin");
946 PyRun_SimpleString ("sys.stderr = save_stderr");
947 }
948
949 if (script_interpreter->m_embedded_thread_input_reader_sp)
950 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
951
952 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
953
954 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
955 if (log)
956 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
957
958
959 // Clean up the input reader and make the debugger pop it off the stack.
960 Debugger &debugger = script_interpreter->m_interpreter.GetDebugger();
961 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
962 script_interpreter->m_embedded_thread_input_reader_sp.reset();
963 debugger.PopInputReader (reader_sp);
964
965 return NULL;
966}
967
968
969