Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 1 | //===-- ScriptInterpreterPython.cpp -----------------------------*- C++ -*-===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | |
| 10 | // In order to guarantee correct working with Python, Python.h *MUST* be |
| 11 | // the *FIRST* header file included: |
| 12 | |
| 13 | #include <Python.h> |
| 14 | |
| 15 | #include "lldb/Interpreter/ScriptInterpreterPython.h" |
| 16 | |
| 17 | |
| 18 | #include <sys/ioctl.h> |
| 19 | #include <termios.h> |
| 20 | #include <stdlib.h> |
| 21 | #include <stdio.h> |
| 22 | |
| 23 | #include <string> |
| 24 | |
| 25 | #include "lldb/Breakpoint/Breakpoint.h" |
| 26 | #include "lldb/Breakpoint/BreakpointLocation.h" |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 27 | #include "lldb/Breakpoint/StoppointCallbackContext.h" |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 28 | #include "lldb/Core/Debugger.h" |
| 29 | #include "lldb/Core/FileSpec.h" |
| 30 | #include "lldb/Core/InputReader.h" |
| 31 | #include "lldb/Core/Stream.h" |
| 32 | #include "lldb/Core/StreamString.h" |
| 33 | #include "lldb/Core/Timer.h" |
| 34 | #include "lldb/Host/Host.h" |
| 35 | #include "lldb/Interpreter/CommandInterpreter.h" |
| 36 | #include "lldb/Interpreter/CommandReturnObject.h" |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 37 | #include "lldb/Core/Debugger.h" |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 38 | #include "lldb/Target/Process.h" |
| 39 | |
Greg Clayton | 121f331 | 2010-07-07 18:40:03 +0000 | [diff] [blame] | 40 | // This function is in the C++ output file generated by SWIG after it is |
| 41 | // run on all of the headers in "lldb/API/SB*.h" |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 42 | extern "C" void init_lldb (void); |
| 43 | |
| 44 | using namespace lldb; |
| 45 | using namespace lldb_private; |
| 46 | |
| 47 | const char embedded_interpreter_string[] = |
| 48 | "import readline\n\ |
| 49 | import code\n\ |
| 50 | import sys\n\ |
| 51 | import traceback\n\ |
| 52 | \n\ |
| 53 | class SimpleREPL(code.InteractiveConsole):\n\ |
| 54 | def __init__(self, prompt, dict):\n\ |
| 55 | code.InteractiveConsole.__init__(self,dict)\n\ |
| 56 | self.prompt = prompt\n\ |
| 57 | self.loop_exit = False\n\ |
| 58 | self.dict = dict\n\ |
| 59 | \n\ |
| 60 | def interact(self):\n\ |
| 61 | try:\n\ |
| 62 | sys.ps1\n\ |
| 63 | except AttributeError:\n\ |
| 64 | sys.ps1 = \">>> \"\n\ |
| 65 | try:\n\ |
| 66 | sys.ps2\n\ |
| 67 | except AttributeError:\n\ |
| 68 | sys.ps2 = \"... \"\n\ |
| 69 | \n\ |
| 70 | while not self.loop_exit:\n\ |
| 71 | try:\n\ |
| 72 | self.read_py_command()\n\ |
| 73 | except (SystemExit, EOFError):\n\ |
| 74 | # EOF while in Python just breaks out to top level.\n\ |
| 75 | self.write('\\n')\n\ |
| 76 | self.loop_exit = True\n\ |
| 77 | break\n\ |
| 78 | except KeyboardInterrupt:\n\ |
| 79 | self.write(\"\\nKeyboardInterrupt\\n\")\n\ |
| 80 | self.resetbuffer()\n\ |
| 81 | more = 0\n\ |
| 82 | except:\n\ |
| 83 | traceback.print_exc()\n\ |
| 84 | \n\ |
| 85 | def process_input (self, in_str):\n\ |
| 86 | # Canonicalize the format of the input string\n\ |
| 87 | temp_str = in_str\n\ |
| 88 | temp_str.strip(' \t')\n\ |
| 89 | words = temp_str.split()\n\ |
| 90 | temp_str = ('').join(words)\n\ |
| 91 | \n\ |
| 92 | # Check the input string to see if it was the quit\n\ |
| 93 | # command. If so, intercept it, so that it doesn't\n\ |
| 94 | # close stdin on us!\n\ |
Jason Molenda | a8a5e56 | 2010-06-09 21:56:00 +0000 | [diff] [blame] | 95 | if (temp_str.lower() == \"quit()\" or temp_str.lower() == \"exit()\"):\n\ |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 96 | self.loop_exit = True\n\ |
| 97 | in_str = \"raise SystemExit \"\n\ |
| 98 | return in_str\n\ |
| 99 | \n\ |
| 100 | def my_raw_input (self, prompt):\n\ |
| 101 | stream = sys.stdout\n\ |
| 102 | stream.write (prompt)\n\ |
| 103 | stream.flush ()\n\ |
| 104 | try:\n\ |
| 105 | line = sys.stdin.readline()\n\ |
| 106 | except KeyboardInterrupt:\n\ |
| 107 | line = \" \\n\"\n\ |
| 108 | except (SystemExit, EOFError):\n\ |
| 109 | line = \"quit()\\n\"\n\ |
| 110 | if not line:\n\ |
| 111 | raise EOFError\n\ |
| 112 | if line[-1] == '\\n':\n\ |
| 113 | line = line[:-1]\n\ |
| 114 | return line\n\ |
| 115 | \n\ |
| 116 | def read_py_command(self):\n\ |
| 117 | # Read off a complete Python command.\n\ |
| 118 | more = 0\n\ |
| 119 | while 1:\n\ |
| 120 | if more:\n\ |
| 121 | prompt = sys.ps2\n\ |
| 122 | else:\n\ |
| 123 | prompt = sys.ps1\n\ |
| 124 | line = self.my_raw_input(prompt)\n\ |
| 125 | # Can be None if sys.stdin was redefined\n\ |
| 126 | encoding = getattr(sys.stdin, \"encoding\", None)\n\ |
| 127 | if encoding and not isinstance(line, unicode):\n\ |
| 128 | line = line.decode(encoding)\n\ |
| 129 | line = self.process_input (line)\n\ |
| 130 | more = self.push(line)\n\ |
| 131 | if not more:\n\ |
| 132 | break\n\ |
| 133 | \n\ |
| 134 | def run_python_interpreter (dict):\n\ |
| 135 | # Pass in the dictionary, for continuity from one session to the next.\n\ |
| 136 | repl = SimpleREPL('>>> ', dict)\n\ |
| 137 | repl.interact()\n"; |
| 138 | |
| 139 | static int |
| 140 | _check_and_flush (FILE *stream) |
| 141 | { |
| 142 | int prev_fail = ferror (stream); |
| 143 | return fflush (stream) || prev_fail ? EOF : 0; |
| 144 | } |
| 145 | |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 146 | ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) : |
Greg Clayton | 238c0a1 | 2010-09-18 01:14:36 +0000 | [diff] [blame^] | 147 | ScriptInterpreter (interpreter, eScriptLanguagePython), |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 148 | m_compiled_module (NULL), |
| 149 | m_termios_valid (false) |
| 150 | { |
| 151 | |
| 152 | Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); |
| 153 | // Find the module that owns this code and use that path we get to |
| 154 | // set the PYTHONPATH appropriately. |
| 155 | |
| 156 | FileSpec this_module (Host::GetModuleFileSpecForHostAddress ((void *)init_lldb)); |
| 157 | std::string python_path; |
| 158 | |
| 159 | if (this_module.GetDirectory()) |
| 160 | { |
| 161 | // Append the directory that the module that loaded this code |
| 162 | // belongs to |
| 163 | python_path += this_module.GetDirectory().AsCString(""); |
| 164 | |
| 165 | #if defined (__APPLE__) |
| 166 | // If we are running on MacOSX we might be in a framework and should |
| 167 | // add an appropriate path so Resource can be found in a bundle |
| 168 | |
| 169 | if (::strstr(this_module.GetDirectory().AsCString(""), ".framework")) |
| 170 | { |
| 171 | python_path.append(1, ':'); |
| 172 | python_path.append(this_module.GetDirectory().AsCString("")); |
| 173 | python_path.append("/Resources/Python"); |
| 174 | } |
| 175 | #endif |
| 176 | // The the PYTHONPATH environment variable so that Python can find |
| 177 | // our lldb.py module and our _lldb.so. |
| 178 | ::setenv ("PYTHONPATH", python_path.c_str(), 1); |
| 179 | } |
| 180 | |
| 181 | Py_Initialize (); |
| 182 | |
| 183 | PyObject *compiled_module = Py_CompileString (embedded_interpreter_string, "embedded_interpreter.py", |
| 184 | Py_file_input); |
| 185 | |
Eli Friedman | 3c90d99 | 2010-06-09 18:31:38 +0000 | [diff] [blame] | 186 | m_compiled_module = static_cast<void*>(compiled_module); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 187 | |
Greg Clayton | 121f331 | 2010-07-07 18:40:03 +0000 | [diff] [blame] | 188 | // This function is in the C++ output file generated by SWIG after it is |
| 189 | // run on all of the headers in "lldb/API/SB*.h" |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 190 | init_lldb (); |
| 191 | |
| 192 | // Update the path python uses to search for modules to include the current directory. |
| 193 | |
| 194 | int success = PyRun_SimpleString ("import sys"); |
| 195 | success = PyRun_SimpleString ("sys.path.append ('.')"); |
| 196 | if (success == 0) |
| 197 | { |
| 198 | // Import the Script Bridge module. |
Johnny Chen | 98bea86 | 2010-09-10 16:19:10 +0000 | [diff] [blame] | 199 | success = PyRun_SimpleString ("import lldb"); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 200 | } |
| 201 | |
| 202 | const char *pty_slave_name = GetScriptInterpreterPtyName (); |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 203 | FILE *out_fh = interpreter.GetDebugger().GetOutputFileHandle(); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 204 | |
Eli Friedman | 3c90d99 | 2010-06-09 18:31:38 +0000 | [diff] [blame] | 205 | PyObject *pmod = PyImport_ExecCodeModule( |
| 206 | const_cast<char*>("embedded_interpreter"), |
| 207 | static_cast<PyObject*>(m_compiled_module)); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 208 | if (pmod != NULL) |
| 209 | { |
| 210 | PyRun_SimpleString ("ConsoleDict = locals()"); |
| 211 | PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter"); |
| 212 | PyRun_SimpleString ("import sys"); |
| 213 | PyRun_SimpleString ("from termios import *"); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 214 | |
| 215 | StreamString run_string; |
| 216 | run_string.Printf ("new_stdin = open('%s', 'r')", pty_slave_name); |
| 217 | PyRun_SimpleString (run_string.GetData()); |
| 218 | PyRun_SimpleString ("sys.stdin = new_stdin"); |
| 219 | |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 220 | if (out_fh != NULL) |
| 221 | { |
| 222 | PyObject *new_sysout = PyFile_FromFile (out_fh, (char *) "", (char *) "w", |
| 223 | _check_and_flush); |
| 224 | PyObject *sysmod = PyImport_AddModule ("sys"); |
| 225 | PyObject *sysdict = PyModule_GetDict (sysmod); |
| 226 | |
| 227 | if ((new_sysout != NULL) |
| 228 | && (sysmod != NULL) |
| 229 | && (sysdict != NULL)) |
| 230 | { |
| 231 | PyDict_SetItemString (sysdict, "stdout", new_sysout); |
| 232 | } |
| 233 | |
| 234 | if (PyErr_Occurred()) |
| 235 | PyErr_Clear(); |
| 236 | } |
| 237 | |
| 238 | PyRun_SimpleString ("new_mode = tcgetattr(new_stdin)"); |
| 239 | PyRun_SimpleString ("new_mode[3] = new_mode[3] | ECHO | ICANON"); |
| 240 | PyRun_SimpleString ("new_mode[6][VEOF] = 255"); |
| 241 | PyRun_SimpleString ("tcsetattr (new_stdin, TCSANOW, new_mode)"); |
Caroline Tice | 558be58 | 2010-06-30 16:22:25 +0000 | [diff] [blame] | 242 | |
| 243 | run_string.Clear(); |
Johnny Chen | 98bea86 | 2010-09-10 16:19:10 +0000 | [diff] [blame] | 244 | run_string.Printf ("lldb.debugger_unique_id = %d", interpreter.GetDebugger().GetID()); |
Caroline Tice | 558be58 | 2010-06-30 16:22:25 +0000 | [diff] [blame] | 245 | PyRun_SimpleString (run_string.GetData()); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 246 | } |
| 247 | |
| 248 | |
| 249 | } |
| 250 | |
| 251 | ScriptInterpreterPython::~ScriptInterpreterPython () |
| 252 | { |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 253 | Py_Finalize (); |
| 254 | } |
| 255 | |
Johnny Chen | 60dde64 | 2010-07-30 22:33:14 +0000 | [diff] [blame] | 256 | bool |
Greg Clayton | 238c0a1 | 2010-09-18 01:14:36 +0000 | [diff] [blame^] | 257 | ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result) |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 258 | { |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 259 | if (command) |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 260 | { |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 261 | int success; |
| 262 | |
| 263 | success = PyRun_SimpleString (command); |
Johnny Chen | 60dde64 | 2010-07-30 22:33:14 +0000 | [diff] [blame] | 264 | if (success == 0) |
| 265 | return true; |
| 266 | |
| 267 | // The one-liner failed. Append the error message. |
| 268 | if (result) |
| 269 | result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command); |
| 270 | return false; |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 271 | } |
Johnny Chen | 60dde64 | 2010-07-30 22:33:14 +0000 | [diff] [blame] | 272 | |
| 273 | if (result) |
| 274 | result->AppendError ("empty command passed to python\n"); |
| 275 | return false; |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 276 | } |
| 277 | |
| 278 | |
| 279 | |
| 280 | size_t |
| 281 | ScriptInterpreterPython::InputReaderCallback |
| 282 | ( |
| 283 | void *baton, |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 284 | InputReader &reader, |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 285 | lldb::InputReaderAction notification, |
| 286 | const char *bytes, |
| 287 | size_t bytes_len |
| 288 | ) |
| 289 | { |
| 290 | if (baton == NULL) |
| 291 | return 0; |
| 292 | |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 293 | ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton; |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 294 | switch (notification) |
| 295 | { |
| 296 | case eInputReaderActivate: |
| 297 | { |
| 298 | // Save terminal settings if we can |
Caroline Tice | c95c6d1 | 2010-09-14 22:49:06 +0000 | [diff] [blame] | 299 | int input_fd; |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 300 | FILE *input_fh = reader.GetDebugger().GetInputFileHandle(); |
Caroline Tice | c95c6d1 | 2010-09-14 22:49:06 +0000 | [diff] [blame] | 301 | if (input_fh != NULL) |
| 302 | input_fd = ::fileno (input_fh); |
| 303 | else |
| 304 | input_fd = STDIN_FILENO; |
| 305 | |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 306 | script_interpreter->m_termios_valid = ::tcgetattr (input_fd, &script_interpreter->m_termios) == 0; |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 307 | struct termios tmp_termios; |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 308 | if (::tcgetattr (input_fd, &tmp_termios) == 0) |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 309 | { |
| 310 | tmp_termios.c_cc[VEOF] = _POSIX_VDISABLE; |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 311 | ::tcsetattr (input_fd, TCSANOW, &tmp_termios); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 312 | } |
| 313 | } |
| 314 | break; |
| 315 | |
| 316 | case eInputReaderDeactivate: |
| 317 | break; |
| 318 | |
| 319 | case eInputReaderReactivate: |
| 320 | break; |
| 321 | |
| 322 | case eInputReaderGotToken: |
| 323 | if (bytes && bytes_len) |
| 324 | { |
| 325 | if ((int) bytes[0] == 4) |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 326 | ::write (script_interpreter->GetMasterFileDescriptor(), "quit()", 6); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 327 | else |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 328 | ::write (script_interpreter->GetMasterFileDescriptor(), bytes, bytes_len); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 329 | } |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 330 | ::write (script_interpreter->GetMasterFileDescriptor(), "\n", 1); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 331 | break; |
| 332 | |
| 333 | case eInputReaderDone: |
| 334 | // Send a control D to the script interpreter |
| 335 | //::write (interpreter->GetMasterFileDescriptor(), "\nquit()\n", strlen("\nquit()\n")); |
| 336 | // Write a newline out to the reader output |
| 337 | //::fwrite ("\n", 1, 1, out_fh); |
| 338 | // Restore terminal settings if they were validly saved |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 339 | if (script_interpreter->m_termios_valid) |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 340 | { |
Caroline Tice | c95c6d1 | 2010-09-14 22:49:06 +0000 | [diff] [blame] | 341 | int input_fd; |
| 342 | FILE *input_fh = reader.GetDebugger().GetInputFileHandle(); |
| 343 | if (input_fh != NULL) |
| 344 | input_fd = ::fileno (input_fh); |
| 345 | else |
| 346 | input_fd = STDIN_FILENO; |
| 347 | |
| 348 | ::tcsetattr (input_fd, TCSANOW, &script_interpreter->m_termios); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 349 | } |
| 350 | break; |
| 351 | } |
| 352 | |
| 353 | return bytes_len; |
| 354 | } |
| 355 | |
| 356 | |
| 357 | void |
Greg Clayton | 238c0a1 | 2010-09-18 01:14:36 +0000 | [diff] [blame^] | 358 | ScriptInterpreterPython::ExecuteInterpreterLoop () |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 359 | { |
| 360 | Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); |
| 361 | |
Greg Clayton | 238c0a1 | 2010-09-18 01:14:36 +0000 | [diff] [blame^] | 362 | Debugger &debugger = m_interpreter.GetDebugger(); |
Caroline Tice | c95c6d1 | 2010-09-14 22:49:06 +0000 | [diff] [blame] | 363 | |
| 364 | // At the moment, the only time the debugger does not have an input file handle is when this is called |
| 365 | // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to |
| 366 | // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't |
| 367 | // do it. |
| 368 | |
| 369 | if (debugger.GetInputFileHandle() == NULL) |
| 370 | return; |
| 371 | |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 372 | InputReaderSP reader_sp (new InputReader(debugger)); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 373 | if (reader_sp) |
| 374 | { |
| 375 | Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback, |
| 376 | this, // baton |
| 377 | eInputReaderGranularityLine, // token size, to pass to callback function |
| 378 | NULL, // end token |
| 379 | NULL, // prompt |
| 380 | true)); // echo input |
| 381 | |
| 382 | if (error.Success()) |
| 383 | { |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 384 | debugger.PushInputReader (reader_sp); |
Greg Clayton | 238c0a1 | 2010-09-18 01:14:36 +0000 | [diff] [blame^] | 385 | ExecuteOneLine ("run_python_interpreter(ConsoleDict)", NULL); |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 386 | debugger.PopInputReader (reader_sp); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 387 | } |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | bool |
| 392 | ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string, |
| 393 | ScriptInterpreter::ReturnType return_type, |
| 394 | void *ret_value) |
| 395 | { |
| 396 | PyObject *py_return = NULL; |
| 397 | PyObject *mainmod = PyImport_AddModule ("__main__"); |
| 398 | PyObject *globals = PyModule_GetDict (mainmod); |
| 399 | PyObject *locals = globals; |
| 400 | PyObject *py_error = NULL; |
| 401 | bool ret_success; |
| 402 | int success; |
| 403 | |
| 404 | if (in_string != NULL) |
| 405 | { |
| 406 | py_return = PyRun_String (in_string, Py_eval_input, globals, locals); |
| 407 | if (py_return == NULL) |
| 408 | { |
| 409 | py_error = PyErr_Occurred (); |
| 410 | if (py_error != NULL) |
| 411 | PyErr_Clear (); |
| 412 | |
| 413 | py_return = PyRun_String (in_string, Py_single_input, globals, locals); |
| 414 | } |
| 415 | |
| 416 | if (py_return != NULL) |
| 417 | { |
| 418 | switch (return_type) |
| 419 | { |
| 420 | case eCharPtr: // "char *" |
| 421 | { |
| 422 | const char format[3] = "s#"; |
| 423 | success = PyArg_Parse (py_return, format, (char **) &ret_value); |
| 424 | break; |
| 425 | } |
| 426 | case eBool: |
| 427 | { |
| 428 | const char format[2] = "b"; |
| 429 | success = PyArg_Parse (py_return, format, (bool *) ret_value); |
| 430 | break; |
| 431 | } |
| 432 | case eShortInt: |
| 433 | { |
| 434 | const char format[2] = "h"; |
| 435 | success = PyArg_Parse (py_return, format, (short *) ret_value); |
| 436 | break; |
| 437 | } |
| 438 | case eShortIntUnsigned: |
| 439 | { |
| 440 | const char format[2] = "H"; |
| 441 | success = PyArg_Parse (py_return, format, (unsigned short *) ret_value); |
| 442 | break; |
| 443 | } |
| 444 | case eInt: |
| 445 | { |
| 446 | const char format[2] = "i"; |
| 447 | success = PyArg_Parse (py_return, format, (int *) ret_value); |
| 448 | break; |
| 449 | } |
| 450 | case eIntUnsigned: |
| 451 | { |
| 452 | const char format[2] = "I"; |
| 453 | success = PyArg_Parse (py_return, format, (unsigned int *) ret_value); |
| 454 | break; |
| 455 | } |
| 456 | case eLongInt: |
| 457 | { |
| 458 | const char format[2] = "l"; |
| 459 | success = PyArg_Parse (py_return, format, (long *) ret_value); |
| 460 | break; |
| 461 | } |
| 462 | case eLongIntUnsigned: |
| 463 | { |
| 464 | const char format[2] = "k"; |
| 465 | success = PyArg_Parse (py_return, format, (unsigned long *) ret_value); |
| 466 | break; |
| 467 | } |
| 468 | case eLongLong: |
| 469 | { |
| 470 | const char format[2] = "L"; |
| 471 | success = PyArg_Parse (py_return, format, (long long *) ret_value); |
| 472 | break; |
| 473 | } |
| 474 | case eLongLongUnsigned: |
| 475 | { |
| 476 | const char format[2] = "K"; |
| 477 | success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value); |
| 478 | break; |
| 479 | } |
| 480 | case eFloat: |
| 481 | { |
| 482 | const char format[2] = "f"; |
| 483 | success = PyArg_Parse (py_return, format, (float *) ret_value); |
| 484 | break; |
| 485 | } |
| 486 | case eDouble: |
| 487 | { |
| 488 | const char format[2] = "d"; |
| 489 | success = PyArg_Parse (py_return, format, (double *) ret_value); |
| 490 | break; |
| 491 | } |
| 492 | case eChar: |
| 493 | { |
| 494 | const char format[2] = "c"; |
| 495 | success = PyArg_Parse (py_return, format, (char *) ret_value); |
| 496 | break; |
| 497 | } |
| 498 | default: |
| 499 | {} |
| 500 | } |
| 501 | Py_DECREF (py_return); |
| 502 | if (success) |
| 503 | ret_success = true; |
| 504 | else |
| 505 | ret_success = false; |
| 506 | } |
| 507 | } |
| 508 | |
| 509 | py_error = PyErr_Occurred(); |
| 510 | if (py_error != NULL) |
| 511 | { |
| 512 | if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError)) |
| 513 | PyErr_Print (); |
| 514 | PyErr_Clear(); |
| 515 | ret_success = false; |
| 516 | } |
| 517 | |
| 518 | return ret_success; |
| 519 | } |
| 520 | |
| 521 | bool |
| 522 | ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string) |
| 523 | { |
| 524 | bool success = false; |
| 525 | PyObject *py_return = NULL; |
| 526 | PyObject *mainmod = PyImport_AddModule ("__main__"); |
| 527 | PyObject *globals = PyModule_GetDict (mainmod); |
| 528 | PyObject *locals = globals; |
| 529 | PyObject *py_error = NULL; |
| 530 | |
| 531 | if (in_string != NULL) |
| 532 | { |
| 533 | struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input); |
| 534 | if (compiled_node) |
| 535 | { |
| 536 | PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py"); |
| 537 | if (compiled_code) |
| 538 | { |
| 539 | py_return = PyEval_EvalCode (compiled_code, globals, locals); |
| 540 | if (py_return != NULL) |
| 541 | { |
| 542 | success = true; |
| 543 | Py_DECREF (py_return); |
| 544 | } |
| 545 | } |
| 546 | } |
| 547 | } |
| 548 | |
| 549 | py_error = PyErr_Occurred (); |
| 550 | if (py_error != NULL) |
| 551 | { |
| 552 | if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError)) |
| 553 | PyErr_Print (); |
| 554 | PyErr_Clear(); |
| 555 | success = false; |
| 556 | } |
| 557 | |
| 558 | return success; |
| 559 | } |
| 560 | |
| 561 | static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end."; |
| 562 | |
| 563 | size_t |
| 564 | ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback |
| 565 | ( |
| 566 | void *baton, |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 567 | InputReader &reader, |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 568 | lldb::InputReaderAction notification, |
| 569 | const char *bytes, |
| 570 | size_t bytes_len |
| 571 | ) |
| 572 | { |
| 573 | static StringList commands_in_progress; |
| 574 | |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 575 | FILE *out_fh = reader.GetDebugger().GetOutputFileHandle(); |
Caroline Tice | c95c6d1 | 2010-09-14 22:49:06 +0000 | [diff] [blame] | 576 | if (out_fh == NULL) |
| 577 | out_fh = stdout; |
| 578 | |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 579 | switch (notification) |
| 580 | { |
| 581 | case eInputReaderActivate: |
| 582 | { |
| 583 | commands_in_progress.Clear(); |
| 584 | if (out_fh) |
| 585 | { |
| 586 | ::fprintf (out_fh, "%s\n", g_reader_instructions); |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 587 | if (reader.GetPrompt()) |
| 588 | ::fprintf (out_fh, "%s", reader.GetPrompt()); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 589 | } |
| 590 | } |
| 591 | break; |
| 592 | |
| 593 | case eInputReaderDeactivate: |
| 594 | break; |
| 595 | |
| 596 | case eInputReaderReactivate: |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 597 | if (reader.GetPrompt() && out_fh) |
| 598 | ::fprintf (out_fh, "%s", reader.GetPrompt()); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 599 | break; |
| 600 | |
| 601 | case eInputReaderGotToken: |
| 602 | { |
| 603 | std::string temp_string (bytes, bytes_len); |
| 604 | commands_in_progress.AppendString (temp_string.c_str()); |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 605 | if (out_fh && !reader.IsDone() && reader.GetPrompt()) |
| 606 | ::fprintf (out_fh, "%s", reader.GetPrompt()); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 607 | } |
| 608 | break; |
| 609 | |
| 610 | case eInputReaderDone: |
| 611 | { |
| 612 | BreakpointOptions *bp_options = (BreakpointOptions *)baton; |
| 613 | std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData()); |
| 614 | data_ap->user_source.AppendList (commands_in_progress); |
| 615 | if (data_ap.get()) |
| 616 | { |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 617 | ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter(); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 618 | if (interpreter) |
| 619 | { |
| 620 | if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source, |
| 621 | data_ap->script_source)) |
| 622 | { |
| 623 | if (data_ap->script_source.GetSize() == 1) |
| 624 | { |
| 625 | BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release())); |
| 626 | bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp); |
| 627 | } |
| 628 | } |
| 629 | } |
| 630 | else |
| 631 | { |
| 632 | // FIXME: Error processing. |
| 633 | } |
| 634 | } |
| 635 | } |
| 636 | break; |
| 637 | |
| 638 | } |
| 639 | |
| 640 | return bytes_len; |
| 641 | } |
| 642 | |
| 643 | void |
Greg Clayton | 238c0a1 | 2010-09-18 01:14:36 +0000 | [diff] [blame^] | 644 | ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options, |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 645 | CommandReturnObject &result) |
| 646 | { |
Greg Clayton | 238c0a1 | 2010-09-18 01:14:36 +0000 | [diff] [blame^] | 647 | Debugger &debugger = m_interpreter.GetDebugger(); |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 648 | InputReaderSP reader_sp (new InputReader (debugger)); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 649 | |
| 650 | if (reader_sp) |
| 651 | { |
| 652 | Error err = reader_sp->Initialize ( |
| 653 | ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback, |
| 654 | bp_options, // baton |
| 655 | eInputReaderGranularityLine, // token size, for feeding data to callback function |
| 656 | "DONE", // end token |
| 657 | "> ", // prompt |
| 658 | true); // echo input |
| 659 | |
| 660 | if (err.Success()) |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 661 | debugger.PushInputReader (reader_sp); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 662 | else |
| 663 | { |
| 664 | result.AppendError (err.AsCString()); |
| 665 | result.SetStatus (eReturnStatusFailed); |
| 666 | } |
| 667 | } |
| 668 | else |
| 669 | { |
| 670 | result.AppendError("out of memory"); |
| 671 | result.SetStatus (eReturnStatusFailed); |
| 672 | } |
| 673 | } |
| 674 | |
Johnny Chen | 3e0571b | 2010-09-11 00:23:59 +0000 | [diff] [blame] | 675 | // Set a Python one-liner as the callback for the breakpoint. |
Johnny Chen | d1c2dca | 2010-09-10 18:21:10 +0000 | [diff] [blame] | 676 | void |
Greg Clayton | 238c0a1 | 2010-09-18 01:14:36 +0000 | [diff] [blame^] | 677 | ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options, |
Johnny Chen | d1c2dca | 2010-09-10 18:21:10 +0000 | [diff] [blame] | 678 | const char *oneliner) |
| 679 | { |
| 680 | std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData()); |
| 681 | |
| 682 | // It's necessary to set both user_source and script_source to the oneliner. |
| 683 | // The former is used to generate callback description (as in breakpoint command list) |
| 684 | // while the latter is used for Python to interpret during the actual callback. |
| 685 | data_ap->user_source.AppendString (oneliner); |
| 686 | data_ap->script_source.AppendString (oneliner); |
| 687 | |
| 688 | BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release())); |
| 689 | bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp); |
| 690 | |
| 691 | return; |
| 692 | } |
| 693 | |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 694 | bool |
| 695 | ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def) |
| 696 | { |
| 697 | // Convert StringList to one long, newline delimited, const char *. |
| 698 | std::string function_def_string; |
| 699 | |
| 700 | int num_lines = function_def.GetSize(); |
| 701 | |
| 702 | for (int i = 0; i < num_lines; ++i) |
| 703 | { |
| 704 | function_def_string.append (function_def.GetStringAtIndex(i)); |
| 705 | if (function_def_string.at (function_def_string.length() - 1) != '\n') |
| 706 | function_def_string.append ("\n"); |
| 707 | |
| 708 | } |
| 709 | |
| 710 | return ExecuteMultipleLines (function_def_string.c_str()); |
| 711 | } |
| 712 | |
| 713 | bool |
| 714 | ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data) |
| 715 | { |
| 716 | static int num_created_functions = 0; |
| 717 | |
| 718 | user_input.RemoveBlankLines (); |
| 719 | int num_lines = user_input.GetSize(); |
| 720 | std::string last_function_call; |
| 721 | |
| 722 | // Go through lines of input looking for any function definitions. For each function definition found, |
| 723 | // export the function definition to Python, create a potential function call for the function, and |
| 724 | // mark the lines of the function to be removed from the user input. |
| 725 | |
| 726 | for (int i = 0; i < num_lines; ++i) |
| 727 | { |
| 728 | int function_start = i; |
| 729 | std::string current_str = user_input.GetStringAtIndex (i); |
| 730 | const char *current_line = current_str.c_str(); |
| 731 | int len = 0; |
| 732 | if (current_line) |
| 733 | len = strlen (current_line); |
| 734 | |
| 735 | // Check to see if the current line is the start of a Python function definition. |
| 736 | if (len > 4 && strncmp (current_line, "def ", 4) == 0) |
| 737 | { |
| 738 | // We've found the first line of a function. First, get the function name. |
| 739 | |
| 740 | // Skip over the 'def '. |
| 741 | char *start = (char *) current_line + 4; |
| 742 | |
| 743 | // Skip over white space. |
| 744 | while (start[0] == ' ' || start[0] == '\t') |
| 745 | ++start; |
| 746 | |
| 747 | // Find the end of the function name. |
| 748 | char *end = start; |
| 749 | while (isalnum (end[0]) || end[0] == '_') |
| 750 | ++end; |
| 751 | |
| 752 | int name_len = end - start; |
| 753 | std::string func_name = current_str.substr (4, name_len); |
| 754 | |
| 755 | // Now to find the last line of the function. That will be the first line that does not begin with |
| 756 | // any white space (thanks to Python's indentation rules). |
| 757 | ++i; |
| 758 | bool found = false; |
| 759 | while (i < num_lines && !found) |
| 760 | { |
| 761 | std::string next_str = user_input.GetStringAtIndex (i); |
| 762 | const char *next_line = next_str.c_str(); |
| 763 | if (next_line[0] != ' ' && next_line[0] != '\t') |
| 764 | found = true; |
| 765 | else |
| 766 | ++i; |
| 767 | } |
| 768 | if (found) |
| 769 | --i; // Make 'i' correspond to the last line of the function. |
| 770 | int function_end = i; |
| 771 | |
| 772 | // Special case: All of user_input is one big function definition. |
| 773 | if ((function_start == 0) && (function_end == (num_lines - 1))) |
| 774 | { |
| 775 | ExportFunctionDefinitionToInterpreter (user_input); |
| 776 | last_function_call = func_name + " ()"; |
| 777 | callback_data.AppendString (last_function_call.c_str()); |
| 778 | return callback_data.GetSize() > 0; |
| 779 | } |
| 780 | else |
| 781 | { |
| 782 | // Make a copy of the function definition: |
| 783 | StringList new_function; |
| 784 | for (int k = function_start; k <= function_end; ++k) |
| 785 | { |
| 786 | new_function.AppendString (user_input.GetStringAtIndex (k)); |
| 787 | // Mark the string to be deleted from user_input. |
| 788 | user_input.DeleteStringAtIndex (k); |
| 789 | user_input.InsertStringAtIndex (k, "<lldb_delete>"); |
| 790 | } |
| 791 | ExportFunctionDefinitionToInterpreter (new_function); |
| 792 | last_function_call = func_name + " ()"; |
| 793 | } |
| 794 | } |
| 795 | } |
| 796 | |
| 797 | // Now instead of trying to really delete the marked lines from user_input, we will just copy all the |
| 798 | // unmarked lines into a new StringList. |
| 799 | |
| 800 | StringList new_user_input; |
| 801 | |
| 802 | for (int i = 0; i < num_lines; ++i) |
| 803 | { |
| 804 | std::string current_string = user_input.GetStringAtIndex (i); |
| 805 | if (current_string.compare (0, 13, "<lldb_delete>") == 0) |
| 806 | continue; |
| 807 | |
| 808 | new_user_input.AppendString (current_string.c_str()); |
| 809 | } |
| 810 | |
| 811 | num_lines = new_user_input.GetSize(); |
| 812 | |
| 813 | if (num_lines > 0) |
| 814 | { |
| 815 | if (num_lines == 1 |
| 816 | && strchr (new_user_input.GetStringAtIndex(0), '\n') == NULL) |
| 817 | { |
| 818 | // If there's only one line of input, and it doesn't contain any newline characters.... |
| 819 | callback_data.AppendString (new_user_input.GetStringAtIndex (0)); |
| 820 | } |
| 821 | else |
| 822 | { |
| 823 | // Create the new function name. |
| 824 | StreamString func_name; |
| 825 | func_name.Printf ("lldb_bp_callback_func_%d", num_created_functions); |
| 826 | //std::string func_name = "lldb_bp_callback_func_" + num_created_functions; |
| 827 | ++num_created_functions; |
| 828 | |
| 829 | // Create the function call for the new function. |
| 830 | last_function_call = func_name.GetString() + " ()"; |
| 831 | |
| 832 | // Create the Python function definition line (which will have to be inserted at the beginning of |
| 833 | // the function). |
| 834 | std::string def_line = "def " + func_name.GetString() + " ():"; |
| 835 | |
| 836 | |
| 837 | // Indent all lines an additional four spaces (as they are now being put inside a function definition). |
| 838 | for (int i = 0; i < num_lines; ++i) |
| 839 | { |
| 840 | const char *temp_cstring = new_user_input.GetStringAtIndex(i); |
| 841 | std::string temp2 = " "; |
| 842 | temp2.append(temp_cstring); |
| 843 | new_user_input.DeleteStringAtIndex (i); |
| 844 | new_user_input.InsertStringAtIndex (i, temp2.c_str()); |
| 845 | } |
| 846 | |
| 847 | // Insert the function definition line at the top of the new function. |
| 848 | new_user_input.InsertStringAtIndex (0, def_line.c_str()); |
| 849 | |
| 850 | ExportFunctionDefinitionToInterpreter (new_user_input); |
| 851 | callback_data.AppendString (last_function_call.c_str()); |
| 852 | } |
| 853 | } |
| 854 | else |
| 855 | { |
| 856 | if (!last_function_call.empty()) |
| 857 | callback_data.AppendString (last_function_call.c_str()); |
| 858 | } |
| 859 | |
| 860 | return callback_data.GetSize() > 0; |
| 861 | } |
| 862 | |
| 863 | bool |
| 864 | ScriptInterpreterPython::BreakpointCallbackFunction |
| 865 | ( |
| 866 | void *baton, |
| 867 | StoppointCallbackContext *context, |
| 868 | lldb::user_id_t break_id, |
| 869 | lldb::user_id_t break_loc_id |
| 870 | ) |
| 871 | { |
| 872 | bool ret_value = true; |
| 873 | bool temp_bool; |
| 874 | |
| 875 | BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton; |
| 876 | |
| 877 | const char *python_string = bp_option_data->script_source.GetStringAtIndex(0); |
| 878 | |
| 879 | if (python_string != NULL) |
| 880 | { |
Greg Clayton | 63094e0 | 2010-06-23 01:19:29 +0000 | [diff] [blame] | 881 | bool success = context->exe_ctx.target->GetDebugger(). |
| 882 | GetCommandInterpreter(). |
| 883 | GetScriptInterpreter()->ExecuteOneLineWithReturn (python_string, |
| 884 | ScriptInterpreter::eBool, |
| 885 | (void *) &temp_bool); |
Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame] | 886 | if (success) |
| 887 | ret_value = temp_bool; |
| 888 | } |
| 889 | |
| 890 | return ret_value; |
| 891 | } |