blob: ef472c385a0f45407929a6f843fb504baf38ef27 [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),
164 m_termios_valid (false)
165{
166
167 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000168
169 // Save terminal settings if we can
170 int input_fd;
171 FILE *input_fh = m_interpreter.GetDebugger().GetInputFileHandle();
172 if (input_fh != NULL)
173 input_fd = ::fileno (input_fh);
174 else
175 input_fd = STDIN_FILENO;
176
177 m_termios_valid = ::tcgetattr (input_fd, &m_termios) == 0;
178
Chris Lattner24943d22010-06-08 16:52:24 +0000179 // Find the module that owns this code and use that path we get to
180 // set the PYTHONPATH appropriately.
181
Greg Clayton24b48ff2010-10-17 22:03:32 +0000182 FileSpec file_spec;
183 char python_dir_path[PATH_MAX];
184 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +0000185 {
Greg Clayton24b48ff2010-10-17 22:03:32 +0000186 std::string python_path;
187 const char *curr_python_path = ::getenv ("PYTHONPATH");
188 if (curr_python_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000189 {
Greg Clayton24b48ff2010-10-17 22:03:32 +0000190 // We have a current value for PYTHONPATH, so lets append to it
191 python_path.append (curr_python_path);
Chris Lattner24943d22010-06-08 16:52:24 +0000192 }
Greg Clayton24b48ff2010-10-17 22:03:32 +0000193
194 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
195 {
196 if (!python_path.empty())
197 python_path.append (1, ':');
198 python_path.append (python_dir_path);
199 }
200
201 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
202 {
203 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
204 {
205 if (!python_path.empty())
206 python_path.append (1, ':');
207 python_path.append (python_dir_path);
208 }
209 }
210 const char *pathon_path_env_cstr = python_path.c_str();
211 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000212 }
213
214 Py_Initialize ();
215
Greg Clayton24b48ff2010-10-17 22:03:32 +0000216 PyObject *compiled_module = Py_CompileString (embedded_interpreter_string,
217 "embedded_interpreter.py",
Chris Lattner24943d22010-06-08 16:52:24 +0000218 Py_file_input);
219
Eli Friedman3c90d992010-06-09 18:31:38 +0000220 m_compiled_module = static_cast<void*>(compiled_module);
Chris Lattner24943d22010-06-08 16:52:24 +0000221
Greg Clayton121f3312010-07-07 18:40:03 +0000222 // This function is in the C++ output file generated by SWIG after it is
223 // run on all of the headers in "lldb/API/SB*.h"
Chris Lattner24943d22010-06-08 16:52:24 +0000224 init_lldb ();
225
226 // Update the path python uses to search for modules to include the current directory.
227
228 int success = PyRun_SimpleString ("import sys");
229 success = PyRun_SimpleString ("sys.path.append ('.')");
230 if (success == 0)
231 {
232 // Import the Script Bridge module.
Johnny Chen98bea862010-09-10 16:19:10 +0000233 success = PyRun_SimpleString ("import lldb");
Chris Lattner24943d22010-06-08 16:52:24 +0000234 }
235
236 const char *pty_slave_name = GetScriptInterpreterPtyName ();
Greg Clayton63094e02010-06-23 01:19:29 +0000237 FILE *out_fh = interpreter.GetDebugger().GetOutputFileHandle();
Chris Lattner24943d22010-06-08 16:52:24 +0000238
Caroline Tice5867f6b2010-10-18 18:24:17 +0000239 PyObject *pmod = PyImport_ExecCodeModule (const_cast<char*> ("embedded_interpreter"),
240 static_cast<PyObject*>(m_compiled_module));
241
Chris Lattner24943d22010-06-08 16:52:24 +0000242 if (pmod != NULL)
243 {
244 PyRun_SimpleString ("ConsoleDict = locals()");
245 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
246 PyRun_SimpleString ("import sys");
247 PyRun_SimpleString ("from termios import *");
Chris Lattner24943d22010-06-08 16:52:24 +0000248
Chris Lattner24943d22010-06-08 16:52:24 +0000249 if (out_fh != NULL)
250 {
251 PyObject *new_sysout = PyFile_FromFile (out_fh, (char *) "", (char *) "w",
252 _check_and_flush);
253 PyObject *sysmod = PyImport_AddModule ("sys");
254 PyObject *sysdict = PyModule_GetDict (sysmod);
255
256 if ((new_sysout != NULL)
257 && (sysmod != NULL)
258 && (sysdict != NULL))
259 {
260 PyDict_SetItemString (sysdict, "stdout", new_sysout);
261 }
262
263 if (PyErr_Occurred())
264 PyErr_Clear();
265 }
266
Caroline Tice5867f6b2010-10-18 18:24:17 +0000267 StreamString run_string;
268 run_string.Printf ("new_stdin = open('%s', 'r')", pty_slave_name);
269 PyRun_SimpleString (run_string.GetData());
270 PyRun_SimpleString ("sys.stdin = new_stdin");
271
Chris Lattner24943d22010-06-08 16:52:24 +0000272 PyRun_SimpleString ("new_mode = tcgetattr(new_stdin)");
273 PyRun_SimpleString ("new_mode[3] = new_mode[3] | ECHO | ICANON");
274 PyRun_SimpleString ("new_mode[6][VEOF] = 255");
275 PyRun_SimpleString ("tcsetattr (new_stdin, TCSANOW, new_mode)");
Caroline Tice558be582010-06-30 16:22:25 +0000276
277 run_string.Clear();
Johnny Chen98bea862010-09-10 16:19:10 +0000278 run_string.Printf ("lldb.debugger_unique_id = %d", interpreter.GetDebugger().GetID());
Caroline Tice558be582010-06-30 16:22:25 +0000279 PyRun_SimpleString (run_string.GetData());
Chris Lattner24943d22010-06-08 16:52:24 +0000280 }
281
282
Caroline Tice5867f6b2010-10-18 18:24:17 +0000283 // Restore terminal settings if they were validly saved
284 if (m_termios_valid)
285 {
286 ::tcsetattr (input_fd, TCSANOW, &m_termios);
287 }
Chris Lattner24943d22010-06-08 16:52:24 +0000288}
289
290ScriptInterpreterPython::~ScriptInterpreterPython ()
291{
Chris Lattner24943d22010-06-08 16:52:24 +0000292 Py_Finalize ();
293}
294
Johnny Chen60dde642010-07-30 22:33:14 +0000295bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000296ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000297{
Greg Clayton63094e02010-06-23 01:19:29 +0000298 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000299 {
Greg Clayton63094e02010-06-23 01:19:29 +0000300 int success;
301
Caroline Tice5867f6b2010-10-18 18:24:17 +0000302
303 // Save the current input file handle state before executing the command.
304 int input_fd;
305 struct termios tmp_termios;
306 bool valid_termios = false;
307 FILE *input_fh = m_interpreter.GetDebugger().GetInputFileHandle();
308 if (input_fh != NULL)
309 {
310 input_fd = ::fileno (input_fh);
311 valid_termios = ::tcgetattr (input_fd, &tmp_termios) == 0;
312 }
313
Greg Clayton63094e02010-06-23 01:19:29 +0000314 success = PyRun_SimpleString (command);
Johnny Chen60dde642010-07-30 22:33:14 +0000315 if (success == 0)
316 return true;
317
Caroline Tice5867f6b2010-10-18 18:24:17 +0000318 // Restore the input file handle state after executing the command.
319 if (valid_termios)
320 ::tcsetattr (input_fd, TCSANOW, &tmp_termios);
321
Johnny Chen60dde642010-07-30 22:33:14 +0000322 // The one-liner failed. Append the error message.
323 if (result)
324 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
325 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000326 }
Johnny Chen60dde642010-07-30 22:33:14 +0000327
328 if (result)
329 result->AppendError ("empty command passed to python\n");
330 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000331}
332
333
334
335size_t
336ScriptInterpreterPython::InputReaderCallback
337(
338 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000339 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000340 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000341 const char *bytes,
342 size_t bytes_len
343)
344{
345 if (baton == NULL)
346 return 0;
347
Greg Clayton63094e02010-06-23 01:19:29 +0000348 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Chris Lattner24943d22010-06-08 16:52:24 +0000349 switch (notification)
350 {
351 case eInputReaderActivate:
352 {
353 // Save terminal settings if we can
Caroline Ticec95c6d12010-09-14 22:49:06 +0000354 int input_fd;
Greg Clayton63094e02010-06-23 01:19:29 +0000355 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000356 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000357 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000358 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000359 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000360
Greg Clayton63094e02010-06-23 01:19:29 +0000361 script_interpreter->m_termios_valid = ::tcgetattr (input_fd, &script_interpreter->m_termios) == 0;
Greg Clayton24b48ff2010-10-17 22:03:32 +0000362
363 if (script_interpreter->m_termios_valid)
Chris Lattner24943d22010-06-08 16:52:24 +0000364 {
Greg Clayton24b48ff2010-10-17 22:03:32 +0000365 struct termios tmp_termios = script_interpreter->m_termios;
Chris Lattner24943d22010-06-08 16:52:24 +0000366 tmp_termios.c_cc[VEOF] = _POSIX_VDISABLE;
Greg Clayton63094e02010-06-23 01:19:29 +0000367 ::tcsetattr (input_fd, TCSANOW, &tmp_termios);
Chris Lattner24943d22010-06-08 16:52:24 +0000368 }
369 }
370 break;
371
372 case eInputReaderDeactivate:
373 break;
374
375 case eInputReaderReactivate:
376 break;
377
378 case eInputReaderGotToken:
379 if (bytes && bytes_len)
380 {
381 if ((int) bytes[0] == 4)
Greg Clayton63094e02010-06-23 01:19:29 +0000382 ::write (script_interpreter->GetMasterFileDescriptor(), "quit()", 6);
Chris Lattner24943d22010-06-08 16:52:24 +0000383 else
Greg Clayton63094e02010-06-23 01:19:29 +0000384 ::write (script_interpreter->GetMasterFileDescriptor(), bytes, bytes_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000385 }
Greg Clayton63094e02010-06-23 01:19:29 +0000386 ::write (script_interpreter->GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000387 break;
388
389 case eInputReaderDone:
390 // Send a control D to the script interpreter
391 //::write (interpreter->GetMasterFileDescriptor(), "\nquit()\n", strlen("\nquit()\n"));
392 // Write a newline out to the reader output
393 //::fwrite ("\n", 1, 1, out_fh);
394 // Restore terminal settings if they were validly saved
Greg Clayton63094e02010-06-23 01:19:29 +0000395 if (script_interpreter->m_termios_valid)
Chris Lattner24943d22010-06-08 16:52:24 +0000396 {
Caroline Ticec95c6d12010-09-14 22:49:06 +0000397 int input_fd;
398 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
399 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000400 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000401 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000402 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000403
404 ::tcsetattr (input_fd, TCSANOW, &script_interpreter->m_termios);
Chris Lattner24943d22010-06-08 16:52:24 +0000405 }
406 break;
407 }
408
409 return bytes_len;
410}
411
412
413void
Greg Clayton238c0a12010-09-18 01:14:36 +0000414ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000415{
416 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
417
Greg Clayton238c0a12010-09-18 01:14:36 +0000418 Debugger &debugger = m_interpreter.GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000419
420 // At the moment, the only time the debugger does not have an input file handle is when this is called
421 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
422 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
423 // do it.
424
425 if (debugger.GetInputFileHandle() == NULL)
426 return;
427
Greg Clayton63094e02010-06-23 01:19:29 +0000428 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000429 if (reader_sp)
430 {
431 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
432 this, // baton
433 eInputReaderGranularityLine, // token size, to pass to callback function
434 NULL, // end token
435 NULL, // prompt
436 true)); // echo input
437
438 if (error.Success())
439 {
Greg Clayton63094e02010-06-23 01:19:29 +0000440 debugger.PushInputReader (reader_sp);
Greg Clayton238c0a12010-09-18 01:14:36 +0000441 ExecuteOneLine ("run_python_interpreter(ConsoleDict)", NULL);
Greg Clayton63094e02010-06-23 01:19:29 +0000442 debugger.PopInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +0000443 }
444 }
445}
446
447bool
448ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
449 ScriptInterpreter::ReturnType return_type,
450 void *ret_value)
451{
452 PyObject *py_return = NULL;
453 PyObject *mainmod = PyImport_AddModule ("__main__");
454 PyObject *globals = PyModule_GetDict (mainmod);
455 PyObject *locals = globals;
456 PyObject *py_error = NULL;
457 bool ret_success;
458 int success;
459
460 if (in_string != NULL)
461 {
462 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
463 if (py_return == NULL)
464 {
465 py_error = PyErr_Occurred ();
466 if (py_error != NULL)
467 PyErr_Clear ();
468
469 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
470 }
471
472 if (py_return != NULL)
473 {
474 switch (return_type)
475 {
476 case eCharPtr: // "char *"
477 {
478 const char format[3] = "s#";
479 success = PyArg_Parse (py_return, format, (char **) &ret_value);
480 break;
481 }
482 case eBool:
483 {
484 const char format[2] = "b";
485 success = PyArg_Parse (py_return, format, (bool *) ret_value);
486 break;
487 }
488 case eShortInt:
489 {
490 const char format[2] = "h";
491 success = PyArg_Parse (py_return, format, (short *) ret_value);
492 break;
493 }
494 case eShortIntUnsigned:
495 {
496 const char format[2] = "H";
497 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
498 break;
499 }
500 case eInt:
501 {
502 const char format[2] = "i";
503 success = PyArg_Parse (py_return, format, (int *) ret_value);
504 break;
505 }
506 case eIntUnsigned:
507 {
508 const char format[2] = "I";
509 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
510 break;
511 }
512 case eLongInt:
513 {
514 const char format[2] = "l";
515 success = PyArg_Parse (py_return, format, (long *) ret_value);
516 break;
517 }
518 case eLongIntUnsigned:
519 {
520 const char format[2] = "k";
521 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
522 break;
523 }
524 case eLongLong:
525 {
526 const char format[2] = "L";
527 success = PyArg_Parse (py_return, format, (long long *) ret_value);
528 break;
529 }
530 case eLongLongUnsigned:
531 {
532 const char format[2] = "K";
533 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
534 break;
535 }
536 case eFloat:
537 {
538 const char format[2] = "f";
539 success = PyArg_Parse (py_return, format, (float *) ret_value);
540 break;
541 }
542 case eDouble:
543 {
544 const char format[2] = "d";
545 success = PyArg_Parse (py_return, format, (double *) ret_value);
546 break;
547 }
548 case eChar:
549 {
550 const char format[2] = "c";
551 success = PyArg_Parse (py_return, format, (char *) ret_value);
552 break;
553 }
554 default:
555 {}
556 }
557 Py_DECREF (py_return);
558 if (success)
559 ret_success = true;
560 else
561 ret_success = false;
562 }
563 }
564
565 py_error = PyErr_Occurred();
566 if (py_error != NULL)
567 {
568 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
569 PyErr_Print ();
570 PyErr_Clear();
571 ret_success = false;
572 }
573
574 return ret_success;
575}
576
577bool
578ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
579{
580 bool success = false;
581 PyObject *py_return = NULL;
582 PyObject *mainmod = PyImport_AddModule ("__main__");
583 PyObject *globals = PyModule_GetDict (mainmod);
584 PyObject *locals = globals;
585 PyObject *py_error = NULL;
586
587 if (in_string != NULL)
588 {
589 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
590 if (compiled_node)
591 {
592 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
593 if (compiled_code)
594 {
595 py_return = PyEval_EvalCode (compiled_code, globals, locals);
596 if (py_return != NULL)
597 {
598 success = true;
599 Py_DECREF (py_return);
600 }
601 }
602 }
603 }
604
605 py_error = PyErr_Occurred ();
606 if (py_error != NULL)
607 {
608 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
609 PyErr_Print ();
610 PyErr_Clear();
611 success = false;
612 }
613
614 return success;
615}
616
617static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
618
619size_t
620ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
621(
622 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000623 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000624 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000625 const char *bytes,
626 size_t bytes_len
627)
628{
629 static StringList commands_in_progress;
630
Greg Clayton63094e02010-06-23 01:19:29 +0000631 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000632 if (out_fh == NULL)
633 out_fh = stdout;
634
Chris Lattner24943d22010-06-08 16:52:24 +0000635 switch (notification)
636 {
637 case eInputReaderActivate:
638 {
639 commands_in_progress.Clear();
640 if (out_fh)
641 {
642 ::fprintf (out_fh, "%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000643 if (reader.GetPrompt())
644 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +0000645 ::fflush (out_fh);
Chris Lattner24943d22010-06-08 16:52:24 +0000646 }
647 }
648 break;
649
650 case eInputReaderDeactivate:
651 break;
652
653 case eInputReaderReactivate:
Greg Clayton63094e02010-06-23 01:19:29 +0000654 if (reader.GetPrompt() && out_fh)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000655 {
Greg Clayton63094e02010-06-23 01:19:29 +0000656 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +0000657 ::fflush (out_fh);
658 }
Chris Lattner24943d22010-06-08 16:52:24 +0000659 break;
660
661 case eInputReaderGotToken:
662 {
663 std::string temp_string (bytes, bytes_len);
664 commands_in_progress.AppendString (temp_string.c_str());
Greg Clayton63094e02010-06-23 01:19:29 +0000665 if (out_fh && !reader.IsDone() && reader.GetPrompt())
Caroline Ticef81b4c52010-10-27 18:34:42 +0000666 {
Greg Clayton63094e02010-06-23 01:19:29 +0000667 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +0000668 ::fflush (out_fh);
669 }
Chris Lattner24943d22010-06-08 16:52:24 +0000670 }
671 break;
672
673 case eInputReaderDone:
674 {
675 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
676 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
677 data_ap->user_source.AppendList (commands_in_progress);
678 if (data_ap.get())
679 {
Greg Clayton63094e02010-06-23 01:19:29 +0000680 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +0000681 if (interpreter)
682 {
683 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
684 data_ap->script_source))
685 {
686 if (data_ap->script_source.GetSize() == 1)
687 {
688 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
689 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
690 }
691 }
Caroline Ticeb447e842010-09-21 19:25:28 +0000692 else
Caroline Tice5136f942010-09-27 21:35:15 +0000693 ::fprintf (out_fh, "Warning: No command attached to breakpoint.\n");
Chris Lattner24943d22010-06-08 16:52:24 +0000694 }
695 else
696 {
697 // FIXME: Error processing.
698 }
699 }
700 }
701 break;
702
703 }
704
705 return bytes_len;
706}
707
708void
Greg Clayton238c0a12010-09-18 01:14:36 +0000709ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +0000710 CommandReturnObject &result)
711{
Greg Clayton238c0a12010-09-18 01:14:36 +0000712 Debugger &debugger = m_interpreter.GetDebugger();
Greg Clayton63094e02010-06-23 01:19:29 +0000713 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000714
715 if (reader_sp)
716 {
717 Error err = reader_sp->Initialize (
718 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
719 bp_options, // baton
720 eInputReaderGranularityLine, // token size, for feeding data to callback function
721 "DONE", // end token
722 "> ", // prompt
723 true); // echo input
724
725 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +0000726 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +0000727 else
728 {
729 result.AppendError (err.AsCString());
730 result.SetStatus (eReturnStatusFailed);
731 }
732 }
733 else
734 {
735 result.AppendError("out of memory");
736 result.SetStatus (eReturnStatusFailed);
737 }
738}
739
Johnny Chen3e0571b2010-09-11 00:23:59 +0000740// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +0000741void
Greg Clayton238c0a12010-09-18 01:14:36 +0000742ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +0000743 const char *oneliner)
744{
745 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
746
747 // It's necessary to set both user_source and script_source to the oneliner.
748 // The former is used to generate callback description (as in breakpoint command list)
749 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +0000750
Johnny Chend1c2dca2010-09-10 18:21:10 +0000751 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +0000752
Caroline Tice5136f942010-09-27 21:35:15 +0000753 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
754 {
755 if (data_ap->script_source.GetSize() == 1)
756 {
757 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
758 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
759 }
760 }
761
Johnny Chend1c2dca2010-09-10 18:21:10 +0000762 return;
763}
764
Chris Lattner24943d22010-06-08 16:52:24 +0000765bool
766ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
767{
768 // Convert StringList to one long, newline delimited, const char *.
769 std::string function_def_string;
770
771 int num_lines = function_def.GetSize();
772
773 for (int i = 0; i < num_lines; ++i)
774 {
775 function_def_string.append (function_def.GetStringAtIndex(i));
776 if (function_def_string.at (function_def_string.length() - 1) != '\n')
777 function_def_string.append ("\n");
778
779 }
780
781 return ExecuteMultipleLines (function_def_string.c_str());
782}
783
784bool
785ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
786{
787 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000788 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000789 int num_lines = user_input.GetSize ();
790 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +0000791
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000792 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
793 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +0000794
Caroline Ticeb447e842010-09-21 19:25:28 +0000795
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000796 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
797 ++num_created_functions;
798 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +0000799
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000800 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +0000801 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +0000802
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000803 // Create the function name & definition string.
804
805 sstr.Printf ("def %s (frame, bp_loc):", auto_generated_function_name.c_str());
806 auto_generated_function.AppendString (sstr.GetData());
807
808 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +0000809
810 for (int i = 0; i < num_lines; ++i)
811 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000812 sstr.Clear ();
813 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
814 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +0000815 }
Chris Lattner24943d22010-06-08 16:52:24 +0000816
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000817 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +0000818
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000819 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +0000820 {
Caroline Ticeb447e842010-09-21 19:25:28 +0000821 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000822 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000823
824 // Store the name of the auto-generated function to be called.
825
826 callback_data.AppendString (auto_generated_function_name.c_str());
827 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000828}
829
Greg Clayton5144f382010-10-07 17:14:24 +0000830bool
831ScriptInterpreterPython::BreakpointCallbackFunction
832(
833 void *baton,
834 StoppointCallbackContext *context,
835 user_id_t break_id,
836 user_id_t break_loc_id
837)
838{
839 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
840 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
841
842 if (python_function_name != NULL
843 && python_function_name[0] != '\0')
844 {
845 Thread *thread = context->exe_ctx.thread;
846 Target *target = context->exe_ctx.target;
847 const StackFrameSP stop_frame_sp = thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame);
848 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
849 const BreakpointLocationSP bp_loc_sp = breakpoint_sp->FindLocationByID (break_loc_id);
850
851 SBFrame sb_frame (stop_frame_sp);
852 SBBreakpointLocation sb_bp_loc (bp_loc_sp);
853
854 if (sb_bp_loc.IsValid() || sb_frame.IsValid())
855 return LLDBSWIGPythonBreakpointCallbackFunction (python_function_name, sb_frame, sb_bp_loc);
856 }
857 // We currently always true so we stop in case anything goes wrong when
858 // trying to call the script function
859 return true;
860}