blob: 9520150efab74f9153ebd55f2c36b7ce0df9d569 [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
13#include <Python.h>
14
15#include "lldb/Interpreter/ScriptInterpreterPython.h"
16
17
18#include <sys/ioctl.h>
19#include <termios.h>
20#include <stdlib.h>
21#include <stdio.h>
22
23#include <string>
24
Greg Clayton5144f382010-10-07 17:14:24 +000025#include "lldb/API/SBFrame.h"
26#include "lldb/API/SBBreakpointLocation.h"
Chris Lattner24943d22010-06-08 16:52:24 +000027#include "lldb/Breakpoint/Breakpoint.h"
28#include "lldb/Breakpoint/BreakpointLocation.h"
Greg Clayton63094e02010-06-23 01:19:29 +000029#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030#include "lldb/Core/Debugger.h"
31#include "lldb/Core/FileSpec.h"
32#include "lldb/Core/InputReader.h"
33#include "lldb/Core/Stream.h"
34#include "lldb/Core/StreamString.h"
35#include "lldb/Core/Timer.h"
36#include "lldb/Host/Host.h"
37#include "lldb/Interpreter/CommandInterpreter.h"
38#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton63094e02010-06-23 01:19:29 +000039#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040#include "lldb/Target/Process.h"
Greg Clayton5144f382010-10-07 17:14:24 +000041#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000042
Greg Clayton121f3312010-07-07 18:40:03 +000043// This function is in the C++ output file generated by SWIG after it is
44// run on all of the headers in "lldb/API/SB*.h"
Chris Lattner24943d22010-06-08 16:52:24 +000045extern "C" void init_lldb (void);
46
Greg Clayton5144f382010-10-07 17:14:24 +000047extern "C" bool
48LLDBSWIGPythonBreakpointCallbackFunction
49(
50 const char *python_function_name,
51 lldb::SBFrame& sb_frame,
52 lldb::SBBreakpointLocation& sb_bp_loc
53);
54
Chris Lattner24943d22010-06-08 16:52:24 +000055using namespace lldb;
56using namespace lldb_private;
57
58const char embedded_interpreter_string[] =
59"import readline\n\
60import code\n\
61import sys\n\
62import traceback\n\
63\n\
64class SimpleREPL(code.InteractiveConsole):\n\
65 def __init__(self, prompt, dict):\n\
66 code.InteractiveConsole.__init__(self,dict)\n\
67 self.prompt = prompt\n\
68 self.loop_exit = False\n\
69 self.dict = dict\n\
70\n\
71 def interact(self):\n\
72 try:\n\
73 sys.ps1\n\
74 except AttributeError:\n\
75 sys.ps1 = \">>> \"\n\
76 try:\n\
77 sys.ps2\n\
78 except AttributeError:\n\
79 sys.ps2 = \"... \"\n\
80\n\
81 while not self.loop_exit:\n\
82 try:\n\
83 self.read_py_command()\n\
84 except (SystemExit, EOFError):\n\
85 # EOF while in Python just breaks out to top level.\n\
86 self.write('\\n')\n\
87 self.loop_exit = True\n\
88 break\n\
89 except KeyboardInterrupt:\n\
90 self.write(\"\\nKeyboardInterrupt\\n\")\n\
91 self.resetbuffer()\n\
92 more = 0\n\
93 except:\n\
94 traceback.print_exc()\n\
95\n\
96 def process_input (self, in_str):\n\
97 # Canonicalize the format of the input string\n\
98 temp_str = in_str\n\
99 temp_str.strip(' \t')\n\
100 words = temp_str.split()\n\
101 temp_str = ('').join(words)\n\
102\n\
103 # Check the input string to see if it was the quit\n\
104 # command. If so, intercept it, so that it doesn't\n\
105 # close stdin on us!\n\
Jason Molendaa8a5e562010-06-09 21:56:00 +0000106 if (temp_str.lower() == \"quit()\" or temp_str.lower() == \"exit()\"):\n\
Chris Lattner24943d22010-06-08 16:52:24 +0000107 self.loop_exit = True\n\
108 in_str = \"raise SystemExit \"\n\
109 return in_str\n\
110\n\
111 def my_raw_input (self, prompt):\n\
112 stream = sys.stdout\n\
113 stream.write (prompt)\n\
114 stream.flush ()\n\
115 try:\n\
116 line = sys.stdin.readline()\n\
117 except KeyboardInterrupt:\n\
118 line = \" \\n\"\n\
119 except (SystemExit, EOFError):\n\
120 line = \"quit()\\n\"\n\
121 if not line:\n\
122 raise EOFError\n\
123 if line[-1] == '\\n':\n\
124 line = line[:-1]\n\
125 return line\n\
126\n\
127 def read_py_command(self):\n\
128 # Read off a complete Python command.\n\
129 more = 0\n\
130 while 1:\n\
131 if more:\n\
132 prompt = sys.ps2\n\
133 else:\n\
134 prompt = sys.ps1\n\
135 line = self.my_raw_input(prompt)\n\
136 # Can be None if sys.stdin was redefined\n\
137 encoding = getattr(sys.stdin, \"encoding\", None)\n\
138 if encoding and not isinstance(line, unicode):\n\
139 line = line.decode(encoding)\n\
140 line = self.process_input (line)\n\
141 more = self.push(line)\n\
142 if not more:\n\
143 break\n\
144\n\
145def run_python_interpreter (dict):\n\
146 # Pass in the dictionary, for continuity from one session to the next.\n\
147 repl = SimpleREPL('>>> ', dict)\n\
148 repl.interact()\n";
149
150static int
151_check_and_flush (FILE *stream)
152{
153 int prev_fail = ferror (stream);
154 return fflush (stream) || prev_fail ? EOF : 0;
155}
156
Greg Clayton63094e02010-06-23 01:19:29 +0000157ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000158 ScriptInterpreter (interpreter, eScriptLanguagePython),
Chris Lattner24943d22010-06-08 16:52:24 +0000159 m_compiled_module (NULL),
160 m_termios_valid (false)
161{
162
163 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
164 // Find the module that owns this code and use that path we get to
165 // set the PYTHONPATH appropriately.
166
Greg Clayton24b48ff2010-10-17 22:03:32 +0000167 FileSpec file_spec;
168 char python_dir_path[PATH_MAX];
169 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +0000170 {
Greg Clayton24b48ff2010-10-17 22:03:32 +0000171 std::string python_path;
172 const char *curr_python_path = ::getenv ("PYTHONPATH");
173 if (curr_python_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000174 {
Greg Clayton24b48ff2010-10-17 22:03:32 +0000175 // We have a current value for PYTHONPATH, so lets append to it
176 python_path.append (curr_python_path);
Chris Lattner24943d22010-06-08 16:52:24 +0000177 }
Greg Clayton24b48ff2010-10-17 22:03:32 +0000178
179 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
180 {
181 if (!python_path.empty())
182 python_path.append (1, ':');
183 python_path.append (python_dir_path);
184 }
185
186 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
187 {
188 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
189 {
190 if (!python_path.empty())
191 python_path.append (1, ':');
192 python_path.append (python_dir_path);
193 }
194 }
195 const char *pathon_path_env_cstr = python_path.c_str();
196 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000197 }
198
199 Py_Initialize ();
200
Greg Clayton24b48ff2010-10-17 22:03:32 +0000201 PyObject *compiled_module = Py_CompileString (embedded_interpreter_string,
202 "embedded_interpreter.py",
Chris Lattner24943d22010-06-08 16:52:24 +0000203 Py_file_input);
204
Eli Friedman3c90d992010-06-09 18:31:38 +0000205 m_compiled_module = static_cast<void*>(compiled_module);
Chris Lattner24943d22010-06-08 16:52:24 +0000206
Greg Clayton121f3312010-07-07 18:40:03 +0000207 // This function is in the C++ output file generated by SWIG after it is
208 // run on all of the headers in "lldb/API/SB*.h"
Chris Lattner24943d22010-06-08 16:52:24 +0000209 init_lldb ();
210
211 // Update the path python uses to search for modules to include the current directory.
212
213 int success = PyRun_SimpleString ("import sys");
214 success = PyRun_SimpleString ("sys.path.append ('.')");
215 if (success == 0)
216 {
217 // Import the Script Bridge module.
Johnny Chen98bea862010-09-10 16:19:10 +0000218 success = PyRun_SimpleString ("import lldb");
Chris Lattner24943d22010-06-08 16:52:24 +0000219 }
220
221 const char *pty_slave_name = GetScriptInterpreterPtyName ();
Greg Clayton63094e02010-06-23 01:19:29 +0000222 FILE *out_fh = interpreter.GetDebugger().GetOutputFileHandle();
Chris Lattner24943d22010-06-08 16:52:24 +0000223
Eli Friedman3c90d992010-06-09 18:31:38 +0000224 PyObject *pmod = PyImport_ExecCodeModule(
225 const_cast<char*>("embedded_interpreter"),
226 static_cast<PyObject*>(m_compiled_module));
Chris Lattner24943d22010-06-08 16:52:24 +0000227 if (pmod != NULL)
228 {
229 PyRun_SimpleString ("ConsoleDict = locals()");
230 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
231 PyRun_SimpleString ("import sys");
232 PyRun_SimpleString ("from termios import *");
Chris Lattner24943d22010-06-08 16:52:24 +0000233
234 StreamString run_string;
235 run_string.Printf ("new_stdin = open('%s', 'r')", pty_slave_name);
236 PyRun_SimpleString (run_string.GetData());
237 PyRun_SimpleString ("sys.stdin = new_stdin");
238
Chris Lattner24943d22010-06-08 16:52:24 +0000239 if (out_fh != NULL)
240 {
241 PyObject *new_sysout = PyFile_FromFile (out_fh, (char *) "", (char *) "w",
242 _check_and_flush);
243 PyObject *sysmod = PyImport_AddModule ("sys");
244 PyObject *sysdict = PyModule_GetDict (sysmod);
245
246 if ((new_sysout != NULL)
247 && (sysmod != NULL)
248 && (sysdict != NULL))
249 {
250 PyDict_SetItemString (sysdict, "stdout", new_sysout);
251 }
252
253 if (PyErr_Occurred())
254 PyErr_Clear();
255 }
256
257 PyRun_SimpleString ("new_mode = tcgetattr(new_stdin)");
258 PyRun_SimpleString ("new_mode[3] = new_mode[3] | ECHO | ICANON");
259 PyRun_SimpleString ("new_mode[6][VEOF] = 255");
260 PyRun_SimpleString ("tcsetattr (new_stdin, TCSANOW, new_mode)");
Caroline Tice558be582010-06-30 16:22:25 +0000261
262 run_string.Clear();
Johnny Chen98bea862010-09-10 16:19:10 +0000263 run_string.Printf ("lldb.debugger_unique_id = %d", interpreter.GetDebugger().GetID());
Caroline Tice558be582010-06-30 16:22:25 +0000264 PyRun_SimpleString (run_string.GetData());
Chris Lattner24943d22010-06-08 16:52:24 +0000265 }
266
267
268}
269
270ScriptInterpreterPython::~ScriptInterpreterPython ()
271{
Chris Lattner24943d22010-06-08 16:52:24 +0000272 Py_Finalize ();
273}
274
Johnny Chen60dde642010-07-30 22:33:14 +0000275bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000276ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000277{
Greg Clayton63094e02010-06-23 01:19:29 +0000278 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000279 {
Greg Clayton63094e02010-06-23 01:19:29 +0000280 int success;
281
282 success = PyRun_SimpleString (command);
Johnny Chen60dde642010-07-30 22:33:14 +0000283 if (success == 0)
284 return true;
285
286 // The one-liner failed. Append the error message.
287 if (result)
288 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
289 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000290 }
Johnny Chen60dde642010-07-30 22:33:14 +0000291
292 if (result)
293 result->AppendError ("empty command passed to python\n");
294 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000295}
296
297
298
299size_t
300ScriptInterpreterPython::InputReaderCallback
301(
302 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000303 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000304 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000305 const char *bytes,
306 size_t bytes_len
307)
308{
309 if (baton == NULL)
310 return 0;
311
Greg Clayton63094e02010-06-23 01:19:29 +0000312 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Chris Lattner24943d22010-06-08 16:52:24 +0000313 switch (notification)
314 {
315 case eInputReaderActivate:
316 {
317 // Save terminal settings if we can
Caroline Ticec95c6d12010-09-14 22:49:06 +0000318 int input_fd;
Greg Clayton63094e02010-06-23 01:19:29 +0000319 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000320 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000321 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000322 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000323 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000324
Greg Clayton63094e02010-06-23 01:19:29 +0000325 script_interpreter->m_termios_valid = ::tcgetattr (input_fd, &script_interpreter->m_termios) == 0;
Greg Clayton24b48ff2010-10-17 22:03:32 +0000326
327 if (script_interpreter->m_termios_valid)
Chris Lattner24943d22010-06-08 16:52:24 +0000328 {
Greg Clayton24b48ff2010-10-17 22:03:32 +0000329 struct termios tmp_termios = script_interpreter->m_termios;
Chris Lattner24943d22010-06-08 16:52:24 +0000330 tmp_termios.c_cc[VEOF] = _POSIX_VDISABLE;
Greg Clayton63094e02010-06-23 01:19:29 +0000331 ::tcsetattr (input_fd, TCSANOW, &tmp_termios);
Chris Lattner24943d22010-06-08 16:52:24 +0000332 }
333 }
334 break;
335
336 case eInputReaderDeactivate:
337 break;
338
339 case eInputReaderReactivate:
340 break;
341
342 case eInputReaderGotToken:
343 if (bytes && bytes_len)
344 {
345 if ((int) bytes[0] == 4)
Greg Clayton63094e02010-06-23 01:19:29 +0000346 ::write (script_interpreter->GetMasterFileDescriptor(), "quit()", 6);
Chris Lattner24943d22010-06-08 16:52:24 +0000347 else
Greg Clayton63094e02010-06-23 01:19:29 +0000348 ::write (script_interpreter->GetMasterFileDescriptor(), bytes, bytes_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000349 }
Greg Clayton63094e02010-06-23 01:19:29 +0000350 ::write (script_interpreter->GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000351 break;
352
353 case eInputReaderDone:
354 // Send a control D to the script interpreter
355 //::write (interpreter->GetMasterFileDescriptor(), "\nquit()\n", strlen("\nquit()\n"));
356 // Write a newline out to the reader output
357 //::fwrite ("\n", 1, 1, out_fh);
358 // Restore terminal settings if they were validly saved
Greg Clayton63094e02010-06-23 01:19:29 +0000359 if (script_interpreter->m_termios_valid)
Chris Lattner24943d22010-06-08 16:52:24 +0000360 {
Caroline Ticec95c6d12010-09-14 22:49:06 +0000361 int input_fd;
362 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
363 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000364 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000365 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000366 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000367
368 ::tcsetattr (input_fd, TCSANOW, &script_interpreter->m_termios);
Chris Lattner24943d22010-06-08 16:52:24 +0000369 }
370 break;
371 }
372
373 return bytes_len;
374}
375
376
377void
Greg Clayton238c0a12010-09-18 01:14:36 +0000378ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000379{
380 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
381
Greg Clayton238c0a12010-09-18 01:14:36 +0000382 Debugger &debugger = m_interpreter.GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000383
384 // At the moment, the only time the debugger does not have an input file handle is when this is called
385 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
386 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
387 // do it.
388
389 if (debugger.GetInputFileHandle() == NULL)
390 return;
391
Greg Clayton63094e02010-06-23 01:19:29 +0000392 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000393 if (reader_sp)
394 {
395 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
396 this, // baton
397 eInputReaderGranularityLine, // token size, to pass to callback function
398 NULL, // end token
399 NULL, // prompt
400 true)); // echo input
401
402 if (error.Success())
403 {
Greg Clayton63094e02010-06-23 01:19:29 +0000404 debugger.PushInputReader (reader_sp);
Greg Clayton238c0a12010-09-18 01:14:36 +0000405 ExecuteOneLine ("run_python_interpreter(ConsoleDict)", NULL);
Greg Clayton63094e02010-06-23 01:19:29 +0000406 debugger.PopInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +0000407 }
408 }
409}
410
411bool
412ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
413 ScriptInterpreter::ReturnType return_type,
414 void *ret_value)
415{
416 PyObject *py_return = NULL;
417 PyObject *mainmod = PyImport_AddModule ("__main__");
418 PyObject *globals = PyModule_GetDict (mainmod);
419 PyObject *locals = globals;
420 PyObject *py_error = NULL;
421 bool ret_success;
422 int success;
423
424 if (in_string != NULL)
425 {
426 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
427 if (py_return == NULL)
428 {
429 py_error = PyErr_Occurred ();
430 if (py_error != NULL)
431 PyErr_Clear ();
432
433 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
434 }
435
436 if (py_return != NULL)
437 {
438 switch (return_type)
439 {
440 case eCharPtr: // "char *"
441 {
442 const char format[3] = "s#";
443 success = PyArg_Parse (py_return, format, (char **) &ret_value);
444 break;
445 }
446 case eBool:
447 {
448 const char format[2] = "b";
449 success = PyArg_Parse (py_return, format, (bool *) ret_value);
450 break;
451 }
452 case eShortInt:
453 {
454 const char format[2] = "h";
455 success = PyArg_Parse (py_return, format, (short *) ret_value);
456 break;
457 }
458 case eShortIntUnsigned:
459 {
460 const char format[2] = "H";
461 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
462 break;
463 }
464 case eInt:
465 {
466 const char format[2] = "i";
467 success = PyArg_Parse (py_return, format, (int *) ret_value);
468 break;
469 }
470 case eIntUnsigned:
471 {
472 const char format[2] = "I";
473 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
474 break;
475 }
476 case eLongInt:
477 {
478 const char format[2] = "l";
479 success = PyArg_Parse (py_return, format, (long *) ret_value);
480 break;
481 }
482 case eLongIntUnsigned:
483 {
484 const char format[2] = "k";
485 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
486 break;
487 }
488 case eLongLong:
489 {
490 const char format[2] = "L";
491 success = PyArg_Parse (py_return, format, (long long *) ret_value);
492 break;
493 }
494 case eLongLongUnsigned:
495 {
496 const char format[2] = "K";
497 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
498 break;
499 }
500 case eFloat:
501 {
502 const char format[2] = "f";
503 success = PyArg_Parse (py_return, format, (float *) ret_value);
504 break;
505 }
506 case eDouble:
507 {
508 const char format[2] = "d";
509 success = PyArg_Parse (py_return, format, (double *) ret_value);
510 break;
511 }
512 case eChar:
513 {
514 const char format[2] = "c";
515 success = PyArg_Parse (py_return, format, (char *) ret_value);
516 break;
517 }
518 default:
519 {}
520 }
521 Py_DECREF (py_return);
522 if (success)
523 ret_success = true;
524 else
525 ret_success = false;
526 }
527 }
528
529 py_error = PyErr_Occurred();
530 if (py_error != NULL)
531 {
532 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
533 PyErr_Print ();
534 PyErr_Clear();
535 ret_success = false;
536 }
537
538 return ret_success;
539}
540
541bool
542ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
543{
544 bool success = false;
545 PyObject *py_return = NULL;
546 PyObject *mainmod = PyImport_AddModule ("__main__");
547 PyObject *globals = PyModule_GetDict (mainmod);
548 PyObject *locals = globals;
549 PyObject *py_error = NULL;
550
551 if (in_string != NULL)
552 {
553 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
554 if (compiled_node)
555 {
556 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
557 if (compiled_code)
558 {
559 py_return = PyEval_EvalCode (compiled_code, globals, locals);
560 if (py_return != NULL)
561 {
562 success = true;
563 Py_DECREF (py_return);
564 }
565 }
566 }
567 }
568
569 py_error = PyErr_Occurred ();
570 if (py_error != NULL)
571 {
572 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
573 PyErr_Print ();
574 PyErr_Clear();
575 success = false;
576 }
577
578 return success;
579}
580
581static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
582
583size_t
584ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
585(
586 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000587 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000588 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000589 const char *bytes,
590 size_t bytes_len
591)
592{
593 static StringList commands_in_progress;
594
Greg Clayton63094e02010-06-23 01:19:29 +0000595 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000596 if (out_fh == NULL)
597 out_fh = stdout;
598
Chris Lattner24943d22010-06-08 16:52:24 +0000599 switch (notification)
600 {
601 case eInputReaderActivate:
602 {
603 commands_in_progress.Clear();
604 if (out_fh)
605 {
606 ::fprintf (out_fh, "%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000607 if (reader.GetPrompt())
608 ::fprintf (out_fh, "%s", reader.GetPrompt());
Chris Lattner24943d22010-06-08 16:52:24 +0000609 }
610 }
611 break;
612
613 case eInputReaderDeactivate:
614 break;
615
616 case eInputReaderReactivate:
Greg Clayton63094e02010-06-23 01:19:29 +0000617 if (reader.GetPrompt() && out_fh)
618 ::fprintf (out_fh, "%s", reader.GetPrompt());
Chris Lattner24943d22010-06-08 16:52:24 +0000619 break;
620
621 case eInputReaderGotToken:
622 {
623 std::string temp_string (bytes, bytes_len);
624 commands_in_progress.AppendString (temp_string.c_str());
Greg Clayton63094e02010-06-23 01:19:29 +0000625 if (out_fh && !reader.IsDone() && reader.GetPrompt())
626 ::fprintf (out_fh, "%s", reader.GetPrompt());
Chris Lattner24943d22010-06-08 16:52:24 +0000627 }
628 break;
629
630 case eInputReaderDone:
631 {
632 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
633 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
634 data_ap->user_source.AppendList (commands_in_progress);
635 if (data_ap.get())
636 {
Greg Clayton63094e02010-06-23 01:19:29 +0000637 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +0000638 if (interpreter)
639 {
640 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
641 data_ap->script_source))
642 {
643 if (data_ap->script_source.GetSize() == 1)
644 {
645 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
646 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
647 }
648 }
Caroline Ticeb447e842010-09-21 19:25:28 +0000649 else
Caroline Tice5136f942010-09-27 21:35:15 +0000650 ::fprintf (out_fh, "Warning: No command attached to breakpoint.\n");
Chris Lattner24943d22010-06-08 16:52:24 +0000651 }
652 else
653 {
654 // FIXME: Error processing.
655 }
656 }
657 }
658 break;
659
660 }
661
662 return bytes_len;
663}
664
665void
Greg Clayton238c0a12010-09-18 01:14:36 +0000666ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +0000667 CommandReturnObject &result)
668{
Greg Clayton238c0a12010-09-18 01:14:36 +0000669 Debugger &debugger = m_interpreter.GetDebugger();
Greg Clayton63094e02010-06-23 01:19:29 +0000670 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000671
672 if (reader_sp)
673 {
674 Error err = reader_sp->Initialize (
675 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
676 bp_options, // baton
677 eInputReaderGranularityLine, // token size, for feeding data to callback function
678 "DONE", // end token
679 "> ", // prompt
680 true); // echo input
681
682 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +0000683 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +0000684 else
685 {
686 result.AppendError (err.AsCString());
687 result.SetStatus (eReturnStatusFailed);
688 }
689 }
690 else
691 {
692 result.AppendError("out of memory");
693 result.SetStatus (eReturnStatusFailed);
694 }
695}
696
Johnny Chen3e0571b2010-09-11 00:23:59 +0000697// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +0000698void
Greg Clayton238c0a12010-09-18 01:14:36 +0000699ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +0000700 const char *oneliner)
701{
702 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
703
704 // It's necessary to set both user_source and script_source to the oneliner.
705 // The former is used to generate callback description (as in breakpoint command list)
706 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +0000707
Johnny Chend1c2dca2010-09-10 18:21:10 +0000708 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +0000709
Caroline Tice5136f942010-09-27 21:35:15 +0000710 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
711 {
712 if (data_ap->script_source.GetSize() == 1)
713 {
714 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
715 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
716 }
717 }
718
Johnny Chend1c2dca2010-09-10 18:21:10 +0000719 return;
720}
721
Chris Lattner24943d22010-06-08 16:52:24 +0000722bool
723ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
724{
725 // Convert StringList to one long, newline delimited, const char *.
726 std::string function_def_string;
727
728 int num_lines = function_def.GetSize();
729
730 for (int i = 0; i < num_lines; ++i)
731 {
732 function_def_string.append (function_def.GetStringAtIndex(i));
733 if (function_def_string.at (function_def_string.length() - 1) != '\n')
734 function_def_string.append ("\n");
735
736 }
737
738 return ExecuteMultipleLines (function_def_string.c_str());
739}
740
741bool
742ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
743{
744 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000745 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000746 int num_lines = user_input.GetSize ();
747 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +0000748
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000749 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
750 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +0000751
Caroline Ticeb447e842010-09-21 19:25:28 +0000752
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000753 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
754 ++num_created_functions;
755 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +0000756
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000757 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +0000758 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +0000759
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000760 // Create the function name & definition string.
761
762 sstr.Printf ("def %s (frame, bp_loc):", auto_generated_function_name.c_str());
763 auto_generated_function.AppendString (sstr.GetData());
764
765 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +0000766
767 for (int i = 0; i < num_lines; ++i)
768 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000769 sstr.Clear ();
770 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
771 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +0000772 }
Chris Lattner24943d22010-06-08 16:52:24 +0000773
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000774 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +0000775
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000776 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +0000777 {
Caroline Ticeb447e842010-09-21 19:25:28 +0000778 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000779 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000780
781 // Store the name of the auto-generated function to be called.
782
783 callback_data.AppendString (auto_generated_function_name.c_str());
784 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000785}
786
Greg Clayton5144f382010-10-07 17:14:24 +0000787bool
788ScriptInterpreterPython::BreakpointCallbackFunction
789(
790 void *baton,
791 StoppointCallbackContext *context,
792 user_id_t break_id,
793 user_id_t break_loc_id
794)
795{
796 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
797 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
798
799 if (python_function_name != NULL
800 && python_function_name[0] != '\0')
801 {
802 Thread *thread = context->exe_ctx.thread;
803 Target *target = context->exe_ctx.target;
804 const StackFrameSP stop_frame_sp = thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame);
805 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
806 const BreakpointLocationSP bp_loc_sp = breakpoint_sp->FindLocationByID (break_loc_id);
807
808 SBFrame sb_frame (stop_frame_sp);
809 SBBreakpointLocation sb_bp_loc (bp_loc_sp);
810
811 if (sb_bp_loc.IsValid() || sb_frame.IsValid())
812 return LLDBSWIGPythonBreakpointCallbackFunction (python_function_name, sb_frame, sb_bp_loc);
813 }
814 // We currently always true so we stop in case anything goes wrong when
815 // trying to call the script function
816 return true;
817}