blob: 1e3a308e83c8d79b1d5fc7c9b75eb53dac11256a [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
Greg Clayton63094e02010-06-23 01:19:29 +0000333 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Chris Lattner24943d22010-06-08 16:52:24 +0000334 switch (notification)
335 {
336 case eInputReaderActivate:
337 {
338 // Save terminal settings if we can
Caroline Ticec95c6d12010-09-14 22:49:06 +0000339 int input_fd;
Greg Clayton63094e02010-06-23 01:19:29 +0000340 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000341 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000342 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000343 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000344 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000345
Greg Clayton63094e02010-06-23 01:19:29 +0000346 script_interpreter->m_termios_valid = ::tcgetattr (input_fd, &script_interpreter->m_termios) == 0;
Greg Clayton24b48ff2010-10-17 22:03:32 +0000347
Caroline Tice2ade6112010-11-10 19:18:14 +0000348 char error_str[1024];
349 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
350 sizeof(error_str)))
351 {
352 if (log)
353 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
354 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
355 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
356 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
357 script_interpreter, NULL);
358 if (embedded_interpreter_thread != LLDB_INVALID_HOST_THREAD)
359 {
360 if (log)
361 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
362 Error detach_error;
363 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
364 }
365 else
366 {
367 if (log)
368 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
369 reader.SetIsDone (true);
370 }
371 }
372 else
373 {
374 if (log)
375 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
376 reader.SetIsDone (true);
377 }
378
Chris Lattner24943d22010-06-08 16:52:24 +0000379 }
380 break;
381
382 case eInputReaderDeactivate:
383 break;
384
385 case eInputReaderReactivate:
386 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000387
388 case eInputReaderInterrupt:
389 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
390 break;
391
392 case eInputReaderEndOfFile:
393 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
394 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000395
396 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000397 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000398 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000399 if (log)
400 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
401 bytes_len);
402 if (bytes && bytes_len)
403 {
404 if ((int) bytes[0] == 4)
405 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
406 else
407 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
408 }
409 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000410 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000411 else
412 {
413 if (log)
414 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
415 bytes,
416 bytes_len);
417 reader.SetIsDone (true);
418 }
419
Chris Lattner24943d22010-06-08 16:52:24 +0000420 break;
421
422 case eInputReaderDone:
423 // Send a control D to the script interpreter
424 //::write (interpreter->GetMasterFileDescriptor(), "\nquit()\n", strlen("\nquit()\n"));
425 // Write a newline out to the reader output
426 //::fwrite ("\n", 1, 1, out_fh);
427 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000428 if (log)
429 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Greg Clayton63094e02010-06-23 01:19:29 +0000430 if (script_interpreter->m_termios_valid)
Chris Lattner24943d22010-06-08 16:52:24 +0000431 {
Caroline Ticec95c6d12010-09-14 22:49:06 +0000432 int input_fd;
433 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
434 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000435 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000436 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000437 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000438
439 ::tcsetattr (input_fd, TCSANOW, &script_interpreter->m_termios);
Chris Lattner24943d22010-06-08 16:52:24 +0000440 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000441 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000442 break;
443 }
444
445 return bytes_len;
446}
447
448
449void
Greg Clayton238c0a12010-09-18 01:14:36 +0000450ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000451{
452 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
453
Greg Clayton238c0a12010-09-18 01:14:36 +0000454 Debugger &debugger = m_interpreter.GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000455
456 // At the moment, the only time the debugger does not have an input file handle is when this is called
457 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
458 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
459 // do it.
460
461 if (debugger.GetInputFileHandle() == NULL)
462 return;
463
Greg Clayton63094e02010-06-23 01:19:29 +0000464 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000465 if (reader_sp)
466 {
467 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
468 this, // baton
469 eInputReaderGranularityLine, // token size, to pass to callback function
470 NULL, // end token
471 NULL, // prompt
472 true)); // echo input
473
474 if (error.Success())
475 {
Greg Clayton63094e02010-06-23 01:19:29 +0000476 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000477 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000478 }
479 }
480}
481
482bool
483ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
484 ScriptInterpreter::ReturnType return_type,
485 void *ret_value)
486{
487 PyObject *py_return = NULL;
488 PyObject *mainmod = PyImport_AddModule ("__main__");
489 PyObject *globals = PyModule_GetDict (mainmod);
490 PyObject *locals = globals;
491 PyObject *py_error = NULL;
492 bool ret_success;
493 int success;
494
495 if (in_string != NULL)
496 {
497 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
498 if (py_return == NULL)
499 {
500 py_error = PyErr_Occurred ();
501 if (py_error != NULL)
502 PyErr_Clear ();
503
504 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
505 }
506
507 if (py_return != NULL)
508 {
509 switch (return_type)
510 {
511 case eCharPtr: // "char *"
512 {
513 const char format[3] = "s#";
514 success = PyArg_Parse (py_return, format, (char **) &ret_value);
515 break;
516 }
517 case eBool:
518 {
519 const char format[2] = "b";
520 success = PyArg_Parse (py_return, format, (bool *) ret_value);
521 break;
522 }
523 case eShortInt:
524 {
525 const char format[2] = "h";
526 success = PyArg_Parse (py_return, format, (short *) ret_value);
527 break;
528 }
529 case eShortIntUnsigned:
530 {
531 const char format[2] = "H";
532 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
533 break;
534 }
535 case eInt:
536 {
537 const char format[2] = "i";
538 success = PyArg_Parse (py_return, format, (int *) ret_value);
539 break;
540 }
541 case eIntUnsigned:
542 {
543 const char format[2] = "I";
544 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
545 break;
546 }
547 case eLongInt:
548 {
549 const char format[2] = "l";
550 success = PyArg_Parse (py_return, format, (long *) ret_value);
551 break;
552 }
553 case eLongIntUnsigned:
554 {
555 const char format[2] = "k";
556 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
557 break;
558 }
559 case eLongLong:
560 {
561 const char format[2] = "L";
562 success = PyArg_Parse (py_return, format, (long long *) ret_value);
563 break;
564 }
565 case eLongLongUnsigned:
566 {
567 const char format[2] = "K";
568 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
569 break;
570 }
571 case eFloat:
572 {
573 const char format[2] = "f";
574 success = PyArg_Parse (py_return, format, (float *) ret_value);
575 break;
576 }
577 case eDouble:
578 {
579 const char format[2] = "d";
580 success = PyArg_Parse (py_return, format, (double *) ret_value);
581 break;
582 }
583 case eChar:
584 {
585 const char format[2] = "c";
586 success = PyArg_Parse (py_return, format, (char *) ret_value);
587 break;
588 }
589 default:
590 {}
591 }
592 Py_DECREF (py_return);
593 if (success)
594 ret_success = true;
595 else
596 ret_success = false;
597 }
598 }
599
600 py_error = PyErr_Occurred();
601 if (py_error != NULL)
602 {
603 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
604 PyErr_Print ();
605 PyErr_Clear();
606 ret_success = false;
607 }
608
609 return ret_success;
610}
611
612bool
613ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
614{
615 bool success = false;
616 PyObject *py_return = NULL;
617 PyObject *mainmod = PyImport_AddModule ("__main__");
618 PyObject *globals = PyModule_GetDict (mainmod);
619 PyObject *locals = globals;
620 PyObject *py_error = NULL;
621
622 if (in_string != NULL)
623 {
624 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
625 if (compiled_node)
626 {
627 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
628 if (compiled_code)
629 {
630 py_return = PyEval_EvalCode (compiled_code, globals, locals);
631 if (py_return != NULL)
632 {
633 success = true;
634 Py_DECREF (py_return);
635 }
636 }
637 }
638 }
639
640 py_error = PyErr_Occurred ();
641 if (py_error != NULL)
642 {
643 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
644 PyErr_Print ();
645 PyErr_Clear();
646 success = false;
647 }
648
649 return success;
650}
651
652static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
653
654size_t
655ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
656(
657 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000658 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000659 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000660 const char *bytes,
661 size_t bytes_len
662)
663{
664 static StringList commands_in_progress;
665
Greg Clayton63094e02010-06-23 01:19:29 +0000666 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000667 if (out_fh == NULL)
668 out_fh = stdout;
669
Chris Lattner24943d22010-06-08 16:52:24 +0000670 switch (notification)
671 {
672 case eInputReaderActivate:
673 {
674 commands_in_progress.Clear();
675 if (out_fh)
676 {
677 ::fprintf (out_fh, "%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000678 if (reader.GetPrompt())
679 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +0000680 ::fflush (out_fh);
Chris Lattner24943d22010-06-08 16:52:24 +0000681 }
682 }
683 break;
684
685 case eInputReaderDeactivate:
686 break;
687
688 case eInputReaderReactivate:
Greg Clayton63094e02010-06-23 01:19:29 +0000689 if (reader.GetPrompt() && out_fh)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000690 {
Greg Clayton63094e02010-06-23 01:19:29 +0000691 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +0000692 ::fflush (out_fh);
693 }
Chris Lattner24943d22010-06-08 16:52:24 +0000694 break;
695
696 case eInputReaderGotToken:
697 {
698 std::string temp_string (bytes, bytes_len);
699 commands_in_progress.AppendString (temp_string.c_str());
Greg Clayton63094e02010-06-23 01:19:29 +0000700 if (out_fh && !reader.IsDone() && reader.GetPrompt())
Caroline Ticef81b4c52010-10-27 18:34:42 +0000701 {
Greg Clayton63094e02010-06-23 01:19:29 +0000702 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +0000703 ::fflush (out_fh);
704 }
Chris Lattner24943d22010-06-08 16:52:24 +0000705 }
706 break;
707
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000708 case eInputReaderEndOfFile:
709 case eInputReaderInterrupt:
710 // Control-c (SIGINT) & control-d both mean finish & exit.
711 reader.SetIsDone(true);
712
713 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
714 if (notification == eInputReaderInterrupt)
715 commands_in_progress.Clear();
716
717 // Fall through here...
718
Chris Lattner24943d22010-06-08 16:52:24 +0000719 case eInputReaderDone:
720 {
721 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
722 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
723 data_ap->user_source.AppendList (commands_in_progress);
724 if (data_ap.get())
725 {
Greg Clayton63094e02010-06-23 01:19:29 +0000726 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +0000727 if (interpreter)
728 {
729 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
730 data_ap->script_source))
731 {
732 if (data_ap->script_source.GetSize() == 1)
733 {
734 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
735 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
736 }
737 }
Caroline Ticeb447e842010-09-21 19:25:28 +0000738 else
Caroline Tice5136f942010-09-27 21:35:15 +0000739 ::fprintf (out_fh, "Warning: No command attached to breakpoint.\n");
Chris Lattner24943d22010-06-08 16:52:24 +0000740 }
741 else
742 {
743 // FIXME: Error processing.
744 }
745 }
746 }
747 break;
748
749 }
750
751 return bytes_len;
752}
753
754void
Greg Clayton238c0a12010-09-18 01:14:36 +0000755ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +0000756 CommandReturnObject &result)
757{
Greg Clayton238c0a12010-09-18 01:14:36 +0000758 Debugger &debugger = m_interpreter.GetDebugger();
Greg Clayton63094e02010-06-23 01:19:29 +0000759 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000760
761 if (reader_sp)
762 {
763 Error err = reader_sp->Initialize (
764 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
765 bp_options, // baton
766 eInputReaderGranularityLine, // token size, for feeding data to callback function
767 "DONE", // end token
768 "> ", // prompt
769 true); // echo input
770
771 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +0000772 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +0000773 else
774 {
775 result.AppendError (err.AsCString());
776 result.SetStatus (eReturnStatusFailed);
777 }
778 }
779 else
780 {
781 result.AppendError("out of memory");
782 result.SetStatus (eReturnStatusFailed);
783 }
784}
785
Johnny Chen3e0571b2010-09-11 00:23:59 +0000786// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +0000787void
Greg Clayton238c0a12010-09-18 01:14:36 +0000788ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +0000789 const char *oneliner)
790{
791 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
792
793 // It's necessary to set both user_source and script_source to the oneliner.
794 // The former is used to generate callback description (as in breakpoint command list)
795 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +0000796
Johnny Chend1c2dca2010-09-10 18:21:10 +0000797 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +0000798
Caroline Tice5136f942010-09-27 21:35:15 +0000799 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
800 {
801 if (data_ap->script_source.GetSize() == 1)
802 {
803 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
804 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
805 }
806 }
807
Johnny Chend1c2dca2010-09-10 18:21:10 +0000808 return;
809}
810
Chris Lattner24943d22010-06-08 16:52:24 +0000811bool
812ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
813{
814 // Convert StringList to one long, newline delimited, const char *.
815 std::string function_def_string;
816
817 int num_lines = function_def.GetSize();
818
819 for (int i = 0; i < num_lines; ++i)
820 {
821 function_def_string.append (function_def.GetStringAtIndex(i));
822 if (function_def_string.at (function_def_string.length() - 1) != '\n')
823 function_def_string.append ("\n");
824
825 }
826
827 return ExecuteMultipleLines (function_def_string.c_str());
828}
829
830bool
831ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
832{
833 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000834 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000835 int num_lines = user_input.GetSize ();
836 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +0000837
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000838 // Check to see if we have any data; if not, just return.
839 if (user_input.GetSize() == 0)
840 return false;
841
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000842 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
843 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +0000844
Caroline Ticeb447e842010-09-21 19:25:28 +0000845
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000846 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
847 ++num_created_functions;
848 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +0000849
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000850 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +0000851 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +0000852
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000853 // Create the function name & definition string.
854
855 sstr.Printf ("def %s (frame, bp_loc):", auto_generated_function_name.c_str());
856 auto_generated_function.AppendString (sstr.GetData());
857
858 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +0000859
860 for (int i = 0; i < num_lines; ++i)
861 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000862 sstr.Clear ();
863 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
864 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +0000865 }
Chris Lattner24943d22010-06-08 16:52:24 +0000866
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000867 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +0000868
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000869 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +0000870 {
Caroline Ticeb447e842010-09-21 19:25:28 +0000871 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000872 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000873
874 // Store the name of the auto-generated function to be called.
875
876 callback_data.AppendString (auto_generated_function_name.c_str());
877 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000878}
879
Greg Clayton5144f382010-10-07 17:14:24 +0000880bool
881ScriptInterpreterPython::BreakpointCallbackFunction
882(
883 void *baton,
884 StoppointCallbackContext *context,
885 user_id_t break_id,
886 user_id_t break_loc_id
887)
888{
889 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
890 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
891
892 if (python_function_name != NULL
893 && python_function_name[0] != '\0')
894 {
895 Thread *thread = context->exe_ctx.thread;
896 Target *target = context->exe_ctx.target;
897 const StackFrameSP stop_frame_sp = thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame);
898 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
899 const BreakpointLocationSP bp_loc_sp = breakpoint_sp->FindLocationByID (break_loc_id);
900
901 SBFrame sb_frame (stop_frame_sp);
902 SBBreakpointLocation sb_bp_loc (bp_loc_sp);
903
904 if (sb_bp_loc.IsValid() || sb_frame.IsValid())
905 return LLDBSWIGPythonBreakpointCallbackFunction (python_function_name, sb_frame, sb_bp_loc);
906 }
907 // We currently always true so we stop in case anything goes wrong when
908 // trying to call the script function
909 return true;
910}
Caroline Tice2ade6112010-11-10 19:18:14 +0000911
912lldb::thread_result_t
913ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
914{
915 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
916
917 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
918
919 if (log)
920 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
921
922 char error_str[1024];
923 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
924 if (pty_slave_name != NULL)
925 {
926 StreamString run_string;
927 PyRun_SimpleString ("save_stderr = sys.stderr");
928 PyRun_SimpleString ("sys.stderr = sys.stdout");
929 PyRun_SimpleString ("save_stdin = sys.stdin");
930 run_string.Printf ("sys.stdin = open ('%s', 'r')", pty_slave_name);
931 PyRun_SimpleString (run_string.GetData());
Caroline Tice2ade6112010-11-10 19:18:14 +0000932
933 // The following call drops into the embedded interpreter loop and stays there until the
934 // user chooses to exit from the Python interpreter.
935 script_interpreter->ExecuteOneLine ("run_python_interpreter(ConsoleDict)", NULL);
936
937 PyRun_SimpleString ("sys.stdin = save_stdin");
938 PyRun_SimpleString ("sys.stderr = save_stderr");
939 }
940
941 if (script_interpreter->m_embedded_thread_input_reader_sp)
942 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
943
944 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
945
946 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
947 if (log)
948 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
949
950
951 // Clean up the input reader and make the debugger pop it off the stack.
952 Debugger &debugger = script_interpreter->m_interpreter.GetDebugger();
953 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
954 script_interpreter->m_embedded_thread_input_reader_sp.reset();
955 debugger.PopInputReader (reader_sp);
956
957 return NULL;
958}
959
960
961