blob: a2c31165ae83df88b56f5222c93a06677cf91596 [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
Caroline Tice558be582010-06-30 16:22:25 +0000275 run_string.Clear();
Johnny Chen98bea862010-09-10 16:19:10 +0000276 run_string.Printf ("lldb.debugger_unique_id = %d", interpreter.GetDebugger().GetID());
Caroline Tice558be582010-06-30 16:22:25 +0000277 PyRun_SimpleString (run_string.GetData());
Chris Lattner24943d22010-06-08 16:52:24 +0000278 }
279
280
Caroline Tice5867f6b2010-10-18 18:24:17 +0000281 // Restore terminal settings if they were validly saved
282 if (m_termios_valid)
283 {
284 ::tcsetattr (input_fd, TCSANOW, &m_termios);
285 }
Chris Lattner24943d22010-06-08 16:52:24 +0000286}
287
288ScriptInterpreterPython::~ScriptInterpreterPython ()
289{
Chris Lattner24943d22010-06-08 16:52:24 +0000290 Py_Finalize ();
291}
292
Johnny Chen60dde642010-07-30 22:33:14 +0000293bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000294ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000295{
Greg Clayton63094e02010-06-23 01:19:29 +0000296 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000297 {
Greg Clayton63094e02010-06-23 01:19:29 +0000298 int success;
299
300 success = PyRun_SimpleString (command);
Johnny Chen60dde642010-07-30 22:33:14 +0000301 if (success == 0)
302 return true;
303
304 // The one-liner failed. Append the error message.
305 if (result)
306 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
307 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000308 }
Johnny Chen60dde642010-07-30 22:33:14 +0000309
310 if (result)
311 result->AppendError ("empty command passed to python\n");
312 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000313}
314
315
316
317size_t
318ScriptInterpreterPython::InputReaderCallback
319(
320 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000321 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000322 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000323 const char *bytes,
324 size_t bytes_len
325)
326{
Caroline Tice2ade6112010-11-10 19:18:14 +0000327 lldb::thread_t embedded_interpreter_thread;
328 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
329
Chris Lattner24943d22010-06-08 16:52:24 +0000330 if (baton == NULL)
331 return 0;
332
Caroline Tice67637d82010-12-15 19:51:12 +0000333 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle ();
334 if (out_fh == NULL)
335 out_fh = stdout;
336
Greg Clayton63094e02010-06-23 01:19:29 +0000337 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Chris Lattner24943d22010-06-08 16:52:24 +0000338 switch (notification)
339 {
340 case eInputReaderActivate:
341 {
Caroline Tice67637d82010-12-15 19:51:12 +0000342 if (out_fh)
343 {
344 ::fprintf (out_fh, "Python Interactive Interpreter. To exit Python, type 'quit()' or 'exit()'.\n");
345 ::fprintf (out_fh, "Do NOT use Ctrl-D (EOF) to exit, as that will cause the lldb debugger to hang.\n");
346 }
Chris Lattner24943d22010-06-08 16:52:24 +0000347 // Save terminal settings if we can
Caroline Ticec95c6d12010-09-14 22:49:06 +0000348 int input_fd;
Greg Clayton63094e02010-06-23 01:19:29 +0000349 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000350 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000351 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000352 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000353 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000354
Greg Clayton63094e02010-06-23 01:19:29 +0000355 script_interpreter->m_termios_valid = ::tcgetattr (input_fd, &script_interpreter->m_termios) == 0;
Greg Clayton24b48ff2010-10-17 22:03:32 +0000356
Caroline Tice2ade6112010-11-10 19:18:14 +0000357 char error_str[1024];
358 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
359 sizeof(error_str)))
360 {
361 if (log)
362 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
363 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
364 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
365 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
366 script_interpreter, NULL);
367 if (embedded_interpreter_thread != LLDB_INVALID_HOST_THREAD)
368 {
369 if (log)
370 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
371 Error detach_error;
372 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
373 }
374 else
375 {
376 if (log)
377 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
378 reader.SetIsDone (true);
379 }
380 }
381 else
382 {
383 if (log)
384 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
385 reader.SetIsDone (true);
386 }
387
Chris Lattner24943d22010-06-08 16:52:24 +0000388 }
389 break;
390
391 case eInputReaderDeactivate:
392 break;
393
394 case eInputReaderReactivate:
395 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000396
397 case eInputReaderInterrupt:
398 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
399 break;
400
401 case eInputReaderEndOfFile:
402 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
403 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000404
405 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000406 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000407 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000408 if (log)
409 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
410 bytes_len);
411 if (bytes && bytes_len)
412 {
413 if ((int) bytes[0] == 4)
414 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
415 else
416 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
417 }
418 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000419 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000420 else
421 {
422 if (log)
423 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
424 bytes,
425 bytes_len);
426 reader.SetIsDone (true);
427 }
428
Chris Lattner24943d22010-06-08 16:52:24 +0000429 break;
430
431 case eInputReaderDone:
432 // Send a control D to the script interpreter
433 //::write (interpreter->GetMasterFileDescriptor(), "\nquit()\n", strlen("\nquit()\n"));
434 // Write a newline out to the reader output
435 //::fwrite ("\n", 1, 1, out_fh);
436 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000437 if (log)
438 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Greg Clayton63094e02010-06-23 01:19:29 +0000439 if (script_interpreter->m_termios_valid)
Chris Lattner24943d22010-06-08 16:52:24 +0000440 {
Caroline Ticec95c6d12010-09-14 22:49:06 +0000441 int input_fd;
442 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
443 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000444 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000445 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000446 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000447
448 ::tcsetattr (input_fd, TCSANOW, &script_interpreter->m_termios);
Chris Lattner24943d22010-06-08 16:52:24 +0000449 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000450 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000451 break;
452 }
453
454 return bytes_len;
455}
456
457
458void
Greg Clayton238c0a12010-09-18 01:14:36 +0000459ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000460{
461 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
462
Greg Clayton238c0a12010-09-18 01:14:36 +0000463 Debugger &debugger = m_interpreter.GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000464
465 // At the moment, the only time the debugger does not have an input file handle is when this is called
466 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
467 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
468 // do it.
469
470 if (debugger.GetInputFileHandle() == NULL)
471 return;
472
Greg Clayton63094e02010-06-23 01:19:29 +0000473 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000474 if (reader_sp)
475 {
476 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
477 this, // baton
478 eInputReaderGranularityLine, // token size, to pass to callback function
479 NULL, // end token
480 NULL, // prompt
481 true)); // echo input
482
483 if (error.Success())
484 {
Greg Clayton63094e02010-06-23 01:19:29 +0000485 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000486 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000487 }
488 }
489}
490
491bool
492ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
493 ScriptInterpreter::ReturnType return_type,
494 void *ret_value)
495{
496 PyObject *py_return = NULL;
497 PyObject *mainmod = PyImport_AddModule ("__main__");
498 PyObject *globals = PyModule_GetDict (mainmod);
499 PyObject *locals = globals;
500 PyObject *py_error = NULL;
501 bool ret_success;
502 int success;
503
504 if (in_string != NULL)
505 {
506 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
507 if (py_return == NULL)
508 {
509 py_error = PyErr_Occurred ();
510 if (py_error != NULL)
511 PyErr_Clear ();
512
513 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
514 }
515
516 if (py_return != NULL)
517 {
518 switch (return_type)
519 {
520 case eCharPtr: // "char *"
521 {
522 const char format[3] = "s#";
523 success = PyArg_Parse (py_return, format, (char **) &ret_value);
524 break;
525 }
526 case eBool:
527 {
528 const char format[2] = "b";
529 success = PyArg_Parse (py_return, format, (bool *) ret_value);
530 break;
531 }
532 case eShortInt:
533 {
534 const char format[2] = "h";
535 success = PyArg_Parse (py_return, format, (short *) ret_value);
536 break;
537 }
538 case eShortIntUnsigned:
539 {
540 const char format[2] = "H";
541 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
542 break;
543 }
544 case eInt:
545 {
546 const char format[2] = "i";
547 success = PyArg_Parse (py_return, format, (int *) ret_value);
548 break;
549 }
550 case eIntUnsigned:
551 {
552 const char format[2] = "I";
553 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
554 break;
555 }
556 case eLongInt:
557 {
558 const char format[2] = "l";
559 success = PyArg_Parse (py_return, format, (long *) ret_value);
560 break;
561 }
562 case eLongIntUnsigned:
563 {
564 const char format[2] = "k";
565 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
566 break;
567 }
568 case eLongLong:
569 {
570 const char format[2] = "L";
571 success = PyArg_Parse (py_return, format, (long long *) ret_value);
572 break;
573 }
574 case eLongLongUnsigned:
575 {
576 const char format[2] = "K";
577 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
578 break;
579 }
580 case eFloat:
581 {
582 const char format[2] = "f";
583 success = PyArg_Parse (py_return, format, (float *) ret_value);
584 break;
585 }
586 case eDouble:
587 {
588 const char format[2] = "d";
589 success = PyArg_Parse (py_return, format, (double *) ret_value);
590 break;
591 }
592 case eChar:
593 {
594 const char format[2] = "c";
595 success = PyArg_Parse (py_return, format, (char *) ret_value);
596 break;
597 }
598 default:
599 {}
600 }
601 Py_DECREF (py_return);
602 if (success)
603 ret_success = true;
604 else
605 ret_success = false;
606 }
607 }
608
609 py_error = PyErr_Occurred();
610 if (py_error != NULL)
611 {
612 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
613 PyErr_Print ();
614 PyErr_Clear();
615 ret_success = false;
616 }
617
618 return ret_success;
619}
620
621bool
622ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
623{
624 bool success = false;
625 PyObject *py_return = NULL;
626 PyObject *mainmod = PyImport_AddModule ("__main__");
627 PyObject *globals = PyModule_GetDict (mainmod);
628 PyObject *locals = globals;
629 PyObject *py_error = NULL;
630
631 if (in_string != NULL)
632 {
633 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
634 if (compiled_node)
635 {
636 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
637 if (compiled_code)
638 {
639 py_return = PyEval_EvalCode (compiled_code, globals, locals);
640 if (py_return != NULL)
641 {
642 success = true;
643 Py_DECREF (py_return);
644 }
645 }
646 }
647 }
648
649 py_error = PyErr_Occurred ();
650 if (py_error != NULL)
651 {
652 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
653 PyErr_Print ();
654 PyErr_Clear();
655 success = false;
656 }
657
658 return success;
659}
660
661static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
662
663size_t
664ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
665(
666 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000667 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000668 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000669 const char *bytes,
670 size_t bytes_len
671)
672{
673 static StringList commands_in_progress;
674
Greg Clayton63094e02010-06-23 01:19:29 +0000675 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000676 if (out_fh == NULL)
677 out_fh = stdout;
678
Chris Lattner24943d22010-06-08 16:52:24 +0000679 switch (notification)
680 {
681 case eInputReaderActivate:
682 {
683 commands_in_progress.Clear();
684 if (out_fh)
685 {
686 ::fprintf (out_fh, "%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000687 if (reader.GetPrompt())
688 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +0000689 ::fflush (out_fh);
Chris Lattner24943d22010-06-08 16:52:24 +0000690 }
691 }
692 break;
693
694 case eInputReaderDeactivate:
695 break;
696
697 case eInputReaderReactivate:
Greg Clayton63094e02010-06-23 01:19:29 +0000698 if (reader.GetPrompt() && out_fh)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000699 {
Greg Clayton63094e02010-06-23 01:19:29 +0000700 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +0000701 ::fflush (out_fh);
702 }
Chris Lattner24943d22010-06-08 16:52:24 +0000703 break;
704
705 case eInputReaderGotToken:
706 {
707 std::string temp_string (bytes, bytes_len);
708 commands_in_progress.AppendString (temp_string.c_str());
Greg Clayton63094e02010-06-23 01:19:29 +0000709 if (out_fh && !reader.IsDone() && reader.GetPrompt())
Caroline Ticef81b4c52010-10-27 18:34:42 +0000710 {
Greg Clayton63094e02010-06-23 01:19:29 +0000711 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +0000712 ::fflush (out_fh);
713 }
Chris Lattner24943d22010-06-08 16:52:24 +0000714 }
715 break;
716
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000717 case eInputReaderEndOfFile:
718 case eInputReaderInterrupt:
719 // Control-c (SIGINT) & control-d both mean finish & exit.
720 reader.SetIsDone(true);
721
722 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
723 if (notification == eInputReaderInterrupt)
724 commands_in_progress.Clear();
725
726 // Fall through here...
727
Chris Lattner24943d22010-06-08 16:52:24 +0000728 case eInputReaderDone:
729 {
730 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
731 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
732 data_ap->user_source.AppendList (commands_in_progress);
733 if (data_ap.get())
734 {
Greg Clayton63094e02010-06-23 01:19:29 +0000735 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +0000736 if (interpreter)
737 {
738 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
739 data_ap->script_source))
740 {
741 if (data_ap->script_source.GetSize() == 1)
742 {
743 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
744 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
745 }
746 }
Caroline Ticeb447e842010-09-21 19:25:28 +0000747 else
Caroline Tice5136f942010-09-27 21:35:15 +0000748 ::fprintf (out_fh, "Warning: No command attached to breakpoint.\n");
Chris Lattner24943d22010-06-08 16:52:24 +0000749 }
750 else
751 {
752 // FIXME: Error processing.
753 }
754 }
755 }
756 break;
757
758 }
759
760 return bytes_len;
761}
762
763void
Greg Clayton238c0a12010-09-18 01:14:36 +0000764ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +0000765 CommandReturnObject &result)
766{
Greg Clayton238c0a12010-09-18 01:14:36 +0000767 Debugger &debugger = m_interpreter.GetDebugger();
Greg Clayton63094e02010-06-23 01:19:29 +0000768 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000769
770 if (reader_sp)
771 {
772 Error err = reader_sp->Initialize (
773 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
774 bp_options, // baton
775 eInputReaderGranularityLine, // token size, for feeding data to callback function
776 "DONE", // end token
777 "> ", // prompt
778 true); // echo input
779
780 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +0000781 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +0000782 else
783 {
784 result.AppendError (err.AsCString());
785 result.SetStatus (eReturnStatusFailed);
786 }
787 }
788 else
789 {
790 result.AppendError("out of memory");
791 result.SetStatus (eReturnStatusFailed);
792 }
793}
794
Johnny Chen3e0571b2010-09-11 00:23:59 +0000795// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +0000796void
Greg Clayton238c0a12010-09-18 01:14:36 +0000797ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +0000798 const char *oneliner)
799{
800 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
801
802 // It's necessary to set both user_source and script_source to the oneliner.
803 // The former is used to generate callback description (as in breakpoint command list)
804 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +0000805
Johnny Chend1c2dca2010-09-10 18:21:10 +0000806 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +0000807
Caroline Tice5136f942010-09-27 21:35:15 +0000808 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
809 {
810 if (data_ap->script_source.GetSize() == 1)
811 {
812 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
813 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
814 }
815 }
816
Johnny Chend1c2dca2010-09-10 18:21:10 +0000817 return;
818}
819
Chris Lattner24943d22010-06-08 16:52:24 +0000820bool
821ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
822{
823 // Convert StringList to one long, newline delimited, const char *.
824 std::string function_def_string;
825
826 int num_lines = function_def.GetSize();
827
828 for (int i = 0; i < num_lines; ++i)
829 {
830 function_def_string.append (function_def.GetStringAtIndex(i));
831 if (function_def_string.at (function_def_string.length() - 1) != '\n')
832 function_def_string.append ("\n");
833
834 }
835
836 return ExecuteMultipleLines (function_def_string.c_str());
837}
838
839bool
840ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
841{
842 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000843 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000844 int num_lines = user_input.GetSize ();
845 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +0000846
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000847 // Check to see if we have any data; if not, just return.
848 if (user_input.GetSize() == 0)
849 return false;
850
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000851 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
852 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +0000853
Caroline Ticeb447e842010-09-21 19:25:28 +0000854
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000855 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
856 ++num_created_functions;
857 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +0000858
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000859 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +0000860 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +0000861
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000862 // Create the function name & definition string.
863
864 sstr.Printf ("def %s (frame, bp_loc):", auto_generated_function_name.c_str());
865 auto_generated_function.AppendString (sstr.GetData());
866
867 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +0000868
869 for (int i = 0; i < num_lines; ++i)
870 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000871 sstr.Clear ();
872 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
873 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +0000874 }
Chris Lattner24943d22010-06-08 16:52:24 +0000875
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000876 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +0000877
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000878 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +0000879 {
Caroline Ticeb447e842010-09-21 19:25:28 +0000880 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000881 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000882
883 // Store the name of the auto-generated function to be called.
884
885 callback_data.AppendString (auto_generated_function_name.c_str());
886 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000887}
888
Greg Clayton5144f382010-10-07 17:14:24 +0000889bool
890ScriptInterpreterPython::BreakpointCallbackFunction
891(
892 void *baton,
893 StoppointCallbackContext *context,
894 user_id_t break_id,
895 user_id_t break_loc_id
896)
897{
898 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
899 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
900
901 if (python_function_name != NULL
902 && python_function_name[0] != '\0')
903 {
904 Thread *thread = context->exe_ctx.thread;
905 Target *target = context->exe_ctx.target;
906 const StackFrameSP stop_frame_sp = thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame);
907 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
908 const BreakpointLocationSP bp_loc_sp = breakpoint_sp->FindLocationByID (break_loc_id);
909
910 SBFrame sb_frame (stop_frame_sp);
911 SBBreakpointLocation sb_bp_loc (bp_loc_sp);
912
913 if (sb_bp_loc.IsValid() || sb_frame.IsValid())
914 return LLDBSWIGPythonBreakpointCallbackFunction (python_function_name, sb_frame, sb_bp_loc);
915 }
916 // We currently always true so we stop in case anything goes wrong when
917 // trying to call the script function
918 return true;
919}
Caroline Tice2ade6112010-11-10 19:18:14 +0000920
921lldb::thread_result_t
922ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
923{
924 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
925
926 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
927
928 if (log)
929 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
930
931 char error_str[1024];
932 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
933 if (pty_slave_name != NULL)
934 {
935 StreamString run_string;
936 PyRun_SimpleString ("save_stderr = sys.stderr");
937 PyRun_SimpleString ("sys.stderr = sys.stdout");
938 PyRun_SimpleString ("save_stdin = sys.stdin");
939 run_string.Printf ("sys.stdin = open ('%s', 'r')", pty_slave_name);
940 PyRun_SimpleString (run_string.GetData());
Caroline Tice2ade6112010-11-10 19:18:14 +0000941
942 // The following call drops into the embedded interpreter loop and stays there until the
943 // user chooses to exit from the Python interpreter.
944 script_interpreter->ExecuteOneLine ("run_python_interpreter(ConsoleDict)", NULL);
945
946 PyRun_SimpleString ("sys.stdin = save_stdin");
947 PyRun_SimpleString ("sys.stderr = save_stderr");
948 }
949
950 if (script_interpreter->m_embedded_thread_input_reader_sp)
951 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
952
953 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
954
955 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
956 if (log)
957 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
958
959
960 // Clean up the input reader and make the debugger pop it off the stack.
961 Debugger &debugger = script_interpreter->m_interpreter.GetDebugger();
962 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
963 script_interpreter->m_embedded_thread_input_reader_sp.reset();
964 debugger.PopInputReader (reader_sp);
965
966 return NULL;
967}
968
969
970